LocalVariableTypesCalculator.java revision 1070:34d55faf0b3a
1/* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.codegen; 27 28import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN; 29import static jdk.nashorn.internal.ir.Expression.isAlwaysFalse; 30import static jdk.nashorn.internal.ir.Expression.isAlwaysTrue; 31 32import java.util.ArrayDeque; 33import java.util.ArrayList; 34import java.util.Collections; 35import java.util.Deque; 36import java.util.HashSet; 37import java.util.IdentityHashMap; 38import java.util.Iterator; 39import java.util.LinkedList; 40import java.util.List; 41import java.util.Map; 42import java.util.Set; 43import java.util.function.Function; 44import jdk.nashorn.internal.codegen.types.Type; 45import jdk.nashorn.internal.ir.AccessNode; 46import jdk.nashorn.internal.ir.BaseNode; 47import jdk.nashorn.internal.ir.BinaryNode; 48import jdk.nashorn.internal.ir.Block; 49import jdk.nashorn.internal.ir.BreakNode; 50import jdk.nashorn.internal.ir.BreakableNode; 51import jdk.nashorn.internal.ir.CaseNode; 52import jdk.nashorn.internal.ir.CatchNode; 53import jdk.nashorn.internal.ir.ContinueNode; 54import jdk.nashorn.internal.ir.Expression; 55import jdk.nashorn.internal.ir.ForNode; 56import jdk.nashorn.internal.ir.FunctionNode; 57import jdk.nashorn.internal.ir.FunctionNode.CompilationState; 58import jdk.nashorn.internal.ir.IdentNode; 59import jdk.nashorn.internal.ir.IfNode; 60import jdk.nashorn.internal.ir.IndexNode; 61import jdk.nashorn.internal.ir.JoinPredecessor; 62import jdk.nashorn.internal.ir.JoinPredecessorExpression; 63import jdk.nashorn.internal.ir.JumpStatement; 64import jdk.nashorn.internal.ir.LabelNode; 65import jdk.nashorn.internal.ir.LexicalContext; 66import jdk.nashorn.internal.ir.LexicalContextNode; 67import jdk.nashorn.internal.ir.LiteralNode; 68import jdk.nashorn.internal.ir.LocalVariableConversion; 69import jdk.nashorn.internal.ir.LoopNode; 70import jdk.nashorn.internal.ir.Node; 71import jdk.nashorn.internal.ir.PropertyNode; 72import jdk.nashorn.internal.ir.ReturnNode; 73import jdk.nashorn.internal.ir.RuntimeNode; 74import jdk.nashorn.internal.ir.RuntimeNode.Request; 75import jdk.nashorn.internal.ir.SplitReturn; 76import jdk.nashorn.internal.ir.Statement; 77import jdk.nashorn.internal.ir.SwitchNode; 78import jdk.nashorn.internal.ir.Symbol; 79import jdk.nashorn.internal.ir.TernaryNode; 80import jdk.nashorn.internal.ir.ThrowNode; 81import jdk.nashorn.internal.ir.TryNode; 82import jdk.nashorn.internal.ir.UnaryNode; 83import jdk.nashorn.internal.ir.VarNode; 84import jdk.nashorn.internal.ir.WhileNode; 85import jdk.nashorn.internal.ir.visitor.NodeVisitor; 86import jdk.nashorn.internal.parser.Token; 87import jdk.nashorn.internal.parser.TokenType; 88 89/** 90 * Calculates types for local variables. For purposes of local variable type calculation, the only types used are 91 * Undefined, boolean, int, long, double, and Object. The calculation eagerly widens types of local variable to their 92 * widest at control flow join points. 93 * TODO: investigate a more sophisticated solution that uses use/def information to only widens the type of a local 94 * variable to its widest used type after the join point. That would eliminate some widenings of undefined variables to 95 * object, most notably those used only in loops. We need a full liveness analysis for that. Currently, we can establish 96 * per-type liveness, which eliminates most of unwanted dead widenings. 97 */ 98final class LocalVariableTypesCalculator extends NodeVisitor<LexicalContext>{ 99 100 private static class JumpOrigin { 101 final JoinPredecessor node; 102 final Map<Symbol, LvarType> types; 103 104 JumpOrigin(final JoinPredecessor node, final Map<Symbol, LvarType> types) { 105 this.node = node; 106 this.types = types; 107 } 108 } 109 110 private static class JumpTarget { 111 private final List<JumpOrigin> origins = new LinkedList<>(); 112 private Map<Symbol, LvarType> types = Collections.emptyMap(); 113 114 void addOrigin(final JoinPredecessor originNode, final Map<Symbol, LvarType> originTypes) { 115 origins.add(new JumpOrigin(originNode, originTypes)); 116 this.types = getUnionTypes(this.types, originTypes); 117 } 118 } 119 private enum LvarType { 120 UNDEFINED(Type.UNDEFINED), 121 BOOLEAN(Type.BOOLEAN), 122 INT(Type.INT), 123 LONG(Type.LONG), 124 DOUBLE(Type.NUMBER), 125 OBJECT(Type.OBJECT); 126 127 private final Type type; 128 private LvarType(final Type type) { 129 this.type = type; 130 } 131 } 132 133 private static final Map<Type, LvarType> TO_LVAR_TYPE = new IdentityHashMap<>(); 134 135 static { 136 for(final LvarType lvarType: LvarType.values()) { 137 TO_LVAR_TYPE.put(lvarType.type, lvarType); 138 } 139 } 140 141 @SuppressWarnings("unchecked") 142 private static IdentityHashMap<Symbol, LvarType> cloneMap(final Map<Symbol, LvarType> map) { 143 return (IdentityHashMap<Symbol, LvarType>)((IdentityHashMap<?,?>)map).clone(); 144 } 145 146 private LocalVariableConversion createConversion(final Symbol symbol, final LvarType branchLvarType, 147 final Map<Symbol, LvarType> joinLvarTypes, final LocalVariableConversion next) { 148 final LvarType targetType = joinLvarTypes.get(symbol); 149 assert targetType != null; 150 if(targetType == branchLvarType) { 151 return next; 152 } 153 // NOTE: we could naively just use symbolIsUsed(symbol, branchLvarType) here, but that'd be wrong. While 154 // technically a conversion will read the value of the symbol with that type, but it will also write it to a new 155 // type, and that type might be dead (we can't know yet). For this reason, we don't treat conversion reads as 156 // real uses until we know their target type is live. If we didn't do this, and just did a symbolIsUsed here, 157 // we'd introduce false live variables which could nevertheless turn into dead ones in a subsequent 158 // deoptimization, causing a shift in the list of live locals that'd cause erroneous restoration of 159 // continuations (since RewriteException's byteCodeSlots carries an array and not a name-value map). 160 161 symbolIsConverted(symbol, branchLvarType, targetType); 162 //symbolIsUsed(symbol, branchLvarType); 163 return new LocalVariableConversion(symbol, branchLvarType.type, targetType.type, next); 164 } 165 166 private static Map<Symbol, LvarType> getUnionTypes(final Map<Symbol, LvarType> types1, final Map<Symbol, LvarType> types2) { 167 if(types1 == types2 || types1.isEmpty()) { 168 return types2; 169 } else if(types2.isEmpty()) { 170 return types1; 171 } 172 final Set<Symbol> commonSymbols = new HashSet<>(types1.keySet()); 173 commonSymbols.retainAll(types2.keySet()); 174 // We have a chance of returning an unmodified set if both sets have the same keys and one is strictly wider 175 // than the other. 176 final int commonSize = commonSymbols.size(); 177 final int types1Size = types1.size(); 178 final int types2Size = types2.size(); 179 if(commonSize == types1Size && commonSize == types2Size) { 180 boolean matches1 = true, matches2 = true; 181 Map<Symbol, LvarType> union = null; 182 for(final Symbol symbol: commonSymbols) { 183 final LvarType type1 = types1.get(symbol); 184 final LvarType type2 = types2.get(symbol); 185 final LvarType widest = widestLvarType(type1, type2); 186 if(widest != type1 && matches1) { 187 matches1 = false; 188 if(!matches2) { 189 union = cloneMap(types1); 190 } 191 } 192 if (widest != type2 && matches2) { 193 matches2 = false; 194 if(!matches1) { 195 union = cloneMap(types2); 196 } 197 } 198 if(!(matches1 || matches2) && union != null) { //remove overly enthusiastic "union can be null" warning 199 assert union != null; 200 union.put(symbol, widest); 201 } 202 } 203 return matches1 ? types1 : matches2 ? types2 : union; 204 } 205 // General case 206 final Map<Symbol, LvarType> union; 207 if(types1Size > types2Size) { 208 union = cloneMap(types1); 209 union.putAll(types2); 210 } else { 211 union = cloneMap(types2); 212 union.putAll(types1); 213 } 214 for(final Symbol symbol: commonSymbols) { 215 final LvarType type1 = types1.get(symbol); 216 final LvarType type2 = types2.get(symbol); 217 union.put(symbol, widestLvarType(type1, type2)); 218 } 219 return union; 220 } 221 222 private static void symbolIsUsed(final Symbol symbol, final LvarType type) { 223 if(type != LvarType.UNDEFINED) { 224 symbol.setHasSlotFor(type.type); 225 } 226 } 227 228 private static class SymbolConversions { 229 private static byte I2L = 1 << 0; 230 private static byte I2D = 1 << 1; 231 private static byte I2O = 1 << 2; 232 private static byte L2D = 1 << 3; 233 private static byte L2O = 1 << 4; 234 private static byte D2O = 1 << 5; 235 236 private byte conversions; 237 238 void recordConversion(final LvarType from, final LvarType to) { 239 switch(from) { 240 case UNDEFINED: 241 return; 242 case INT: 243 case BOOLEAN: 244 switch(to) { 245 case LONG: 246 recordConversion(I2L); 247 return; 248 case DOUBLE: 249 recordConversion(I2D); 250 return; 251 case OBJECT: 252 recordConversion(I2O); 253 return; 254 default: 255 illegalConversion(from, to); 256 return; 257 } 258 case LONG: 259 switch(to) { 260 case DOUBLE: 261 recordConversion(L2D); 262 return; 263 case OBJECT: 264 recordConversion(L2O); 265 return; 266 default: 267 illegalConversion(from, to); 268 return; 269 } 270 case DOUBLE: 271 if(to == LvarType.OBJECT) { 272 recordConversion(D2O); 273 } 274 return; 275 default: 276 illegalConversion(from, to); 277 } 278 } 279 280 private static void illegalConversion(final LvarType from, final LvarType to) { 281 throw new AssertionError("Invalid conversion from " + from + " to " + to); 282 } 283 284 void recordConversion(final byte convFlag) { 285 conversions = (byte)(conversions | convFlag); 286 } 287 288 boolean hasConversion(final byte convFlag) { 289 return (conversions & convFlag) != 0; 290 } 291 292 void calculateTypeLiveness(final Symbol symbol) { 293 if(symbol.hasSlotFor(Type.OBJECT)) { 294 if(hasConversion(D2O)) { 295 symbol.setHasSlotFor(Type.NUMBER); 296 } 297 if(hasConversion(L2O)) { 298 symbol.setHasSlotFor(Type.LONG); 299 } 300 if(hasConversion(I2O)) { 301 symbol.setHasSlotFor(Type.INT); 302 } 303 } 304 if(symbol.hasSlotFor(Type.NUMBER)) { 305 if(hasConversion(L2D)) { 306 symbol.setHasSlotFor(Type.LONG); 307 } 308 if(hasConversion(I2D)) { 309 symbol.setHasSlotFor(Type.INT); 310 } 311 } 312 if(symbol.hasSlotFor(Type.LONG)) { 313 if(hasConversion(I2L)) { 314 symbol.setHasSlotFor(Type.INT); 315 } 316 } 317 } 318 } 319 320 private void symbolIsConverted(final Symbol symbol, final LvarType from, final LvarType to) { 321 SymbolConversions conversions = symbolConversions.get(symbol); 322 if(conversions == null) { 323 conversions = new SymbolConversions(); 324 symbolConversions.put(symbol, conversions); 325 } 326 conversions.recordConversion(from, to); 327 } 328 329 private static LvarType toLvarType(final Type type) { 330 assert type != null; 331 final LvarType lvarType = TO_LVAR_TYPE.get(type); 332 if(lvarType != null) { 333 return lvarType; 334 } 335 assert type.isObject(); 336 return LvarType.OBJECT; 337 } 338 private static LvarType widestLvarType(final LvarType t1, final LvarType t2) { 339 if(t1 == t2) { 340 return t1; 341 } 342 // Undefined or boolean to anything always widens to object. 343 if(t1.ordinal() < LvarType.INT.ordinal() || t2.ordinal() < LvarType.INT.ordinal()) { 344 return LvarType.OBJECT; 345 } 346 // NOTE: we allow "widening" of long to double even though it can lose precision. ECMAScript doesn't have an 347 // Int64 type anyway, so this loss of precision is actually more conformant to the specification... 348 return LvarType.values()[Math.max(t1.ordinal(), t2.ordinal())]; 349 } 350 private final Compiler compiler; 351 private final Map<Label, JumpTarget> jumpTargets = new IdentityHashMap<>(); 352 // Local variable type mapping at the currently evaluated point. No map instance is ever modified; setLvarType() always 353 // allocates a new map. Immutability of maps allows for cheap snapshots by just keeping the reference to the current 354 // value. 355 private Map<Symbol, LvarType> localVariableTypes = new IdentityHashMap<>(); 356 357 // Whether the current point in the AST is reachable code 358 private boolean reachable = true; 359 // Return type of the function 360 private Type returnType = Type.UNKNOWN; 361 // Synthetic return node that we must insert at the end of the function if it's end is reachable. 362 private ReturnNode syntheticReturn; 363 364 private boolean alreadyEnteredTopLevelFunction; 365 366 // LvarType and conversion information gathered during the top-down pass; applied to nodes in the bottom-up pass. 367 private final Map<JoinPredecessor, LocalVariableConversion> localVariableConversions = new IdentityHashMap<>(); 368 369 private final Map<IdentNode, LvarType> identifierLvarTypes = new IdentityHashMap<>(); 370 private final Map<Symbol, SymbolConversions> symbolConversions = new IdentityHashMap<>(); 371 372 private SymbolToType symbolToType = new SymbolToType(); 373 374 // Stack of open labels for starts of catch blocks, one for every currently traversed try block; for inserting 375 // control flow edges to them. Note that we currently don't insert actual control flow edges, but instead edges that 376 // help us with type calculations. This means that some operations that can result in an exception being thrown 377 // aren't considered (function calls, side effecting property getters and setters etc.), while some operations that 378 // don't result in control flow transfers do originate an edge to the catch blocks (namely, assignments to local 379 // variables). 380 private final Deque<Label> catchLabels = new ArrayDeque<>(); 381 382 LocalVariableTypesCalculator(final Compiler compiler) { 383 super(new LexicalContext()); 384 this.compiler = compiler; 385 } 386 387 private JumpTarget createJumpTarget(final Label label) { 388 assert !jumpTargets.containsKey(label); 389 final JumpTarget jumpTarget = new JumpTarget(); 390 jumpTargets.put(label, jumpTarget); 391 return jumpTarget; 392 } 393 394 private void doesNotContinueSequentially() { 395 reachable = false; 396 localVariableTypes = Collections.emptyMap(); 397 } 398 399 400 @Override 401 public boolean enterBinaryNode(final BinaryNode binaryNode) { 402 final Expression lhs = binaryNode.lhs(); 403 final Expression rhs = binaryNode.rhs(); 404 final boolean isAssignment = binaryNode.isAssignment(); 405 406 final TokenType tokenType = Token.descType(binaryNode.getToken()); 407 if(tokenType.isLeftAssociative()) { 408 assert !isAssignment; 409 final boolean isLogical = binaryNode.isLogical(); 410 final Label joinLabel = isLogical ? new Label("") : null; 411 lhs.accept(this); 412 if(isLogical) { 413 jumpToLabel((JoinPredecessor)lhs, joinLabel); 414 } 415 rhs.accept(this); 416 if(isLogical) { 417 jumpToLabel((JoinPredecessor)rhs, joinLabel); 418 } 419 joinOnLabel(joinLabel); 420 } else { 421 rhs.accept(this); 422 if(isAssignment) { 423 if(lhs instanceof BaseNode) { 424 ((BaseNode)lhs).getBase().accept(this); 425 if(lhs instanceof IndexNode) { 426 ((IndexNode)lhs).getIndex().accept(this); 427 } else { 428 assert lhs instanceof AccessNode; 429 } 430 } else { 431 assert lhs instanceof IdentNode; 432 if(binaryNode.isSelfModifying()) { 433 ((IdentNode)lhs).accept(this); 434 } 435 } 436 } else { 437 lhs.accept(this); 438 } 439 } 440 441 if(isAssignment && lhs instanceof IdentNode) { 442 if(binaryNode.isSelfModifying()) { 443 onSelfAssignment((IdentNode)lhs, binaryNode); 444 } else { 445 onAssignment((IdentNode)lhs, rhs); 446 } 447 } 448 return false; 449 } 450 451 @Override 452 public boolean enterBlock(final Block block) { 453 for(final Symbol symbol: block.getSymbols()) { 454 if(symbol.isBytecodeLocal() && getLocalVariableTypeOrNull(symbol) == null) { 455 setType(symbol, LvarType.UNDEFINED); 456 } 457 } 458 return true; 459 } 460 461 @Override 462 public boolean enterBreakNode(final BreakNode breakNode) { 463 return enterJumpStatement(breakNode); 464 } 465 466 @Override 467 public boolean enterContinueNode(final ContinueNode continueNode) { 468 return enterJumpStatement(continueNode); 469 } 470 471 private boolean enterJumpStatement(final JumpStatement jump) { 472 if(!reachable) { 473 return false; 474 } 475 final BreakableNode target = jump.getTarget(lc); 476 jumpToLabel(jump, jump.getTargetLabel(target), getBreakTargetTypes(target)); 477 doesNotContinueSequentially(); 478 return false; 479 } 480 481 @Override 482 protected boolean enterDefault(final Node node) { 483 return reachable; 484 } 485 486 private void enterDoWhileLoop(final WhileNode loopNode) { 487 final JoinPredecessorExpression test = loopNode.getTest(); 488 final Block body = loopNode.getBody(); 489 final Label continueLabel = loopNode.getContinueLabel(); 490 final Label breakLabel = loopNode.getBreakLabel(); 491 final Map<Symbol, LvarType> beforeLoopTypes = localVariableTypes; 492 final Label repeatLabel = new Label(""); 493 for(;;) { 494 jumpToLabel(loopNode, repeatLabel, beforeLoopTypes); 495 final Map<Symbol, LvarType> beforeRepeatTypes = localVariableTypes; 496 body.accept(this); 497 if(reachable) { 498 jumpToLabel(body, continueLabel); 499 } 500 joinOnLabel(continueLabel); 501 if(!reachable) { 502 break; 503 } 504 test.accept(this); 505 jumpToLabel(test, breakLabel); 506 if(isAlwaysFalse(test)) { 507 break; 508 } 509 jumpToLabel(test, repeatLabel); 510 joinOnLabel(repeatLabel); 511 if(localVariableTypes.equals(beforeRepeatTypes)) { 512 break; 513 } 514 resetJoinPoint(continueLabel); 515 resetJoinPoint(breakLabel); 516 resetJoinPoint(repeatLabel); 517 } 518 519 if(isAlwaysTrue(test)) { 520 doesNotContinueSequentially(); 521 } 522 523 leaveBreakable(loopNode); 524 } 525 526 @Override 527 public boolean enterForNode(final ForNode forNode) { 528 if(!reachable) { 529 return false; 530 } 531 532 final Expression init = forNode.getInit(); 533 if(forNode.isForIn()) { 534 final JoinPredecessorExpression iterable = forNode.getModify(); 535 iterable.accept(this); 536 enterTestFirstLoop(forNode, null, init, 537 // If we're iterating over property names, and we can discern from the runtime environment 538 // of the compilation that the object being iterated over must use strings for property 539 // names (e.g., it is a native JS object or array), then we'll not bother trying to treat 540 // the property names optimistically. 541 !compiler.useOptimisticTypes() || (!forNode.isForEach() && compiler.hasStringPropertyIterator(iterable.getExpression()))); 542 } else { 543 if(init != null) { 544 init.accept(this); 545 } 546 enterTestFirstLoop(forNode, forNode.getModify(), null, false); 547 } 548 return false; 549 } 550 551 @Override 552 public boolean enterFunctionNode(final FunctionNode functionNode) { 553 if(alreadyEnteredTopLevelFunction) { 554 return false; 555 } 556 int pos = 0; 557 if(!functionNode.isVarArg()) { 558 for (final IdentNode param : functionNode.getParameters()) { 559 final Symbol symbol = param.getSymbol(); 560 // Parameter is not necessarily bytecode local as it can be scoped due to nested context use, but it 561 // must have a slot if we aren't in a function with vararg signature. 562 assert symbol.hasSlot(); 563 final Type callSiteParamType = compiler.getParamType(functionNode, pos); 564 final LvarType paramType = callSiteParamType == null ? LvarType.OBJECT : toLvarType(callSiteParamType); 565 setType(symbol, paramType); 566 // Make sure parameter slot for its incoming value is not marked dead. NOTE: this is a heuristic. Right 567 // now, CodeGenerator.expandParameters() relies on the fact that every parameter's final slot width will 568 // be at least the same as incoming width, therefore even if a parameter is never read, we'll still keep 569 // its slot. 570 symbolIsUsed(symbol); 571 setIdentifierLvarType(param, paramType); 572 pos++; 573 } 574 } 575 setCompilerConstantAsObject(functionNode, CompilerConstants.THIS); 576 577 // TODO: coarse-grained. If we wanted to solve it completely precisely, 578 // we'd also need to push/pop its type when handling WithNode (so that 579 // it can go back to undefined after a 'with' block. 580 if(functionNode.hasScopeBlock() || functionNode.needsParentScope()) { 581 setCompilerConstantAsObject(functionNode, CompilerConstants.SCOPE); 582 } 583 if(functionNode.needsCallee()) { 584 setCompilerConstantAsObject(functionNode, CompilerConstants.CALLEE); 585 } 586 if(functionNode.needsArguments()) { 587 setCompilerConstantAsObject(functionNode, CompilerConstants.ARGUMENTS); 588 } 589 590 alreadyEnteredTopLevelFunction = true; 591 return true; 592 } 593 594 @Override 595 public boolean enterIdentNode(final IdentNode identNode) { 596 final Symbol symbol = identNode.getSymbol(); 597 if(symbol.isBytecodeLocal()) { 598 symbolIsUsed(symbol); 599 setIdentifierLvarType(identNode, getLocalVariableType(symbol)); 600 } 601 return false; 602 } 603 604 @Override 605 public boolean enterIfNode(final IfNode ifNode) { 606 if(!reachable) { 607 return false; 608 } 609 610 final Expression test = ifNode.getTest(); 611 final Block pass = ifNode.getPass(); 612 final Block fail = ifNode.getFail(); 613 614 test.accept(this); 615 616 final Map<Symbol, LvarType> afterTestLvarTypes = localVariableTypes; 617 if(!isAlwaysFalse(test)) { 618 pass.accept(this); 619 } 620 final Map<Symbol, LvarType> passLvarTypes = localVariableTypes; 621 final boolean reachableFromPass = reachable; 622 623 reachable = true; 624 localVariableTypes = afterTestLvarTypes; 625 if(!isAlwaysTrue(test) && fail != null) { 626 fail.accept(this); 627 final boolean reachableFromFail = reachable; 628 reachable |= reachableFromPass; 629 if(!reachable) { 630 return false; 631 } 632 633 if(reachableFromFail) { 634 if(reachableFromPass) { 635 final Map<Symbol, LvarType> failLvarTypes = localVariableTypes; 636 localVariableTypes = getUnionTypes(passLvarTypes, failLvarTypes); 637 setConversion(pass, passLvarTypes, localVariableTypes); 638 setConversion(fail, failLvarTypes, localVariableTypes); 639 } 640 return false; 641 } 642 } 643 644 if(reachableFromPass) { 645 localVariableTypes = getUnionTypes(afterTestLvarTypes, passLvarTypes); 646 // IfNode itself is associated with conversions that might need to be performed after the test if there's no 647 // else branch. E.g. 648 // if(x = 1, cond) { x = 1.0 } must widen "x = 1" to a double. 649 setConversion(pass, passLvarTypes, localVariableTypes); 650 setConversion(ifNode, afterTestLvarTypes, localVariableTypes); 651 } else { 652 localVariableTypes = afterTestLvarTypes; 653 } 654 655 return false; 656 } 657 658 @Override 659 public boolean enterPropertyNode(final PropertyNode propertyNode) { 660 // Avoid falsely adding property keys to the control flow graph 661 if(propertyNode.getValue() != null) { 662 propertyNode.getValue().accept(this); 663 } 664 return false; 665 } 666 667 @Override 668 public boolean enterReturnNode(final ReturnNode returnNode) { 669 if(!reachable) { 670 return false; 671 } 672 673 final Expression returnExpr = returnNode.getExpression(); 674 final Type returnExprType; 675 if(returnExpr != null) { 676 returnExpr.accept(this); 677 returnExprType = getType(returnExpr); 678 } else { 679 returnExprType = Type.UNDEFINED; 680 } 681 returnType = Type.widestReturnType(returnType, returnExprType); 682 doesNotContinueSequentially(); 683 return false; 684 } 685 686 @Override 687 public boolean enterSplitReturn(final SplitReturn splitReturn) { 688 doesNotContinueSequentially(); 689 return false; 690 } 691 692 @Override 693 public boolean enterSwitchNode(final SwitchNode switchNode) { 694 if(!reachable) { 695 return false; 696 } 697 698 final Expression expr = switchNode.getExpression(); 699 expr.accept(this); 700 701 final List<CaseNode> cases = switchNode.getCases(); 702 if(cases.isEmpty()) { 703 return false; 704 } 705 706 // Control flow is different for all-integer cases where we dispatch by switch table, and for all other cases 707 // where we do sequential comparison. Note that CaseNode objects act as join points. 708 final boolean isInteger = switchNode.isInteger(); 709 final Label breakLabel = switchNode.getBreakLabel(); 710 final boolean hasDefault = switchNode.getDefaultCase() != null; 711 712 boolean tagUsed = false; 713 for(final CaseNode caseNode: cases) { 714 final Expression test = caseNode.getTest(); 715 if(!isInteger && test != null) { 716 test.accept(this); 717 if(!tagUsed) { 718 symbolIsUsed(switchNode.getTag(), LvarType.OBJECT); 719 tagUsed = true; 720 } 721 } 722 // CaseNode carries the conversions that need to be performed on its entry from the test. 723 // CodeGenerator ensures these are only emitted when arriving on the branch and not through a 724 // fallthrough. 725 jumpToLabel(caseNode, caseNode.getBody().getEntryLabel()); 726 } 727 if(!hasDefault) { 728 // No default case means we can arrive at the break label without entering any cases. In that case 729 // SwitchNode will carry the conversions that need to be performed before it does that jump. 730 jumpToLabel(switchNode, breakLabel); 731 } 732 733 // All cases are arrived at through jumps 734 doesNotContinueSequentially(); 735 736 Block previousBlock = null; 737 for(final CaseNode caseNode: cases) { 738 final Block body = caseNode.getBody(); 739 final Label entryLabel = body.getEntryLabel(); 740 if(previousBlock != null && reachable) { 741 jumpToLabel(previousBlock, entryLabel); 742 } 743 joinOnLabel(entryLabel); 744 assert reachable == true; 745 body.accept(this); 746 previousBlock = body; 747 } 748 if(previousBlock != null && reachable) { 749 jumpToLabel(previousBlock, breakLabel); 750 } 751 leaveBreakable(switchNode); 752 return false; 753 } 754 755 @Override 756 public boolean enterTernaryNode(final TernaryNode ternaryNode) { 757 final Expression test = ternaryNode.getTest(); 758 final Expression trueExpr = ternaryNode.getTrueExpression(); 759 final Expression falseExpr = ternaryNode.getFalseExpression(); 760 761 test.accept(this); 762 763 final Map<Symbol, LvarType> testExitLvarTypes = localVariableTypes; 764 if(!isAlwaysFalse(test)) { 765 trueExpr.accept(this); 766 } 767 final Map<Symbol, LvarType> trueExitLvarTypes = localVariableTypes; 768 localVariableTypes = testExitLvarTypes; 769 if(!isAlwaysTrue(test)) { 770 falseExpr.accept(this); 771 } 772 final Map<Symbol, LvarType> falseExitLvarTypes = localVariableTypes; 773 localVariableTypes = getUnionTypes(trueExitLvarTypes, falseExitLvarTypes); 774 setConversion((JoinPredecessor)trueExpr, trueExitLvarTypes, localVariableTypes); 775 setConversion((JoinPredecessor)falseExpr, falseExitLvarTypes, localVariableTypes); 776 return false; 777 } 778 779 private void enterTestFirstLoop(final LoopNode loopNode, final JoinPredecessorExpression modify, 780 final Expression iteratorValues, final boolean iteratorValuesAreObject) { 781 final JoinPredecessorExpression test = loopNode.getTest(); 782 if(isAlwaysFalse(test)) { 783 test.accept(this); 784 return; 785 } 786 787 final Label continueLabel = loopNode.getContinueLabel(); 788 final Label breakLabel = loopNode.getBreakLabel(); 789 790 final Label repeatLabel = modify == null ? continueLabel : new Label(""); 791 final Map<Symbol, LvarType> beforeLoopTypes = localVariableTypes; 792 for(;;) { 793 jumpToLabel(loopNode, repeatLabel, beforeLoopTypes); 794 final Map<Symbol, LvarType> beforeRepeatTypes = localVariableTypes; 795 if(test != null) { 796 test.accept(this); 797 } 798 if(!isAlwaysTrue(test)) { 799 jumpToLabel(test, breakLabel); 800 } 801 if(iteratorValues instanceof IdentNode) { 802 final IdentNode ident = (IdentNode)iteratorValues; 803 // Receives iterator values; the optimistic type of the iterator values is tracked on the 804 // identifier, but we override optimism if it's known that the object being iterated over will 805 // never have primitive property names. 806 onAssignment(ident, iteratorValuesAreObject ? LvarType.OBJECT : 807 toLvarType(compiler.getOptimisticType(ident))); 808 } 809 final Block body = loopNode.getBody(); 810 body.accept(this); 811 if(reachable) { 812 jumpToLabel(body, continueLabel); 813 } 814 joinOnLabel(continueLabel); 815 if(!reachable) { 816 break; 817 } 818 if(modify != null) { 819 modify.accept(this); 820 jumpToLabel(modify, repeatLabel); 821 joinOnLabel(repeatLabel); 822 } 823 if(localVariableTypes.equals(beforeRepeatTypes)) { 824 break; 825 } 826 // Reset the join points and repeat the analysis 827 resetJoinPoint(continueLabel); 828 resetJoinPoint(breakLabel); 829 resetJoinPoint(repeatLabel); 830 } 831 832 if(isAlwaysTrue(test) && iteratorValues == null) { 833 doesNotContinueSequentially(); 834 } 835 836 leaveBreakable(loopNode); 837 } 838 839 @Override 840 public boolean enterThrowNode(final ThrowNode throwNode) { 841 if(!reachable) { 842 return false; 843 } 844 845 throwNode.getExpression().accept(this); 846 jumpToCatchBlock(throwNode); 847 doesNotContinueSequentially(); 848 return false; 849 } 850 851 @Override 852 public boolean enterTryNode(final TryNode tryNode) { 853 if(!reachable) { 854 return false; 855 } 856 857 // This is the label for the join point at the entry of the catch blocks. 858 final Label catchLabel = new Label(""); 859 catchLabels.push(catchLabel); 860 861 // Presume that even the start of the try block can immediately go to the catch 862 jumpToLabel(tryNode, catchLabel); 863 864 final Block body = tryNode.getBody(); 865 body.accept(this); 866 catchLabels.pop(); 867 868 // Final exit label for the whole try/catch construct (after the try block and after all catches). 869 final Label endLabel = new Label(""); 870 871 boolean canExit = false; 872 if(reachable) { 873 jumpToLabel(body, endLabel); 874 canExit = true; 875 } 876 doesNotContinueSequentially(); 877 878 joinOnLabel(catchLabel); 879 for(final CatchNode catchNode: tryNode.getCatches()) { 880 final IdentNode exception = catchNode.getException(); 881 onAssignment(exception, LvarType.OBJECT); 882 final Expression condition = catchNode.getExceptionCondition(); 883 if(condition != null) { 884 condition.accept(this); 885 } 886 final Map<Symbol, LvarType> afterConditionTypes = localVariableTypes; 887 final Block catchBody = catchNode.getBody(); 888 // TODO: currently, we consider that the catch blocks are always reachable from the try block as currently 889 // we lack enough analysis to prove that no statement before a break/continue/return in the try block can 890 // throw an exception. 891 reachable = true; 892 catchBody.accept(this); 893 final Symbol exceptionSymbol = exception.getSymbol(); 894 if(reachable) { 895 localVariableTypes = cloneMap(localVariableTypes); 896 localVariableTypes.remove(exceptionSymbol); 897 jumpToLabel(catchBody, endLabel); 898 canExit = true; 899 } 900 localVariableTypes = cloneMap(afterConditionTypes); 901 localVariableTypes.remove(exceptionSymbol); 902 } 903 // NOTE: if we had one or more conditional catch blocks with no unconditional catch block following them, then 904 // there will be an unconditional rethrow, so the join point can never be reached from the last 905 // conditionExpression. 906 doesNotContinueSequentially(); 907 908 if(canExit) { 909 joinOnLabel(endLabel); 910 } 911 912 return false; 913 } 914 915 916 @Override 917 public boolean enterUnaryNode(final UnaryNode unaryNode) { 918 final Expression expr = unaryNode.getExpression(); 919 expr.accept(this); 920 921 if(unaryNode.isSelfModifying()) { 922 if(expr instanceof IdentNode) { 923 onSelfAssignment((IdentNode)expr, unaryNode); 924 } 925 } 926 return false; 927 } 928 929 @Override 930 public boolean enterVarNode(final VarNode varNode) { 931 if (!reachable) { 932 return false; 933 } 934 final Expression init = varNode.getInit(); 935 if(init != null) { 936 init.accept(this); 937 onAssignment(varNode.getName(), init); 938 } 939 return false; 940 } 941 942 @Override 943 public boolean enterWhileNode(final WhileNode whileNode) { 944 if(!reachable) { 945 return false; 946 } 947 if(whileNode.isDoWhile()) { 948 enterDoWhileLoop(whileNode); 949 } else { 950 enterTestFirstLoop(whileNode, null, null, false); 951 } 952 return false; 953 } 954 955 private Map<Symbol, LvarType> getBreakTargetTypes(final BreakableNode target) { 956 // Remove symbols defined in the the blocks that are being broken out of. 957 Map<Symbol, LvarType> types = localVariableTypes; 958 for(final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) { 959 final LexicalContextNode node = it.next(); 960 if(node instanceof Block) { 961 for(final Symbol symbol: ((Block)node).getSymbols()) { 962 if(localVariableTypes.containsKey(symbol)) { 963 if(types == localVariableTypes) { 964 types = cloneMap(localVariableTypes); 965 } 966 types.remove(symbol); 967 } 968 } 969 } 970 if(node == target) { 971 break; 972 } 973 } 974 return types; 975 } 976 977 private LvarType getLocalVariableType(final Symbol symbol) { 978 final LvarType type = getLocalVariableTypeOrNull(symbol); 979 assert type != null; 980 return type; 981 } 982 983 private LvarType getLocalVariableTypeOrNull(final Symbol symbol) { 984 return localVariableTypes.get(symbol); 985 } 986 987 private JumpTarget getOrCreateJumpTarget(final Label label) { 988 JumpTarget jumpTarget = jumpTargets.get(label); 989 if(jumpTarget == null) { 990 jumpTarget = createJumpTarget(label); 991 } 992 return jumpTarget; 993 } 994 995 996 /** 997 * If there's a join point associated with a label, insert the join point into the flow. 998 * @param label the label to insert a join point for. 999 */ 1000 private void joinOnLabel(final Label label) { 1001 final JumpTarget jumpTarget = jumpTargets.remove(label); 1002 if(jumpTarget == null) { 1003 return; 1004 } 1005 assert !jumpTarget.origins.isEmpty(); 1006 reachable = true; 1007 localVariableTypes = getUnionTypes(jumpTarget.types, localVariableTypes); 1008 for(final JumpOrigin jumpOrigin: jumpTarget.origins) { 1009 setConversion(jumpOrigin.node, jumpOrigin.types, localVariableTypes); 1010 } 1011 } 1012 1013 /** 1014 * If we're in a try/catch block, add an edge from the specified node to the try node's pre-catch label. 1015 */ 1016 private void jumpToCatchBlock(final JoinPredecessor jumpOrigin) { 1017 final Label currentCatchLabel = catchLabels.peek(); 1018 if(currentCatchLabel != null) { 1019 jumpToLabel(jumpOrigin, currentCatchLabel); 1020 } 1021 } 1022 1023 private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label) { 1024 jumpToLabel(jumpOrigin, label, localVariableTypes); 1025 } 1026 1027 private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label, final Map<Symbol, LvarType> types) { 1028 getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types); 1029 } 1030 1031 @Override 1032 public Node leaveBlock(final Block block) { 1033 if(lc.isFunctionBody()) { 1034 if(reachable) { 1035 // reachable==true means we can reach the end of the function without an explicit return statement. We 1036 // need to insert a synthetic one then. This logic used to be in Lower.leaveBlock(), but Lower's 1037 // reachability analysis (through Terminal.isTerminal() flags) is not precise enough so 1038 // Lower$BlockLexicalContext.afterSetStatements will sometimes think the control flow terminates even 1039 // when it didn't. Example: function() { switch((z)) { default: {break; } throw x; } }. 1040 createSyntheticReturn(block); 1041 assert !reachable; 1042 } 1043 // We must calculate the return type here (and not in leaveFunctionNode) as it can affect the liveness of 1044 // the :return symbol and thus affect conversion type liveness calculations for it. 1045 calculateReturnType(); 1046 } 1047 1048 boolean cloned = false; 1049 for(final Symbol symbol: block.getSymbols()) { 1050 // Undefine the symbol outside the block 1051 if(localVariableTypes.containsKey(symbol)) { 1052 if(!cloned) { 1053 localVariableTypes = cloneMap(localVariableTypes); 1054 cloned = true; 1055 } 1056 localVariableTypes.remove(symbol); 1057 } 1058 1059 if(symbol.hasSlot()) { 1060 final SymbolConversions conversions = symbolConversions.get(symbol); 1061 if(conversions != null) { 1062 // Potentially make some currently dead types live if they're needed as a source of a type 1063 // conversion at a join. 1064 conversions.calculateTypeLiveness(symbol); 1065 } 1066 if(symbol.slotCount() == 0) { 1067 // This is a local variable that is never read. It won't need a slot. 1068 symbol.setNeedsSlot(false); 1069 } 1070 } 1071 } 1072 1073 if(reachable) { 1074 // TODO: this is totally backwards. Block should not be breakable, LabelNode should be breakable. 1075 final LabelNode labelNode = lc.getCurrentBlockLabelNode(); 1076 if(labelNode != null) { 1077 jumpToLabel(labelNode, block.getBreakLabel()); 1078 } 1079 } 1080 leaveBreakable(block); 1081 return block; 1082 } 1083 1084 private void calculateReturnType() { 1085 // NOTE: if return type is unknown, then the function does not explicitly return a value. Such a function under 1086 // ECMAScript rules returns Undefined, which has Type.OBJECT. We might consider an optimization in the future 1087 // where we can return void functions. 1088 if(returnType.isUnknown()) { 1089 returnType = Type.OBJECT; 1090 } 1091 } 1092 1093 private void createSyntheticReturn(final Block body) { 1094 final FunctionNode functionNode = lc.getCurrentFunction(); 1095 final long token = functionNode.getToken(); 1096 final int finish = functionNode.getFinish(); 1097 final List<Statement> statements = body.getStatements(); 1098 final int lineNumber = statements.isEmpty() ? functionNode.getLineNumber() : statements.get(statements.size() - 1).getLineNumber(); 1099 final IdentNode returnExpr; 1100 if(functionNode.isProgram()) { 1101 returnExpr = new IdentNode(token, finish, RETURN.symbolName()).setSymbol(getCompilerConstantSymbol(functionNode, RETURN)); 1102 } else { 1103 returnExpr = null; 1104 } 1105 syntheticReturn = new ReturnNode(lineNumber, token, finish, returnExpr); 1106 syntheticReturn.accept(this); 1107 } 1108 1109 /** 1110 * Leave a breakable node. If there's a join point associated with its break label (meaning there was at least one 1111 * break statement to the end of the node), insert the join point into the flow. 1112 * @param breakable the breakable node being left. 1113 */ 1114 private void leaveBreakable(final BreakableNode breakable) { 1115 joinOnLabel(breakable.getBreakLabel()); 1116 } 1117 1118 @Override 1119 public Node leaveFunctionNode(final FunctionNode functionNode) { 1120 // Sets the return type of the function and also performs the bottom-up pass of applying type and conversion 1121 // information to nodes as well as doing the calculation on nested functions as required. 1122 FunctionNode newFunction = functionNode; 1123 final NodeVisitor<LexicalContext> applyChangesVisitor = new NodeVisitor<LexicalContext>(new LexicalContext()) { 1124 private boolean inOuterFunction = true; 1125 private final Deque<JoinPredecessor> joinPredecessors = new ArrayDeque<>(); 1126 1127 @Override 1128 protected boolean enterDefault(final Node node) { 1129 if(!inOuterFunction) { 1130 return false; 1131 } 1132 if(node instanceof JoinPredecessor) { 1133 joinPredecessors.push((JoinPredecessor)node); 1134 } 1135 return inOuterFunction; 1136 } 1137 1138 @Override 1139 public boolean enterFunctionNode(final FunctionNode fn) { 1140 if(compiler.isOnDemandCompilation()) { 1141 // Only calculate nested function local variable types if we're doing eager compilation 1142 return false; 1143 } 1144 inOuterFunction = false; 1145 return true; 1146 } 1147 1148 @SuppressWarnings("fallthrough") 1149 @Override 1150 public Node leaveBinaryNode(final BinaryNode binaryNode) { 1151 if(binaryNode.isComparison()) { 1152 final Expression lhs = binaryNode.lhs(); 1153 final Expression rhs = binaryNode.rhs(); 1154 1155 Type cmpWidest = Type.widest(lhs.getType(), rhs.getType()); 1156 boolean newRuntimeNode = false, finalized = false; 1157 final TokenType tt = binaryNode.tokenType(); 1158 switch (tt) { 1159 case EQ_STRICT: 1160 case NE_STRICT: 1161 // Specialize comparison with undefined 1162 final Expression undefinedNode = createIsUndefined(binaryNode, lhs, rhs, 1163 tt == TokenType.EQ_STRICT ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED); 1164 if(undefinedNode != binaryNode) { 1165 return undefinedNode; 1166 } 1167 // Specialize comparison of boolean with non-boolean 1168 if (lhs.getType().isBoolean() != rhs.getType().isBoolean()) { 1169 newRuntimeNode = true; 1170 cmpWidest = Type.OBJECT; 1171 finalized = true; 1172 } 1173 // fallthrough 1174 default: 1175 if (newRuntimeNode || cmpWidest.isObject()) { 1176 return new RuntimeNode(binaryNode).setIsFinal(finalized); 1177 } 1178 } 1179 } else if(binaryNode.isOptimisticUndecidedType()) { 1180 // At this point, we can assign a static type to the optimistic binary ADD operator as now we know 1181 // the types of its operands. 1182 return binaryNode.decideType(); 1183 } 1184 return binaryNode; 1185 } 1186 1187 @Override 1188 protected Node leaveDefault(final Node node) { 1189 if(node instanceof JoinPredecessor) { 1190 final JoinPredecessor original = joinPredecessors.pop(); 1191 assert original.getClass() == node.getClass() : original.getClass().getName() + "!=" + node.getClass().getName(); 1192 return (Node)setLocalVariableConversion(original, (JoinPredecessor)node); 1193 } 1194 return node; 1195 } 1196 1197 @Override 1198 public Node leaveBlock(final Block block) { 1199 if(inOuterFunction && syntheticReturn != null && lc.isFunctionBody()) { 1200 final ArrayList<Statement> stmts = new ArrayList<>(block.getStatements()); 1201 stmts.add((ReturnNode)syntheticReturn.accept(this)); 1202 return block.setStatements(lc, stmts); 1203 } 1204 return super.leaveBlock(block); 1205 } 1206 1207 @Override 1208 public Node leaveFunctionNode(final FunctionNode nestedFunctionNode) { 1209 inOuterFunction = true; 1210 final FunctionNode newNestedFunction = (FunctionNode)nestedFunctionNode.accept( 1211 new LocalVariableTypesCalculator(compiler)); 1212 lc.replace(nestedFunctionNode, newNestedFunction); 1213 return newNestedFunction; 1214 } 1215 1216 @Override 1217 public Node leaveIdentNode(final IdentNode identNode) { 1218 final IdentNode original = (IdentNode)joinPredecessors.pop(); 1219 final Symbol symbol = identNode.getSymbol(); 1220 if(symbol == null) { 1221 assert identNode.isPropertyName(); 1222 return identNode; 1223 } else if(symbol.hasSlot()) { 1224 assert !symbol.isScope() || symbol.isParam(); // Only params can be slotted and scoped. 1225 assert original.getName().equals(identNode.getName()); 1226 final LvarType lvarType = identifierLvarTypes.remove(original); 1227 if(lvarType != null) { 1228 return setLocalVariableConversion(original, identNode.setType(lvarType.type)); 1229 } 1230 // If there's no type, then the identifier must've been in unreachable code. In that case, it can't 1231 // have assigned conversions either. 1232 assert localVariableConversions.get(original) == null; 1233 } else { 1234 assert identIsDeadAndHasNoLiveConversions(original); 1235 } 1236 return identNode; 1237 } 1238 1239 @Override 1240 public Node leaveLiteralNode(final LiteralNode<?> literalNode) { 1241 //for e.g. ArrayLiteralNodes the initial types may have been narrowed due to the 1242 //introduction of optimistic behavior - hence ensure that all literal nodes are 1243 //reinitialized 1244 return literalNode.initialize(lc); 1245 } 1246 1247 @Override 1248 public Node leaveRuntimeNode(final RuntimeNode runtimeNode) { 1249 final Request request = runtimeNode.getRequest(); 1250 final boolean isEqStrict = request == Request.EQ_STRICT; 1251 if(isEqStrict || request == Request.NE_STRICT) { 1252 return createIsUndefined(runtimeNode, runtimeNode.getArgs().get(0), runtimeNode.getArgs().get(1), 1253 isEqStrict ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED); 1254 } 1255 return runtimeNode; 1256 } 1257 1258 @SuppressWarnings("unchecked") 1259 private <T extends JoinPredecessor> T setLocalVariableConversion(final JoinPredecessor original, final T jp) { 1260 // NOTE: can't use Map.remove() as our copy-on-write AST semantics means some nodes appear twice (in 1261 // finally blocks), so we need to be able to access conversions for them multiple times. 1262 return (T)jp.setLocalVariableConversion(lc, localVariableConversions.get(original)); 1263 } 1264 }; 1265 1266 newFunction = newFunction.setBody(lc, (Block)newFunction.getBody().accept(applyChangesVisitor)); 1267 newFunction = newFunction.setReturnType(lc, returnType); 1268 1269 1270 newFunction = newFunction.setState(lc, CompilationState.LOCAL_VARIABLE_TYPES_CALCULATED); 1271 newFunction = newFunction.setParameters(lc, newFunction.visitParameters(applyChangesVisitor)); 1272 return newFunction; 1273 } 1274 1275 private static Expression createIsUndefined(final Expression parent, final Expression lhs, final Expression rhs, final Request request) { 1276 if (isUndefinedIdent(lhs) || isUndefinedIdent(rhs)) { 1277 return new RuntimeNode(parent, request, lhs, rhs); 1278 } 1279 return parent; 1280 } 1281 1282 private static boolean isUndefinedIdent(final Expression expr) { 1283 return expr instanceof IdentNode && "undefined".equals(((IdentNode)expr).getName()); 1284 } 1285 1286 private boolean identIsDeadAndHasNoLiveConversions(final IdentNode identNode) { 1287 final LocalVariableConversion conv = localVariableConversions.get(identNode); 1288 return conv == null || !conv.isLive(); 1289 } 1290 1291 private void onAssignment(final IdentNode identNode, final Expression rhs) { 1292 onAssignment(identNode, toLvarType(getType(rhs))); 1293 } 1294 1295 private void onAssignment(final IdentNode identNode, final LvarType type) { 1296 final Symbol symbol = identNode.getSymbol(); 1297 assert symbol != null : identNode.getName(); 1298 if(!symbol.isBytecodeLocal()) { 1299 return; 1300 } 1301 assert type != null; 1302 final LvarType finalType; 1303 if(type == LvarType.UNDEFINED && getLocalVariableType(symbol) != LvarType.UNDEFINED) { 1304 // Explicit assignment of a known undefined local variable to a local variable that is not undefined will 1305 // materialize that undefined in the assignment target. Note that assigning known undefined to known 1306 // undefined will *not* initialize the variable, e.g. "var x; var y = x;" compiles to no-op. 1307 finalType = LvarType.OBJECT; 1308 symbol.setFlag(Symbol.HAS_OBJECT_VALUE); 1309 } else { 1310 finalType = type; 1311 } 1312 setType(symbol, finalType); 1313 // Explicit assignment of an undefined value. Make sure the variable can store an object 1314 // TODO: if we communicated the fact to codegen with a flag on the IdentNode that the value was already 1315 // undefined before the assignment, we could just ignore it. In general, we could ignore an assignment if we 1316 // know that the value assigned is the same as the current value of the variable, but we'd need constant 1317 // propagation for that. 1318 setIdentifierLvarType(identNode, finalType); 1319 // For purposes of type calculation, we consider an assignment to a local variable to be followed by 1320 // the catch nodes of the current (if any) try block. This will effectively enforce that narrower 1321 // assignments to a local variable in a try block will also have to store a widened value as well. Code 1322 // within the try block will be able to keep loading the narrower value, but after the try block only 1323 // the widest value will remain live. 1324 // Rationale for this is that if there's an use for that variable in any of the catch blocks, or 1325 // following the catch blocks, they must use the widest type. 1326 // Example: 1327 /* 1328 Originally: 1329 =========== 1330 var x; 1331 try { 1332 x = 1; <-- stores into int slot for x 1333 f(x); <-- loads the int slot for x 1334 x = 3.14 <-- stores into the double slot for x 1335 f(x); <-- loads the double slot for x 1336 x = 1; <-- stores into int slot for x 1337 f(x); <-- loads the int slot for x 1338 } finally { 1339 f(x); <-- loads the double slot for x, but can be reached by a path where x is int, so we need 1340 to go back and ensure that double values are also always stored along with int 1341 values. 1342 } 1343 1344 After correction: 1345 ================= 1346 1347 var x; 1348 try { 1349 x = 1; <-- stores into both int and double slots for x 1350 f(x); <-- loads the int slot for x 1351 x = 3.14 <-- stores into the double slot for x 1352 f(x); <-- loads the double slot for x 1353 x = 1; <-- stores into both int and double slots for x 1354 f(x); <-- loads the int slot for x 1355 } finally { 1356 f(x); <-- loads the double slot for x 1357 } 1358 */ 1359 jumpToCatchBlock(identNode); 1360 } 1361 1362 private void onSelfAssignment(final IdentNode identNode, final Expression assignment) { 1363 final Symbol symbol = identNode.getSymbol(); 1364 assert symbol != null : identNode.getName(); 1365 if(!symbol.isBytecodeLocal()) { 1366 return; 1367 } 1368 final LvarType type = toLvarType(getType(assignment)); 1369 // Self-assignment never produce either a boolean or undefined 1370 assert type != null && type != LvarType.UNDEFINED && type != LvarType.BOOLEAN; 1371 setType(symbol, type); 1372 jumpToCatchBlock(identNode); 1373 } 1374 1375 private void resetJoinPoint(final Label label) { 1376 jumpTargets.remove(label); 1377 } 1378 1379 private void setCompilerConstantAsObject(final FunctionNode functionNode, final CompilerConstants cc) { 1380 final Symbol symbol = getCompilerConstantSymbol(functionNode, cc); 1381 setType(symbol, LvarType.OBJECT); 1382 // never mark compiler constants as dead 1383 symbolIsUsed(symbol); 1384 } 1385 1386 private static Symbol getCompilerConstantSymbol(final FunctionNode functionNode, final CompilerConstants cc) { 1387 return functionNode.getBody().getExistingSymbol(cc.symbolName()); 1388 } 1389 1390 private void setConversion(final JoinPredecessor node, final Map<Symbol, LvarType> branchLvarTypes, final Map<Symbol, LvarType> joinLvarTypes) { 1391 if(node == null) { 1392 return; 1393 } 1394 if(branchLvarTypes.isEmpty() || joinLvarTypes.isEmpty()) { 1395 localVariableConversions.remove(node); 1396 } 1397 1398 LocalVariableConversion conversion = null; 1399 if(node instanceof IdentNode) { 1400 // conversions on variable assignment in try block are special cases, as they only apply to the variable 1401 // being assigned and all other conversions should be ignored. 1402 final Symbol symbol = ((IdentNode)node).getSymbol(); 1403 conversion = createConversion(symbol, branchLvarTypes.get(symbol), joinLvarTypes, null); 1404 } else { 1405 for(final Map.Entry<Symbol, LvarType> entry: branchLvarTypes.entrySet()) { 1406 final Symbol symbol = entry.getKey(); 1407 final LvarType branchLvarType = entry.getValue(); 1408 conversion = createConversion(symbol, branchLvarType, joinLvarTypes, conversion); 1409 } 1410 } 1411 if(conversion != null) { 1412 localVariableConversions.put(node, conversion); 1413 } else { 1414 localVariableConversions.remove(node); 1415 } 1416 } 1417 1418 private void setIdentifierLvarType(final IdentNode identNode, final LvarType type) { 1419 assert type != null; 1420 identifierLvarTypes.put(identNode, type); 1421 } 1422 1423 /** 1424 * Marks a local variable as having a specific type from this point onward. Invoked by stores to local variables. 1425 * @param symbol the symbol representing the variable 1426 * @param type the type 1427 */ 1428 private void setType(final Symbol symbol, final LvarType type) { 1429 if(getLocalVariableTypeOrNull(symbol) == type) { 1430 return; 1431 } 1432 assert symbol.hasSlot(); 1433 assert !symbol.isGlobal(); 1434 localVariableTypes = localVariableTypes.isEmpty() ? new IdentityHashMap<Symbol, LvarType>() : cloneMap(localVariableTypes); 1435 localVariableTypes.put(symbol, type); 1436 } 1437 1438 /** 1439 * Set a flag in the symbol marking it as needing to be able to store a value of a particular type. Every symbol for 1440 * a local variable will be assigned between 1 and 6 local variable slots for storing all types it is known to need 1441 * to store. 1442 * @param symbol the symbol 1443 */ 1444 private void symbolIsUsed(final Symbol symbol) { 1445 symbolIsUsed(symbol, getLocalVariableType(symbol)); 1446 } 1447 1448 private Type getType(final Expression expr) { 1449 return expr.getType(getSymbolToType()); 1450 } 1451 1452 private Function<Symbol, Type> getSymbolToType() { 1453 // BinaryNode uses identity of the function to cache type calculations. Therefore, we must use different 1454 // function instances for different localVariableTypes instances. 1455 if(symbolToType.isStale()) { 1456 symbolToType = new SymbolToType(); 1457 } 1458 return symbolToType; 1459 } 1460 1461 private class SymbolToType implements Function<Symbol, Type> { 1462 private final Object boundTypes = localVariableTypes; 1463 @Override 1464 public Type apply(final Symbol t) { 1465 return getLocalVariableType(t).type; 1466 } 1467 1468 boolean isStale() { 1469 return boundTypes != localVariableTypes; 1470 } 1471 } 1472} 1473