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 26 package jdk.nashorn.internal.ir; 27 28 import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT; 29 30 import java.util.Arrays; 31 import java.util.Collections; 32 import java.util.HashSet; 33 import java.util.Set; 34 import jdk.nashorn.internal.codegen.types.Type; 35 import jdk.nashorn.internal.ir.annotations.Ignore; 36 import jdk.nashorn.internal.ir.annotations.Immutable; 37 import jdk.nashorn.internal.ir.visitor.NodeVisitor; 38 import jdk.nashorn.internal.parser.TokenType; 39 40 /** 41 * BinaryNode nodes represent two operand operations. 42 */ 43 @Immutable 44 public final class BinaryNode extends Expression implements Assignment<Expression>, Optimistic { 45 private static final long serialVersionUID = 1L; 46 47 // Placeholder for "undecided optimistic ADD type". Unfortunately, we can't decide the type of ADD during optimistic 48 // type calculation as it can have local variables as its operands that will decide its ultimate type. 49 private static final Type OPTIMISTIC_UNDECIDED_TYPE = Type.typeFor(new Object(){/*empty*/}.getClass()); 50 51 /** Left hand side argument. */ 52 private final Expression lhs; 53 54 private final Expression rhs; 55 56 private final int programPoint; 57 58 private final Type type; 59 private transient Type cachedType; 60 61 @Ignore 62 private static final Set<TokenType> CAN_OVERFLOW = 63 Collections.unmodifiableSet(new HashSet<>(Arrays.asList(new TokenType[] { 64 TokenType.ADD, 65 TokenType.DIV, 66 TokenType.MOD, 67 TokenType.MUL, 68 TokenType.SUB, 69 TokenType.ASSIGN_ADD, 70 TokenType.ASSIGN_DIV, 71 TokenType.ASSIGN_MOD, 72 TokenType.ASSIGN_MUL, 73 TokenType.ASSIGN_SUB, 74 TokenType.SHR, 75 TokenType.ASSIGN_SHR 76 }))); 77 78 /** 79 * Constructor 80 * 81 * @param token token 82 * @param lhs left hand side 83 * @param rhs right hand side 84 */ 85 public BinaryNode(final long token, final Expression lhs, final Expression rhs) { 86 super(token, lhs.getStart(), rhs.getFinish()); 87 assert !(isTokenType(TokenType.AND) || isTokenType(TokenType.OR)) || lhs instanceof JoinPredecessorExpression; 88 this.lhs = lhs; 89 this.rhs = rhs; 90 this.programPoint = INVALID_PROGRAM_POINT; 91 this.type = null; 92 } 93 94 private BinaryNode(final BinaryNode binaryNode, final Expression lhs, final Expression rhs, final Type type, final int programPoint) { 95 super(binaryNode); 96 this.lhs = lhs; 97 this.rhs = rhs; 98 this.programPoint = programPoint; 99 this.type = type; 100 } 101 102 /** 103 * Returns true if the node is a comparison operation (either equality, inequality, or relational). 104 * @return true if the node is a comparison operation. 105 */ 106 public boolean isComparison() { 107 switch (tokenType()) { 108 case EQ: 109 case EQ_STRICT: 110 case NE: 111 case NE_STRICT: 112 case LE: 113 case LT: 114 case GE: 115 case GT: 116 return true; 117 default: 118 return false; 119 } 120 } 121 122 /** 123 * Returns true if the node is a relational operation (less than (or equals), greater than (or equals)). 124 * @return true if the node is a relational operation. 125 */ 126 public boolean isRelational() { 127 switch (tokenType()) { 128 case LT: 129 case GT: 130 case LE: 131 case GE: 132 return true; 133 default: 134 return false; 135 } 136 } 137 138 /** 139 * Returns true if the node is a logical operation. 140 * @return true if the node is a logical operation. 141 */ 142 public boolean isLogical() { 143 return isLogical(tokenType()); 144 } 145 146 /** 147 * Returns true if the token type represents a logical operation. 148 * @param tokenType the token type 149 * @return true if the token type represents a logical operation. 150 */ 151 public static boolean isLogical(final TokenType tokenType) { 152 switch (tokenType) { 153 case AND: 154 case OR: 155 return true; 156 default: 157 return false; 158 } 159 } 160 161 /** 162 * Return the widest possible operand type for this operation. 163 * 164 * @return Type 165 */ 166 public Type getWidestOperandType() { 167 switch (tokenType()) { 168 case SHR: 169 case ASSIGN_SHR: 170 return Type.INT; 171 case INSTANCEOF: 172 return Type.OBJECT; 173 default: 174 if (isComparison()) { 175 return Type.OBJECT; 176 } 177 return getWidestOperationType(); 178 } 179 } 180 181 @Override 182 public Type getWidestOperationType() { 183 switch (tokenType()) { 184 case ADD: 185 case ASSIGN_ADD: { 186 // Compare this logic to decideType(Type, Type); it's similar, but it handles the optimistic type 187 // calculation case while this handles the conservative case. 188 final Type lhsType = lhs.getType(); 189 final Type rhsType = rhs.getType(); 190 if(lhsType == Type.BOOLEAN && rhsType == Type.BOOLEAN) { 191 // Will always fit in an int, as the value range is [0, 1, 2]. If we didn't treat them specially here, 192 // they'd end up being treated as generic INT operands and their sum would be conservatively considered 193 // to be a LONG in the generic case below; we can do better here. 194 return Type.INT; 195 } else if(isString(lhsType) || isString(rhsType)) { 196 // We can statically figure out that this is a string if either operand is a string. In this case, use 197 // CHARSEQUENCE to prevent it from being proactively flattened. 198 return Type.CHARSEQUENCE; 199 } 200 final Type widestOperandType = Type.widest(undefinedToNumber(booleanToInt(lhsType)), undefinedToNumber(booleanToInt(rhsType))); 201 if (widestOperandType.isNumeric()) { 202 return Type.NUMBER; 203 } 204 // We pretty much can't know what it will be statically. Must presume OBJECT conservatively, as we can end 205 // up getting either a string or an object when adding something + object, e.g.: 206 // 1 + {} == "1[object Object]", but 207 // 1 + {valueOf: function() { return 2 }} == 3. Also: 208 // 1 + {valueOf: function() { return "2" }} == "12". 209 return Type.OBJECT; 210 } 211 case SHR: 212 case ASSIGN_SHR: 213 return Type.NUMBER; 214 case ASSIGN_SAR: 215 case ASSIGN_SHL: 216 case BIT_AND: 217 case BIT_OR: 218 case BIT_XOR: 219 case ASSIGN_BIT_AND: 220 case ASSIGN_BIT_OR: 221 case ASSIGN_BIT_XOR: 222 case SAR: 223 case SHL: 224 return Type.INT; 225 case DIV: 226 case MOD: 227 case ASSIGN_DIV: 228 case ASSIGN_MOD: { 229 // Naively, one might think MOD has the same type as the widest of its operands, this is unfortunately not 230 // true when denominator is zero, so even type(int % int) == double. 231 return Type.NUMBER; 232 } 233 case MUL: 234 case SUB: 235 case ASSIGN_MUL: 236 case ASSIGN_SUB: { 237 final Type lhsType = lhs.getType(); 238 final Type rhsType = rhs.getType(); 239 if(lhsType == Type.BOOLEAN && rhsType == Type.BOOLEAN) { 240 return Type.INT; 241 } 242 return Type.NUMBER; 243 } 244 case VOID: { 245 return Type.UNDEFINED; 246 } 247 case ASSIGN: { 248 return rhs.getType(); 249 } 250 case INSTANCEOF: { 251 return Type.BOOLEAN; 252 } 253 case COMMARIGHT: { 254 return rhs.getType(); 255 } 256 case AND: 257 case OR:{ 258 return Type.widestReturnType(lhs.getType(), rhs.getType()); 259 } 260 default: 261 if (isComparison()) { 262 return Type.BOOLEAN; 263 } 264 return Type.OBJECT; 265 } 266 } 267 268 private static boolean isString(final Type type) { 269 return type == Type.STRING || type == Type.CHARSEQUENCE; 270 } 271 272 private static Type booleanToInt(final Type type) { 273 return type == Type.BOOLEAN ? Type.INT : type; 274 } 275 276 private static Type undefinedToNumber(final Type type) { 277 return type == Type.UNDEFINED ? Type.NUMBER : type; 278 } 279 280 /** 281 * Check if this node is an assignment 282 * 283 * @return true if this node assigns a value 284 */ 285 @Override 286 public boolean isAssignment() { 287 switch (tokenType()) { 288 case ASSIGN: 289 case ASSIGN_ADD: 290 case ASSIGN_BIT_AND: 291 case ASSIGN_BIT_OR: 292 case ASSIGN_BIT_XOR: 293 case ASSIGN_DIV: 294 case ASSIGN_MOD: 295 case ASSIGN_MUL: 296 case ASSIGN_SAR: 297 case ASSIGN_SHL: 298 case ASSIGN_SHR: 299 case ASSIGN_SUB: 300 return true; 301 default: 302 return false; 303 } 304 } 305 306 @Override 307 public boolean isSelfModifying() { 308 return isAssignment() && !isTokenType(TokenType.ASSIGN); 309 } 310 311 @Override 312 public Expression getAssignmentDest() { 313 return isAssignment() ? lhs() : null; 314 } 315 316 @Override 317 public BinaryNode setAssignmentDest(final Expression n) { 318 return setLHS(n); 319 } 320 321 @Override 322 public Expression getAssignmentSource() { 323 return rhs(); 324 } 325 326 /** 327 * Assist in IR navigation. 328 * @param visitor IR navigating visitor. 329 */ 330 @Override 331 public Node accept(final NodeVisitor<? extends LexicalContext> visitor) { 332 if (visitor.enterBinaryNode(this)) { 333 return visitor.leaveBinaryNode(setLHS((Expression)lhs.accept(visitor)).setRHS((Expression)rhs.accept(visitor))); 334 } 335 336 return this; 337 } 338 339 @Override 340 public boolean isLocal() { 341 switch (tokenType()) { 342 case SAR: 343 case SHL: 344 case SHR: 345 case BIT_AND: 346 case BIT_OR: 347 case BIT_XOR: 348 case ADD: 349 case DIV: 350 case MOD: 351 case MUL: 352 case SUB: 353 return lhs.isLocal() && lhs.getType().isJSPrimitive() 354 && rhs.isLocal() && rhs.getType().isJSPrimitive(); 355 case ASSIGN_ADD: 356 case ASSIGN_BIT_AND: 357 case ASSIGN_BIT_OR: 358 case ASSIGN_BIT_XOR: 359 case ASSIGN_DIV: 360 case ASSIGN_MOD: 361 case ASSIGN_MUL: 362 case ASSIGN_SAR: 363 case ASSIGN_SHL: 364 case ASSIGN_SHR: 365 case ASSIGN_SUB: 366 return lhs instanceof IdentNode && lhs.isLocal() && lhs.getType().isJSPrimitive() 367 && rhs.isLocal() && rhs.getType().isJSPrimitive(); 368 case ASSIGN: 369 return lhs instanceof IdentNode && lhs.isLocal() && rhs.isLocal(); 370 default: 371 return false; 372 } 373 } 374 375 @Override 376 public boolean isAlwaysFalse() { 377 switch (tokenType()) { 378 case COMMARIGHT: 379 return rhs.isAlwaysFalse(); 380 default: 381 return false; 382 } 383 } 384 385 @Override 386 public boolean isAlwaysTrue() { 387 switch (tokenType()) { 388 case COMMARIGHT: 389 return rhs.isAlwaysTrue(); 390 default: 391 return false; 392 } 393 } 394 395 @Override 396 public void toString(final StringBuilder sb, final boolean printType) { 397 final TokenType tokenType = tokenType(); 398 399 final boolean lhsParen = tokenType.needsParens(lhs().tokenType(), true); 400 final boolean rhsParen = tokenType.needsParens(rhs().tokenType(), false); 401 402 if (lhsParen) { 403 sb.append('('); 404 } 405 406 lhs().toString(sb, printType); 407 408 if (lhsParen) { 409 sb.append(')'); 410 } 411 412 sb.append(' '); 413 414 switch (tokenType) { 415 case COMMARIGHT: 416 sb.append(",>"); 417 break; 418 case INCPREFIX: 419 case DECPREFIX: 420 sb.append("++"); 421 break; 422 default: 423 sb.append(tokenType.getName()); 424 break; 425 } 426 427 if (isOptimistic()) { 428 sb.append(Expression.OPT_IDENTIFIER); 429 } 430 431 sb.append(' '); 432 433 if (rhsParen) { 434 sb.append('('); 435 } 436 rhs().toString(sb, printType); 437 if (rhsParen) { 438 sb.append(')'); 439 } 440 } 441 442 /** 443 * Get the left hand side expression for this node 444 * @return the left hand side expression 445 */ 446 public Expression lhs() { 447 return lhs; 448 } 449 450 /** 451 * Get the right hand side expression for this node 452 * @return the left hand side expression 453 */ 454 public Expression rhs() { 455 return rhs; 456 } 457 458 /** 459 * Set the left hand side expression for this node 460 * @param lhs new left hand side expression 461 * @return a node equivalent to this one except for the requested change. 462 */ 463 public BinaryNode setLHS(final Expression lhs) { 464 if (this.lhs == lhs) { 465 return this; 466 } 467 return new BinaryNode(this, lhs, rhs, type, programPoint); 468 } 469 470 /** 471 * Set the right hand side expression for this node 472 * @param rhs new right hand side expression 473 * @return a node equivalent to this one except for the requested change. 474 */ 475 public BinaryNode setRHS(final Expression rhs) { 476 if (this.rhs == rhs) { 477 return this; 478 } 479 return new BinaryNode(this, lhs, rhs, type, programPoint); 480 } 481 482 /** 483 * Set both the left and the right hand side expression for this node 484 * @param lhs new left hand side expression 485 * @param rhs new left hand side expression 486 * @return a node equivalent to this one except for the requested change. 487 */ 488 public BinaryNode setOperands(final Expression lhs, final Expression rhs) { 489 if (this.lhs == lhs && this.rhs == rhs) { 490 return this; 491 } 492 return new BinaryNode(this, lhs, rhs, type, programPoint); 493 } 494 495 @Override 496 public int getProgramPoint() { 497 return programPoint; 498 } 499 500 @Override 501 public boolean canBeOptimistic() { 502 return isTokenType(TokenType.ADD) || (getMostOptimisticType() != getMostPessimisticType()); 503 } 504 505 @Override 506 public BinaryNode setProgramPoint(final int programPoint) { 507 if (this.programPoint == programPoint) { 508 return this; 509 } 510 return new BinaryNode(this, lhs, rhs, type, programPoint); 511 } 512 513 @Override 514 public Type getMostOptimisticType() { 515 final TokenType tokenType = tokenType(); 516 if(tokenType == TokenType.ADD || tokenType == TokenType.ASSIGN_ADD) { 517 return OPTIMISTIC_UNDECIDED_TYPE; 518 } else if (CAN_OVERFLOW.contains(tokenType)) { 519 return Type.INT; 520 } 521 return getMostPessimisticType(); 522 } 523 524 @Override 525 public Type getMostPessimisticType() { 526 return getWidestOperationType(); 527 } 528 529 /** 530 * Returns true if the node has the optimistic type of the node is not yet decided. Optimistic ADD nodes start out 531 * as undecided until we can figure out if they're numeric or not. 532 * @return true if the node has the optimistic type of the node is not yet decided. 533 */ 534 public boolean isOptimisticUndecidedType() { 535 return type == OPTIMISTIC_UNDECIDED_TYPE; 536 } 537 538 @Override 539 public Type getType() { 540 if (cachedType == null) { 541 cachedType = getTypeUncached(); 542 } 543 return cachedType; 544 } 545 546 private Type getTypeUncached() { 547 if(type == OPTIMISTIC_UNDECIDED_TYPE) { 548 return decideType(lhs.getType(), rhs.getType()); 549 } 550 final Type widest = getWidestOperationType(); 551 if(type == null) { 552 return widest; 553 } 554 if (tokenType() == TokenType.ASSIGN_SHR || tokenType() == TokenType.SHR) { 555 return type; 556 } 557 return Type.narrowest(widest, Type.widest(type, Type.widest(lhs.getType(), rhs.getType()))); 558 } 559 560 private static Type decideType(final Type lhsType, final Type rhsType) { 561 // Compare this to getWidestOperationType() for ADD and ASSIGN_ADD cases. There's some similar logic, but these 562 // are optimistic decisions, meaning that we don't have to treat boolean addition separately (as it'll become 563 // int addition in the general case anyway), and that we also don't conservatively widen sums of ints to 564 // longs, or sums of longs to doubles. 565 if(isString(lhsType) || isString(rhsType)) { 566 return Type.CHARSEQUENCE; 567 } 568 // NOTE: We don't have optimistic object-to-(int, long) conversions. Therefore, if any operand is an Object, we 569 // bail out of optimism here and presume a conservative Object return value, as the object's ToPrimitive() can 570 // end up returning either a number or a string, and their common supertype is Object, for better or worse. 571 final Type widest = Type.widest(undefinedToNumber(booleanToInt(lhsType)), undefinedToNumber(booleanToInt(rhsType))); 572 return widest.isObject() ? Type.OBJECT : widest; 573 } 574 575 /** 576 * If the node is a node representing an add operation and has {@link #isOptimisticUndecidedType() optimistic 577 * undecided type}, decides its type. Should be invoked after its operands types have been finalized. 578 * @return returns a new node similar to this node, but with its type set to the type decided from the type of its 579 * operands. 580 */ 581 public BinaryNode decideType() { 582 assert type == OPTIMISTIC_UNDECIDED_TYPE; 583 return setType(decideType(lhs.getType(), rhs.getType())); 584 } 585 586 @Override 587 public BinaryNode setType(final Type type) { 588 if (this.type == type) { 589 return this; 590 } 591 return new BinaryNode(this, lhs, rhs, type, programPoint); 592 } 593 }