1 /* 2 * Copyright (c) 1999, 2018, 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 com.sun.tools.javac.jvm; 27 28 import java.util.function.BiConsumer; 29 30 import com.sun.tools.javac.tree.TreeInfo.PosKind; 31 import com.sun.tools.javac.util.*; 32 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 33 import com.sun.tools.javac.util.List; 34 import com.sun.tools.javac.code.*; 35 import com.sun.tools.javac.code.Attribute.TypeCompound; 36 import com.sun.tools.javac.code.Symbol.VarSymbol; 37 import com.sun.tools.javac.comp.*; 38 import com.sun.tools.javac.tree.*; 39 40 import com.sun.tools.javac.code.Symbol.*; 41 import com.sun.tools.javac.code.Type.*; 42 import com.sun.tools.javac.jvm.Code.*; 43 import com.sun.tools.javac.jvm.Items.*; 44 import com.sun.tools.javac.resources.CompilerProperties.Errors; 45 import com.sun.tools.javac.tree.EndPosTable; 46 import com.sun.tools.javac.tree.JCTree.*; 47 48 import static com.sun.tools.javac.code.Flags.*; 49 import static com.sun.tools.javac.code.Kinds.Kind.*; 50 import static com.sun.tools.javac.code.TypeTag.*; 51 import static com.sun.tools.javac.jvm.ByteCodes.*; 52 import static com.sun.tools.javac.jvm.CRTFlags.*; 53 import static com.sun.tools.javac.main.Option.*; 54 import static com.sun.tools.javac.tree.JCTree.Tag.*; 55 56 /** This pass maps flat Java (i.e. without inner classes) to bytecodes. 57 * 58 * <p><b>This is NOT part of any supported API. 59 * If you write code that depends on this, you do so at your own risk. 60 * This code and its internal interfaces are subject to change or 61 * deletion without notice.</b> 62 */ 63 public class Gen extends JCTree.Visitor { 64 protected static final Context.Key<Gen> genKey = new Context.Key<>(); 65 66 private final Log log; 67 private final Symtab syms; 68 private final Check chk; 69 private final Resolve rs; 70 private final TreeMaker make; 71 private final Names names; 72 private final Target target; 73 private final Name accessDollar; 74 private final Types types; 75 private final Lower lower; 76 private final Annotate annotate; 77 private final StringConcat concat; 78 79 /** Format of stackmap tables to be generated. */ 80 private final Code.StackMapFormat stackMap; 81 82 /** A type that serves as the expected type for all method expressions. 83 */ 84 private final Type methodType; 85 86 public static Gen instance(Context context) { 87 Gen instance = context.get(genKey); 88 if (instance == null) 89 instance = new Gen(context); 90 return instance; 91 } 92 93 /** Constant pool, reset by genClass. 94 */ 95 private final Pool pool; 96 97 protected Gen(Context context) { 98 context.put(genKey, this); 99 100 names = Names.instance(context); 101 log = Log.instance(context); 102 syms = Symtab.instance(context); 103 chk = Check.instance(context); 104 rs = Resolve.instance(context); 105 make = TreeMaker.instance(context); 106 target = Target.instance(context); 107 types = Types.instance(context); 108 concat = StringConcat.instance(context); 109 110 methodType = new MethodType(null, null, null, syms.methodClass); 111 accessDollar = names. 112 fromString("access" + target.syntheticNameChar()); 113 lower = Lower.instance(context); 114 115 Options options = Options.instance(context); 116 lineDebugInfo = 117 options.isUnset(G_CUSTOM) || 118 options.isSet(G_CUSTOM, "lines"); 119 varDebugInfo = 120 options.isUnset(G_CUSTOM) 121 ? options.isSet(G) 122 : options.isSet(G_CUSTOM, "vars"); 123 genCrt = options.isSet(XJCOV); 124 debugCode = options.isSet("debug.code"); 125 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke"); 126 pool = new Pool(types); 127 128 // ignore cldc because we cannot have both stackmap formats 129 this.stackMap = StackMapFormat.JSR202; 130 annotate = Annotate.instance(context); 131 } 132 133 /** Switches 134 */ 135 private final boolean lineDebugInfo; 136 private final boolean varDebugInfo; 137 private final boolean genCrt; 138 private final boolean debugCode; 139 private boolean disableVirtualizedPrivateInvoke; 140 141 /** Code buffer, set by genMethod. 142 */ 143 private Code code; 144 145 /** Items structure, set by genMethod. 146 */ 147 private Items items; 148 149 /** Environment for symbol lookup, set by genClass 150 */ 151 private Env<AttrContext> attrEnv; 152 153 /** The top level tree. 154 */ 155 private JCCompilationUnit toplevel; 156 157 /** The number of code-gen errors in this class. 158 */ 159 private int nerrs = 0; 160 161 /** An object containing mappings of syntax trees to their 162 * ending source positions. 163 */ 164 EndPosTable endPosTable; 165 166 boolean inCondSwitchExpression; 167 Chain switchExpressionTrueChain; 168 Chain switchExpressionFalseChain; 169 170 /** Generate code to load an integer constant. 171 * @param n The integer to be loaded. 172 */ 173 void loadIntConst(int n) { 174 items.makeImmediateItem(syms.intType, n).load(); 175 } 176 177 /** The opcode that loads a zero constant of a given type code. 178 * @param tc The given type code (@see ByteCode). 179 */ 180 public static int zero(int tc) { 181 switch(tc) { 182 case INTcode: case BYTEcode: case SHORTcode: case CHARcode: 183 return iconst_0; 184 case LONGcode: 185 return lconst_0; 186 case FLOATcode: 187 return fconst_0; 188 case DOUBLEcode: 189 return dconst_0; 190 default: 191 throw new AssertionError("zero"); 192 } 193 } 194 195 /** The opcode that loads a one constant of a given type code. 196 * @param tc The given type code (@see ByteCode). 197 */ 198 public static int one(int tc) { 199 return zero(tc) + 1; 200 } 201 202 /** Generate code to load -1 of the given type code (either int or long). 203 * @param tc The given type code (@see ByteCode). 204 */ 205 void emitMinusOne(int tc) { 206 if (tc == LONGcode) { 207 items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load(); 208 } else { 209 code.emitop0(iconst_m1); 210 } 211 } 212 213 /** Construct a symbol to reflect the qualifying type that should 214 * appear in the byte code as per JLS 13.1. 215 * 216 * For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except 217 * for those cases where we need to work around VM bugs). 218 * 219 * For {@literal target <= 1.1}: If qualified variable or method is defined in a 220 * non-accessible class, clone it with the qualifier class as owner. 221 * 222 * @param sym The accessed symbol 223 * @param site The qualifier's type. 224 */ 225 Symbol binaryQualifier(Symbol sym, Type site) { 226 227 if (site.hasTag(ARRAY)) { 228 if (sym == syms.lengthVar || 229 sym.owner != syms.arrayClass) 230 return sym; 231 // array clone can be qualified by the array type in later targets 232 Symbol qualifier = new ClassSymbol(Flags.PUBLIC, site.tsym.name, 233 site, syms.noSymbol); 234 return sym.clone(qualifier); 235 } 236 237 if (sym.owner == site.tsym || 238 (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) { 239 return sym; 240 } 241 242 // leave alone methods inherited from Object 243 // JLS 13.1. 244 if (sym.owner == syms.objectType.tsym) 245 return sym; 246 247 return sym.clone(site.tsym); 248 } 249 250 /** Insert a reference to given type in the constant pool, 251 * checking for an array with too many dimensions; 252 * return the reference's index. 253 * @param type The type for which a reference is inserted. 254 */ 255 int makeRef(DiagnosticPosition pos, Type type) { 256 checkDimension(pos, type); 257 if (type.isAnnotated()) { 258 return pool.put((Object)type); 259 } else { 260 return pool.put(type.hasTag(CLASS) ? (Object)type.tsym : (Object)type); 261 } 262 } 263 264 /** Check if the given type is an array with too many dimensions. 265 */ 266 private void checkDimension(DiagnosticPosition pos, Type t) { 267 switch (t.getTag()) { 268 case METHOD: 269 checkDimension(pos, t.getReturnType()); 270 for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail) 271 checkDimension(pos, args.head); 272 break; 273 case ARRAY: 274 if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) { 275 log.error(pos, Errors.LimitDimensions); 276 nerrs++; 277 } 278 break; 279 default: 280 break; 281 } 282 } 283 284 /** Create a tempory variable. 285 * @param type The variable's type. 286 */ 287 LocalItem makeTemp(Type type) { 288 VarSymbol v = new VarSymbol(Flags.SYNTHETIC, 289 names.empty, 290 type, 291 env.enclMethod.sym); 292 code.newLocal(v); 293 return items.makeLocalItem(v); 294 } 295 296 /** Generate code to call a non-private method or constructor. 297 * @param pos Position to be used for error reporting. 298 * @param site The type of which the method is a member. 299 * @param name The method's name. 300 * @param argtypes The method's argument types. 301 * @param isStatic A flag that indicates whether we call a 302 * static or instance method. 303 */ 304 void callMethod(DiagnosticPosition pos, 305 Type site, Name name, List<Type> argtypes, 306 boolean isStatic) { 307 Symbol msym = rs. 308 resolveInternalMethod(pos, attrEnv, site, name, argtypes, null); 309 if (isStatic) items.makeStaticItem(msym).invoke(); 310 else items.makeMemberItem(msym, name == names.init).invoke(); 311 } 312 313 /** Is the given method definition an access method 314 * resulting from a qualified super? This is signified by an odd 315 * access code. 316 */ 317 private boolean isAccessSuper(JCMethodDecl enclMethod) { 318 return 319 (enclMethod.mods.flags & SYNTHETIC) != 0 && 320 isOddAccessName(enclMethod.name); 321 } 322 323 /** Does given name start with "access$" and end in an odd digit? 324 */ 325 private boolean isOddAccessName(Name name) { 326 return 327 name.startsWith(accessDollar) && 328 (name.getByteAt(name.getByteLength() - 1) & 1) == 1; 329 } 330 331 /* ************************************************************************ 332 * Non-local exits 333 *************************************************************************/ 334 335 /** Generate code to invoke the finalizer associated with given 336 * environment. 337 * Any calls to finalizers are appended to the environments `cont' chain. 338 * Mark beginning of gap in catch all range for finalizer. 339 */ 340 void genFinalizer(Env<GenContext> env) { 341 if (code.isAlive() && env.info.finalize != null) 342 env.info.finalize.gen(); 343 } 344 345 /** Generate code to call all finalizers of structures aborted by 346 * a non-local 347 * exit. Return target environment of the non-local exit. 348 * @param target The tree representing the structure that's aborted 349 * @param env The environment current at the non-local exit. 350 */ 351 Env<GenContext> unwind(JCTree target, Env<GenContext> env) { 352 Env<GenContext> env1 = env; 353 while (true) { 354 genFinalizer(env1); 355 if (env1.tree == target) break; 356 env1 = env1.next; 357 } 358 return env1; 359 } 360 361 /** Mark end of gap in catch-all range for finalizer. 362 * @param env the environment which might contain the finalizer 363 * (if it does, env.info.gaps != null). 364 */ 365 void endFinalizerGap(Env<GenContext> env) { 366 if (env.info.gaps != null && env.info.gaps.length() % 2 == 1) 367 env.info.gaps.append(code.curCP()); 368 } 369 370 /** Mark end of all gaps in catch-all ranges for finalizers of environments 371 * lying between, and including to two environments. 372 * @param from the most deeply nested environment to mark 373 * @param to the least deeply nested environment to mark 374 */ 375 void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) { 376 Env<GenContext> last = null; 377 while (last != to) { 378 endFinalizerGap(from); 379 last = from; 380 from = from.next; 381 } 382 } 383 384 /** Do any of the structures aborted by a non-local exit have 385 * finalizers that require an empty stack? 386 * @param target The tree representing the structure that's aborted 387 * @param env The environment current at the non-local exit. 388 */ 389 boolean hasFinally(JCTree target, Env<GenContext> env) { 390 while (env.tree != target) { 391 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer()) 392 return true; 393 env = env.next; 394 } 395 return false; 396 } 397 398 /* ************************************************************************ 399 * Normalizing class-members. 400 *************************************************************************/ 401 402 /** Distribute member initializer code into constructors and {@code <clinit>} 403 * method. 404 * @param defs The list of class member declarations. 405 * @param c The enclosing class. 406 */ 407 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) { 408 ListBuffer<JCStatement> initCode = new ListBuffer<>(); 409 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>(); 410 ListBuffer<JCStatement> clinitCode = new ListBuffer<>(); 411 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>(); 412 ListBuffer<JCTree> methodDefs = new ListBuffer<>(); 413 // Sort definitions into three listbuffers: 414 // - initCode for instance initializers 415 // - clinitCode for class initializers 416 // - methodDefs for method definitions 417 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) { 418 JCTree def = l.head; 419 switch (def.getTag()) { 420 case BLOCK: 421 JCBlock block = (JCBlock)def; 422 if ((block.flags & STATIC) != 0) 423 clinitCode.append(block); 424 else if ((block.flags & SYNTHETIC) == 0) 425 initCode.append(block); 426 break; 427 case METHODDEF: 428 methodDefs.append(def); 429 break; 430 case VARDEF: 431 JCVariableDecl vdef = (JCVariableDecl) def; 432 VarSymbol sym = vdef.sym; 433 checkDimension(vdef.pos(), sym.type); 434 if (vdef.init != null) { 435 if ((sym.flags() & STATIC) == 0) { 436 // Always initialize instance variables. 437 JCStatement init = make.at(vdef.pos()). 438 Assignment(sym, vdef.init); 439 initCode.append(init); 440 endPosTable.replaceTree(vdef, init); 441 initTAs.addAll(getAndRemoveNonFieldTAs(sym)); 442 } else if (sym.getConstValue() == null) { 443 // Initialize class (static) variables only if 444 // they are not compile-time constants. 445 JCStatement init = make.at(vdef.pos). 446 Assignment(sym, vdef.init); 447 clinitCode.append(init); 448 endPosTable.replaceTree(vdef, init); 449 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym)); 450 } else { 451 checkStringConstant(vdef.init.pos(), sym.getConstValue()); 452 /* if the init contains a reference to an external class, add it to the 453 * constant's pool 454 */ 455 vdef.init.accept(classReferenceVisitor); 456 } 457 } 458 break; 459 default: 460 Assert.error(); 461 } 462 } 463 // Insert any instance initializers into all constructors. 464 if (initCode.length() != 0) { 465 List<JCStatement> inits = initCode.toList(); 466 initTAs.addAll(c.getInitTypeAttributes()); 467 List<Attribute.TypeCompound> initTAlist = initTAs.toList(); 468 for (JCTree t : methodDefs) { 469 normalizeMethod((JCMethodDecl)t, inits, initTAlist); 470 } 471 } 472 // If there are class initializers, create a <clinit> method 473 // that contains them as its body. 474 if (clinitCode.length() != 0) { 475 MethodSymbol clinit = new MethodSymbol( 476 STATIC | (c.flags() & STRICTFP), 477 names.clinit, 478 new MethodType( 479 List.nil(), syms.voidType, 480 List.nil(), syms.methodClass), 481 c); 482 c.members().enter(clinit); 483 List<JCStatement> clinitStats = clinitCode.toList(); 484 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats); 485 block.endpos = TreeInfo.endPos(clinitStats.last()); 486 methodDefs.append(make.MethodDef(clinit, block)); 487 488 if (!clinitTAs.isEmpty()) 489 clinit.appendUniqueTypeAttributes(clinitTAs.toList()); 490 if (!c.getClassInitTypeAttributes().isEmpty()) 491 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes()); 492 } 493 // Return all method definitions. 494 return methodDefs.toList(); 495 } 496 497 private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) { 498 List<TypeCompound> tas = sym.getRawTypeAttributes(); 499 ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<>(); 500 ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>(); 501 for (TypeCompound ta : tas) { 502 Assert.check(ta.getPosition().type != TargetType.UNKNOWN); 503 if (ta.getPosition().type == TargetType.FIELD) { 504 fieldTAs.add(ta); 505 } else { 506 nonfieldTAs.add(ta); 507 } 508 } 509 sym.setTypeAttributes(fieldTAs.toList()); 510 return nonfieldTAs.toList(); 511 } 512 513 /** Check a constant value and report if it is a string that is 514 * too large. 515 */ 516 private void checkStringConstant(DiagnosticPosition pos, Object constValue) { 517 if (nerrs != 0 || // only complain about a long string once 518 constValue == null || 519 !(constValue instanceof String) || 520 ((String)constValue).length() < Pool.MAX_STRING_LENGTH) 521 return; 522 log.error(pos, Errors.LimitString); 523 nerrs++; 524 } 525 526 /** Insert instance initializer code into initial constructor. 527 * @param md The tree potentially representing a 528 * constructor's definition. 529 * @param initCode The list of instance initializer statements. 530 * @param initTAs Type annotations from the initializer expression. 531 */ 532 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) { 533 if (md.name == names.init && TreeInfo.isInitialConstructor(md)) { 534 // We are seeing a constructor that does not call another 535 // constructor of the same class. 536 List<JCStatement> stats = md.body.stats; 537 ListBuffer<JCStatement> newstats = new ListBuffer<>(); 538 539 if (stats.nonEmpty()) { 540 // Copy initializers of synthetic variables generated in 541 // the translation of inner classes. 542 while (TreeInfo.isSyntheticInit(stats.head)) { 543 newstats.append(stats.head); 544 stats = stats.tail; 545 } 546 // Copy superclass constructor call 547 newstats.append(stats.head); 548 stats = stats.tail; 549 // Copy remaining synthetic initializers. 550 while (stats.nonEmpty() && 551 TreeInfo.isSyntheticInit(stats.head)) { 552 newstats.append(stats.head); 553 stats = stats.tail; 554 } 555 // Now insert the initializer code. 556 newstats.appendList(initCode); 557 // And copy all remaining statements. 558 while (stats.nonEmpty()) { 559 newstats.append(stats.head); 560 stats = stats.tail; 561 } 562 } 563 md.body.stats = newstats.toList(); 564 if (md.body.endpos == Position.NOPOS) 565 md.body.endpos = TreeInfo.endPos(md.body.stats.last()); 566 567 md.sym.appendUniqueTypeAttributes(initTAs); 568 } 569 } 570 571 /* ************************************************************************ 572 * Traversal methods 573 *************************************************************************/ 574 575 /** Visitor argument: The current environment. 576 */ 577 Env<GenContext> env; 578 579 /** Visitor argument: The expected type (prototype). 580 */ 581 Type pt; 582 583 /** Visitor result: The item representing the computed value. 584 */ 585 Item result; 586 587 /** Visitor method: generate code for a definition, catching and reporting 588 * any completion failures. 589 * @param tree The definition to be visited. 590 * @param env The environment current at the definition. 591 */ 592 public void genDef(JCTree tree, Env<GenContext> env) { 593 Env<GenContext> prevEnv = this.env; 594 try { 595 this.env = env; 596 tree.accept(this); 597 } catch (CompletionFailure ex) { 598 chk.completionError(tree.pos(), ex); 599 } finally { 600 this.env = prevEnv; 601 } 602 } 603 604 /** Derived visitor method: check whether CharacterRangeTable 605 * should be emitted, if so, put a new entry into CRTable 606 * and call method to generate bytecode. 607 * If not, just call method to generate bytecode. 608 * @see #genStat(JCTree, Env) 609 * 610 * @param tree The tree to be visited. 611 * @param env The environment to use. 612 * @param crtFlags The CharacterRangeTable flags 613 * indicating type of the entry. 614 */ 615 public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) { 616 if (!genCrt) { 617 genStat(tree, env); 618 return; 619 } 620 int startpc = code.curCP(); 621 genStat(tree, env); 622 if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK; 623 code.crt.put(tree, crtFlags, startpc, code.curCP()); 624 } 625 626 /** Derived visitor method: generate code for a statement. 627 */ 628 public void genStat(JCTree tree, Env<GenContext> env) { 629 if (code.isAlive()) { 630 code.statBegin(tree.pos); 631 genDef(tree, env); 632 } else if (env.info.isSwitch && tree.hasTag(VARDEF)) { 633 // variables whose declarations are in a switch 634 // can be used even if the decl is unreachable. 635 code.newLocal(((JCVariableDecl) tree).sym); 636 } 637 } 638 639 /** Derived visitor method: check whether CharacterRangeTable 640 * should be emitted, if so, put a new entry into CRTable 641 * and call method to generate bytecode. 642 * If not, just call method to generate bytecode. 643 * @see #genStats(List, Env) 644 * 645 * @param trees The list of trees to be visited. 646 * @param env The environment to use. 647 * @param crtFlags The CharacterRangeTable flags 648 * indicating type of the entry. 649 */ 650 public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) { 651 if (!genCrt) { 652 genStats(trees, env); 653 return; 654 } 655 if (trees.length() == 1) { // mark one statement with the flags 656 genStat(trees.head, env, crtFlags | CRT_STATEMENT); 657 } else { 658 int startpc = code.curCP(); 659 genStats(trees, env); 660 code.crt.put(trees, crtFlags, startpc, code.curCP()); 661 } 662 } 663 664 /** Derived visitor method: generate code for a list of statements. 665 */ 666 public void genStats(List<? extends JCTree> trees, Env<GenContext> env) { 667 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 668 genStat(l.head, env, CRT_STATEMENT); 669 } 670 671 /** Derived visitor method: check whether CharacterRangeTable 672 * should be emitted, if so, put a new entry into CRTable 673 * and call method to generate bytecode. 674 * If not, just call method to generate bytecode. 675 * @see #genCond(JCTree,boolean) 676 * 677 * @param tree The tree to be visited. 678 * @param crtFlags The CharacterRangeTable flags 679 * indicating type of the entry. 680 */ 681 public CondItem genCond(JCTree tree, int crtFlags) { 682 if (!genCrt) return genCond(tree, false); 683 int startpc = code.curCP(); 684 CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0); 685 code.crt.put(tree, crtFlags, startpc, code.curCP()); 686 return item; 687 } 688 689 /** Derived visitor method: generate code for a boolean 690 * expression in a control-flow context. 691 * @param _tree The expression to be visited. 692 * @param markBranches The flag to indicate that the condition is 693 * a flow controller so produced conditions 694 * should contain a proper tree to generate 695 * CharacterRangeTable branches for them. 696 */ 697 public CondItem genCond(JCTree _tree, boolean markBranches) { 698 JCTree inner_tree = TreeInfo.skipParens(_tree); 699 if (inner_tree.hasTag(CONDEXPR)) { 700 JCConditional tree = (JCConditional)inner_tree; 701 CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER); 702 if (cond.isTrue()) { 703 code.resolve(cond.trueJumps); 704 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET); 705 if (markBranches) result.tree = tree.truepart; 706 return result; 707 } 708 if (cond.isFalse()) { 709 code.resolve(cond.falseJumps); 710 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET); 711 if (markBranches) result.tree = tree.falsepart; 712 return result; 713 } 714 Chain secondJumps = cond.jumpFalse(); 715 code.resolve(cond.trueJumps); 716 CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET); 717 if (markBranches) first.tree = tree.truepart; 718 Chain falseJumps = first.jumpFalse(); 719 code.resolve(first.trueJumps); 720 Chain trueJumps = code.branch(goto_); 721 code.resolve(secondJumps); 722 CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET); 723 CondItem result = items.makeCondItem(second.opcode, 724 Code.mergeChains(trueJumps, second.trueJumps), 725 Code.mergeChains(falseJumps, second.falseJumps)); 726 if (markBranches) result.tree = tree.falsepart; 727 return result; 728 } else if (inner_tree.hasTag(SWITCH_EXPRESSION)) { 729 boolean prevInCondSwitchExpression = inCondSwitchExpression; 730 Chain prevSwitchExpressionTrueChain = switchExpressionTrueChain; 731 Chain prevSwitchExpressionFalseChain = switchExpressionFalseChain; 732 try { 733 inCondSwitchExpression = true; 734 switchExpressionTrueChain = null; 735 switchExpressionFalseChain = null; 736 try { 737 doHandleSwitchExpression((JCSwitchExpression) inner_tree); 738 } catch (CompletionFailure ex) { 739 chk.completionError(_tree.pos(), ex); 740 code.state.stacksize = 1; 741 } 742 CondItem result = items.makeCondItem(goto_, 743 switchExpressionTrueChain, 744 switchExpressionFalseChain); 745 if (markBranches) result.tree = _tree; 746 return result; 747 } finally { 748 inCondSwitchExpression = prevInCondSwitchExpression; 749 switchExpressionTrueChain = prevSwitchExpressionTrueChain; 750 switchExpressionFalseChain = prevSwitchExpressionFalseChain; 751 } 752 } else if (inner_tree.hasTag(LETEXPR) && ((LetExpr) inner_tree).needsCond) { 753 LetExpr tree = (LetExpr) inner_tree; 754 int limit = code.nextreg; 755 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 756 try { 757 genStats(tree.defs, env); 758 } finally { 759 code.setLetExprStackPos(prevLetExprStart); 760 } 761 CondItem result = genCond(tree.expr, markBranches); 762 code.endScopes(limit); 763 return result; 764 } else { 765 CondItem result = genExpr(_tree, syms.booleanType).mkCond(); 766 if (markBranches) result.tree = _tree; 767 return result; 768 } 769 } 770 771 public Code getCode() { 772 return code; 773 } 774 775 public Items getItems() { 776 return items; 777 } 778 779 public Env<AttrContext> getAttrEnv() { 780 return attrEnv; 781 } 782 783 /** Visitor class for expressions which might be constant expressions. 784 * This class is a subset of TreeScanner. Intended to visit trees pruned by 785 * Lower as long as constant expressions looking for references to any 786 * ClassSymbol. Any such reference will be added to the constant pool so 787 * automated tools can detect class dependencies better. 788 */ 789 class ClassReferenceVisitor extends JCTree.Visitor { 790 791 @Override 792 public void visitTree(JCTree tree) {} 793 794 @Override 795 public void visitBinary(JCBinary tree) { 796 tree.lhs.accept(this); 797 tree.rhs.accept(this); 798 } 799 800 @Override 801 public void visitSelect(JCFieldAccess tree) { 802 if (tree.selected.type.hasTag(CLASS)) { 803 makeRef(tree.selected.pos(), tree.selected.type); 804 } 805 } 806 807 @Override 808 public void visitIdent(JCIdent tree) { 809 if (tree.sym.owner instanceof ClassSymbol) { 810 pool.put(tree.sym.owner); 811 } 812 } 813 814 @Override 815 public void visitConditional(JCConditional tree) { 816 tree.cond.accept(this); 817 tree.truepart.accept(this); 818 tree.falsepart.accept(this); 819 } 820 821 @Override 822 public void visitUnary(JCUnary tree) { 823 tree.arg.accept(this); 824 } 825 826 @Override 827 public void visitParens(JCParens tree) { 828 tree.expr.accept(this); 829 } 830 831 @Override 832 public void visitTypeCast(JCTypeCast tree) { 833 tree.expr.accept(this); 834 } 835 } 836 837 private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor(); 838 839 /** Visitor method: generate code for an expression, catching and reporting 840 * any completion failures. 841 * @param tree The expression to be visited. 842 * @param pt The expression's expected type (proto-type). 843 */ 844 public Item genExpr(JCTree tree, Type pt) { 845 Type prevPt = this.pt; 846 try { 847 if (tree.type.constValue() != null) { 848 // Short circuit any expressions which are constants 849 tree.accept(classReferenceVisitor); 850 checkStringConstant(tree.pos(), tree.type.constValue()); 851 result = items.makeImmediateItem(tree.type, tree.type.constValue()); 852 } else { 853 this.pt = pt; 854 tree.accept(this); 855 } 856 return result.coerce(pt); 857 } catch (CompletionFailure ex) { 858 chk.completionError(tree.pos(), ex); 859 code.state.stacksize = 1; 860 return items.makeStackItem(pt); 861 } finally { 862 this.pt = prevPt; 863 } 864 } 865 866 /** Derived visitor method: generate code for a list of method arguments. 867 * @param trees The argument expressions to be visited. 868 * @param pts The expression's expected types (i.e. the formal parameter 869 * types of the invoked method). 870 */ 871 public void genArgs(List<JCExpression> trees, List<Type> pts) { 872 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { 873 genExpr(l.head, pts.head).load(); 874 pts = pts.tail; 875 } 876 // require lists be of same length 877 Assert.check(pts.isEmpty()); 878 } 879 880 /* ************************************************************************ 881 * Visitor methods for statements and definitions 882 *************************************************************************/ 883 884 /** Thrown when the byte code size exceeds limit. 885 */ 886 public static class CodeSizeOverflow extends RuntimeException { 887 private static final long serialVersionUID = 0; 888 public CodeSizeOverflow() {} 889 } 890 891 public void visitMethodDef(JCMethodDecl tree) { 892 // Create a new local environment that points pack at method 893 // definition. 894 Env<GenContext> localEnv = env.dup(tree); 895 localEnv.enclMethod = tree; 896 // The expected type of every return statement in this method 897 // is the method's return type. 898 this.pt = tree.sym.erasure(types).getReturnType(); 899 900 checkDimension(tree.pos(), tree.sym.erasure(types)); 901 genMethod(tree, localEnv, false); 902 } 903 //where 904 /** Generate code for a method. 905 * @param tree The tree representing the method definition. 906 * @param env The environment current for the method body. 907 * @param fatcode A flag that indicates whether all jumps are 908 * within 32K. We first invoke this method under 909 * the assumption that fatcode == false, i.e. all 910 * jumps are within 32K. If this fails, fatcode 911 * is set to true and we try again. 912 */ 913 void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 914 MethodSymbol meth = tree.sym; 915 int extras = 0; 916 // Count up extra parameters 917 if (meth.isConstructor()) { 918 extras++; 919 if (meth.enclClass().isInner() && 920 !meth.enclClass().isStatic()) { 921 extras++; 922 } 923 } else if ((tree.mods.flags & STATIC) == 0) { 924 extras++; 925 } 926 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG 927 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras > 928 ClassFile.MAX_PARAMETERS) { 929 log.error(tree.pos(), Errors.LimitParameters); 930 nerrs++; 931 } 932 933 else if (tree.body != null) { 934 // Create a new code structure and initialize it. 935 int startpcCrt = initCode(tree, env, fatcode); 936 937 try { 938 genStat(tree.body, env); 939 } catch (CodeSizeOverflow e) { 940 // Failed due to code limit, try again with jsr/ret 941 startpcCrt = initCode(tree, env, fatcode); 942 genStat(tree.body, env); 943 } 944 945 if (code.state.stacksize != 0) { 946 log.error(tree.body.pos(), Errors.StackSimError(tree.sym)); 947 throw new AssertionError(); 948 } 949 950 // If last statement could complete normally, insert a 951 // return at the end. 952 if (code.isAlive()) { 953 code.statBegin(TreeInfo.endPos(tree.body)); 954 if (env.enclMethod == null || 955 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) { 956 code.emitop0(return_); 957 } else { 958 // sometime dead code seems alive (4415991); 959 // generate a small loop instead 960 int startpc = code.entryPoint(); 961 CondItem c = items.makeCondItem(goto_); 962 code.resolve(c.jumpTrue(), startpc); 963 } 964 } 965 if (genCrt) 966 code.crt.put(tree.body, 967 CRT_BLOCK, 968 startpcCrt, 969 code.curCP()); 970 971 code.endScopes(0); 972 973 // If we exceeded limits, panic 974 if (code.checkLimits(tree.pos(), log)) { 975 nerrs++; 976 return; 977 } 978 979 // If we generated short code but got a long jump, do it again 980 // with fatCode = true. 981 if (!fatcode && code.fatcode) genMethod(tree, env, true); 982 983 // Clean up 984 if(stackMap == StackMapFormat.JSR202) { 985 code.lastFrame = null; 986 code.frameBeforeLast = null; 987 } 988 989 // Compress exception table 990 code.compressCatchTable(); 991 992 // Fill in type annotation positions for exception parameters 993 code.fillExceptionParameterPositions(); 994 } 995 } 996 997 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 998 MethodSymbol meth = tree.sym; 999 1000 // Create a new code structure. 1001 meth.code = code = new Code(meth, 1002 fatcode, 1003 lineDebugInfo ? toplevel.lineMap : null, 1004 varDebugInfo, 1005 stackMap, 1006 debugCode, 1007 genCrt ? new CRTable(tree, env.toplevel.endPositions) 1008 : null, 1009 syms, 1010 types, 1011 pool); 1012 items = new Items(pool, code, syms, types); 1013 if (code.debugCode) { 1014 System.err.println(meth + " for body " + tree); 1015 } 1016 1017 // If method is not static, create a new local variable address 1018 // for `this'. 1019 if ((tree.mods.flags & STATIC) == 0) { 1020 Type selfType = meth.owner.type; 1021 if (meth.isConstructor() && selfType != syms.objectType) 1022 selfType = UninitializedType.uninitializedThis(selfType); 1023 code.setDefined( 1024 code.newLocal( 1025 new VarSymbol(FINAL, names._this, selfType, meth.owner))); 1026 } 1027 1028 // Mark all parameters as defined from the beginning of 1029 // the method. 1030 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 1031 checkDimension(l.head.pos(), l.head.sym.type); 1032 code.setDefined(code.newLocal(l.head.sym)); 1033 } 1034 1035 // Get ready to generate code for method body. 1036 int startpcCrt = genCrt ? code.curCP() : 0; 1037 code.entryPoint(); 1038 1039 // Suppress initial stackmap 1040 code.pendingStackMap = false; 1041 1042 return startpcCrt; 1043 } 1044 1045 public void visitVarDef(JCVariableDecl tree) { 1046 VarSymbol v = tree.sym; 1047 if (tree.init != null) { 1048 checkStringConstant(tree.init.pos(), v.getConstValue()); 1049 if (v.getConstValue() == null || varDebugInfo) { 1050 Assert.check(code.isStatementStart()); 1051 code.newLocal(v); 1052 genExpr(tree.init, v.erasure(types)).load(); 1053 items.makeLocalItem(v).store(); 1054 Assert.check(code.isStatementStart()); 1055 } 1056 } else { 1057 code.newLocal(v); 1058 } 1059 checkDimension(tree.pos(), v.type); 1060 } 1061 1062 public void visitSkip(JCSkip tree) { 1063 } 1064 1065 public void visitBlock(JCBlock tree) { 1066 int limit = code.nextreg; 1067 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1068 genStats(tree.stats, localEnv); 1069 // End the scope of all block-local variables in variable info. 1070 if (!env.tree.hasTag(METHODDEF)) { 1071 code.statBegin(tree.endpos); 1072 code.endScopes(limit); 1073 code.pendingStatPos = Position.NOPOS; 1074 } 1075 } 1076 1077 public void visitDoLoop(JCDoWhileLoop tree) { 1078 genLoop(tree, tree.body, tree.cond, List.nil(), false); 1079 } 1080 1081 public void visitWhileLoop(JCWhileLoop tree) { 1082 genLoop(tree, tree.body, tree.cond, List.nil(), true); 1083 } 1084 1085 public void visitForLoop(JCForLoop tree) { 1086 int limit = code.nextreg; 1087 genStats(tree.init, env); 1088 genLoop(tree, tree.body, tree.cond, tree.step, true); 1089 code.endScopes(limit); 1090 } 1091 //where 1092 /** Generate code for a loop. 1093 * @param loop The tree representing the loop. 1094 * @param body The loop's body. 1095 * @param cond The loop's controling condition. 1096 * @param step "Step" statements to be inserted at end of 1097 * each iteration. 1098 * @param testFirst True if the loop test belongs before the body. 1099 */ 1100 private void genLoop(JCStatement loop, 1101 JCStatement body, 1102 JCExpression cond, 1103 List<JCExpressionStatement> step, 1104 boolean testFirst) { 1105 Env<GenContext> loopEnv = env.dup(loop, new GenContext()); 1106 int startpc = code.entryPoint(); 1107 if (testFirst) { //while or for loop 1108 CondItem c; 1109 if (cond != null) { 1110 code.statBegin(cond.pos); 1111 Assert.check(code.isStatementStart()); 1112 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1113 } else { 1114 c = items.makeCondItem(goto_); 1115 } 1116 Chain loopDone = c.jumpFalse(); 1117 code.resolve(c.trueJumps); 1118 Assert.check(code.isStatementStart()); 1119 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1120 code.resolve(loopEnv.info.cont); 1121 genStats(step, loopEnv); 1122 code.resolve(code.branch(goto_), startpc); 1123 code.resolve(loopDone); 1124 } else { 1125 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1126 code.resolve(loopEnv.info.cont); 1127 genStats(step, loopEnv); 1128 if (code.isAlive()) { 1129 CondItem c; 1130 if (cond != null) { 1131 code.statBegin(cond.pos); 1132 Assert.check(code.isStatementStart()); 1133 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1134 } else { 1135 c = items.makeCondItem(goto_); 1136 } 1137 code.resolve(c.jumpTrue(), startpc); 1138 Assert.check(code.isStatementStart()); 1139 code.resolve(c.falseJumps); 1140 } 1141 } 1142 Chain exit = loopEnv.info.exit; 1143 if (exit != null) { 1144 code.resolve(exit); 1145 exit.state.defined.excludeFrom(code.nextreg); 1146 } 1147 } 1148 1149 public void visitForeachLoop(JCEnhancedForLoop tree) { 1150 throw new AssertionError(); // should have been removed by Lower. 1151 } 1152 1153 public void visitLabelled(JCLabeledStatement tree) { 1154 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1155 genStat(tree.body, localEnv, CRT_STATEMENT); 1156 Chain exit = localEnv.info.exit; 1157 if (exit != null) { 1158 code.resolve(exit); 1159 exit.state.defined.excludeFrom(code.nextreg); 1160 } 1161 } 1162 1163 public void visitSwitch(JCSwitch tree) { 1164 handleSwitch(tree, tree.selector, tree.cases); 1165 } 1166 1167 @Override 1168 public void visitSwitchExpression(JCSwitchExpression tree) { 1169 code.resolvePending(); 1170 boolean prevInCondSwitchExpression = inCondSwitchExpression; 1171 try { 1172 inCondSwitchExpression = false; 1173 doHandleSwitchExpression(tree); 1174 } finally { 1175 inCondSwitchExpression = prevInCondSwitchExpression; 1176 } 1177 result = items.makeStackItem(pt); 1178 } 1179 1180 private void doHandleSwitchExpression(JCSwitchExpression tree) { 1181 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 1182 try { 1183 handleSwitch(tree, tree.selector, tree.cases); 1184 } finally { 1185 code.setLetExprStackPos(prevLetExprStart); 1186 } 1187 } 1188 1189 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases) { 1190 int limit = code.nextreg; 1191 Assert.check(!selector.type.hasTag(CLASS)); 1192 int startpcCrt = genCrt ? code.curCP() : 0; 1193 Assert.check(code.isStatementStart()); 1194 Item sel = genExpr(selector, syms.intType); 1195 if (cases.isEmpty()) { 1196 // We are seeing: switch <sel> {} 1197 sel.load().drop(); 1198 if (genCrt) 1199 code.crt.put(TreeInfo.skipParens(selector), 1200 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1201 } else { 1202 // We are seeing a nonempty switch. 1203 sel.load(); 1204 if (genCrt) 1205 code.crt.put(TreeInfo.skipParens(selector), 1206 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1207 Env<GenContext> switchEnv = env.dup(swtch, new GenContext()); 1208 switchEnv.info.isSwitch = true; 1209 1210 // Compute number of labels and minimum and maximum label values. 1211 // For each case, store its label in an array. 1212 int lo = Integer.MAX_VALUE; // minimum label. 1213 int hi = Integer.MIN_VALUE; // maximum label. 1214 int nlabels = 0; // number of labels. 1215 1216 int[] labels = new int[cases.length()]; // the label array. 1217 int defaultIndex = -1; // the index of the default clause. 1218 1219 List<JCCase> l = cases; 1220 for (int i = 0; i < labels.length; i++) { 1221 if (l.head.pats.nonEmpty()) { 1222 Assert.check(l.head.pats.size() == 1); 1223 int val = ((Number)l.head.pats.head.type.constValue()).intValue(); 1224 labels[i] = val; 1225 if (val < lo) lo = val; 1226 if (hi < val) hi = val; 1227 nlabels++; 1228 } else { 1229 Assert.check(defaultIndex == -1); 1230 defaultIndex = i; 1231 } 1232 l = l.tail; 1233 } 1234 1235 // Determine whether to issue a tableswitch or a lookupswitch 1236 // instruction. 1237 long table_space_cost = 4 + ((long) hi - lo + 1); // words 1238 long table_time_cost = 3; // comparisons 1239 long lookup_space_cost = 3 + 2 * (long) nlabels; 1240 long lookup_time_cost = nlabels; 1241 int opcode = 1242 nlabels > 0 && 1243 table_space_cost + 3 * table_time_cost <= 1244 lookup_space_cost + 3 * lookup_time_cost 1245 ? 1246 tableswitch : lookupswitch; 1247 1248 int startpc = code.curCP(); // the position of the selector operation 1249 code.emitop0(opcode); 1250 code.align(4); 1251 int tableBase = code.curCP(); // the start of the jump table 1252 int[] offsets = null; // a table of offsets for a lookupswitch 1253 code.emit4(-1); // leave space for default offset 1254 if (opcode == tableswitch) { 1255 code.emit4(lo); // minimum label 1256 code.emit4(hi); // maximum label 1257 for (long i = lo; i <= hi; i++) { // leave space for jump table 1258 code.emit4(-1); 1259 } 1260 } else { 1261 code.emit4(nlabels); // number of labels 1262 for (int i = 0; i < nlabels; i++) { 1263 code.emit4(-1); code.emit4(-1); // leave space for lookup table 1264 } 1265 offsets = new int[labels.length]; 1266 } 1267 Code.State stateSwitch = code.state.dup(); 1268 code.markDead(); 1269 1270 // For each case do: 1271 l = cases; 1272 for (int i = 0; i < labels.length; i++) { 1273 JCCase c = l.head; 1274 l = l.tail; 1275 1276 int pc = code.entryPoint(stateSwitch); 1277 // Insert offset directly into code or else into the 1278 // offsets table. 1279 if (i != defaultIndex) { 1280 if (opcode == tableswitch) { 1281 code.put4( 1282 tableBase + 4 * (labels[i] - lo + 3), 1283 pc - startpc); 1284 } else { 1285 offsets[i] = pc - startpc; 1286 } 1287 } else { 1288 code.put4(tableBase, pc - startpc); 1289 } 1290 1291 // Generate code for the statements in this case. 1292 genStats(c.stats, switchEnv, CRT_FLOW_TARGET); 1293 } 1294 1295 // Resolve all breaks. 1296 Chain exit = switchEnv.info.exit; 1297 if (exit != null) { 1298 code.resolve(exit); 1299 exit.state.defined.excludeFrom(limit); 1300 } 1301 1302 // If we have not set the default offset, we do so now. 1303 if (code.get4(tableBase) == -1) { 1304 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1305 } 1306 1307 if (opcode == tableswitch) { 1308 // Let any unfilled slots point to the default case. 1309 int defaultOffset = code.get4(tableBase); 1310 for (long i = lo; i <= hi; i++) { 1311 int t = (int)(tableBase + 4 * (i - lo + 3)); 1312 if (code.get4(t) == -1) 1313 code.put4(t, defaultOffset); 1314 } 1315 } else { 1316 // Sort non-default offsets and copy into lookup table. 1317 if (defaultIndex >= 0) 1318 for (int i = defaultIndex; i < labels.length - 1; i++) { 1319 labels[i] = labels[i+1]; 1320 offsets[i] = offsets[i+1]; 1321 } 1322 if (nlabels > 0) 1323 qsort2(labels, offsets, 0, nlabels - 1); 1324 for (int i = 0; i < nlabels; i++) { 1325 int caseidx = tableBase + 8 * (i + 1); 1326 code.put4(caseidx, labels[i]); 1327 code.put4(caseidx + 4, offsets[i]); 1328 } 1329 } 1330 } 1331 code.endScopes(limit); 1332 } 1333 //where 1334 /** Sort (int) arrays of keys and values 1335 */ 1336 static void qsort2(int[] keys, int[] values, int lo, int hi) { 1337 int i = lo; 1338 int j = hi; 1339 int pivot = keys[(i+j)/2]; 1340 do { 1341 while (keys[i] < pivot) i++; 1342 while (pivot < keys[j]) j--; 1343 if (i <= j) { 1344 int temp1 = keys[i]; 1345 keys[i] = keys[j]; 1346 keys[j] = temp1; 1347 int temp2 = values[i]; 1348 values[i] = values[j]; 1349 values[j] = temp2; 1350 i++; 1351 j--; 1352 } 1353 } while (i <= j); 1354 if (lo < j) qsort2(keys, values, lo, j); 1355 if (i < hi) qsort2(keys, values, i, hi); 1356 } 1357 1358 public void visitSynchronized(JCSynchronized tree) { 1359 int limit = code.nextreg; 1360 // Generate code to evaluate lock and save in temporary variable. 1361 final LocalItem lockVar = makeTemp(syms.objectType); 1362 Assert.check(code.isStatementStart()); 1363 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1364 lockVar.store(); 1365 1366 // Generate code to enter monitor. 1367 code.emitop0(monitorenter); 1368 code.state.lock(lockVar.reg); 1369 1370 // Generate code for a try statement with given body, no catch clauses 1371 // in a new environment with the "exit-monitor" operation as finalizer. 1372 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1373 syncEnv.info.finalize = new GenFinalizer() { 1374 void gen() { 1375 genLast(); 1376 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1377 syncEnv.info.gaps.append(code.curCP()); 1378 } 1379 void genLast() { 1380 if (code.isAlive()) { 1381 lockVar.load(); 1382 code.emitop0(monitorexit); 1383 code.state.unlock(lockVar.reg); 1384 } 1385 } 1386 }; 1387 syncEnv.info.gaps = new ListBuffer<>(); 1388 genTry(tree.body, List.nil(), syncEnv); 1389 code.endScopes(limit); 1390 } 1391 1392 public void visitTry(final JCTry tree) { 1393 // Generate code for a try statement with given body and catch clauses, 1394 // in a new environment which calls the finally block if there is one. 1395 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1396 final Env<GenContext> oldEnv = env; 1397 tryEnv.info.finalize = new GenFinalizer() { 1398 void gen() { 1399 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1400 tryEnv.info.gaps.append(code.curCP()); 1401 genLast(); 1402 } 1403 void genLast() { 1404 if (tree.finalizer != null) 1405 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1406 } 1407 boolean hasFinalizer() { 1408 return tree.finalizer != null; 1409 } 1410 1411 @Override 1412 void afterBody() { 1413 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) { 1414 //for body-only finally, remove the GenFinalizer after try body 1415 //so that the finally is not generated to catch bodies: 1416 tryEnv.info.finalize = null; 1417 } 1418 } 1419 1420 }; 1421 tryEnv.info.gaps = new ListBuffer<>(); 1422 genTry(tree.body, tree.catchers, tryEnv); 1423 } 1424 //where 1425 /** Generate code for a try or synchronized statement 1426 * @param body The body of the try or synchronized statement. 1427 * @param catchers The lis of catch clauses. 1428 * @param env the environment current for the body. 1429 */ 1430 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1431 int limit = code.nextreg; 1432 int startpc = code.curCP(); 1433 Code.State stateTry = code.state.dup(); 1434 genStat(body, env, CRT_BLOCK); 1435 int endpc = code.curCP(); 1436 List<Integer> gaps = env.info.gaps.toList(); 1437 code.statBegin(TreeInfo.endPos(body)); 1438 genFinalizer(env); 1439 code.statBegin(TreeInfo.endPos(env.tree)); 1440 Chain exitChain = code.branch(goto_); 1441 endFinalizerGap(env); 1442 env.info.finalize.afterBody(); 1443 boolean hasFinalizer = 1444 env.info.finalize != null && 1445 env.info.finalize.hasFinalizer(); 1446 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) { 1447 // start off with exception on stack 1448 code.entryPoint(stateTry, l.head.param.sym.type); 1449 genCatch(l.head, env, startpc, endpc, gaps); 1450 genFinalizer(env); 1451 if (hasFinalizer || l.tail.nonEmpty()) { 1452 code.statBegin(TreeInfo.endPos(env.tree)); 1453 exitChain = Code.mergeChains(exitChain, 1454 code.branch(goto_)); 1455 } 1456 endFinalizerGap(env); 1457 } 1458 if (hasFinalizer) { 1459 // Create a new register segement to avoid allocating 1460 // the same variables in finalizers and other statements. 1461 code.newRegSegment(); 1462 1463 // Add a catch-all clause. 1464 1465 // start off with exception on stack 1466 int catchallpc = code.entryPoint(stateTry, syms.throwableType); 1467 1468 // Register all exception ranges for catch all clause. 1469 // The range of the catch all clause is from the beginning 1470 // of the try or synchronized block until the present 1471 // code pointer excluding all gaps in the current 1472 // environment's GenContext. 1473 int startseg = startpc; 1474 while (env.info.gaps.nonEmpty()) { 1475 int endseg = env.info.gaps.next().intValue(); 1476 registerCatch(body.pos(), startseg, endseg, 1477 catchallpc, 0); 1478 startseg = env.info.gaps.next().intValue(); 1479 } 1480 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1481 code.markStatBegin(); 1482 1483 Item excVar = makeTemp(syms.throwableType); 1484 excVar.store(); 1485 genFinalizer(env); 1486 code.resolvePending(); 1487 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS)); 1488 code.markStatBegin(); 1489 1490 excVar.load(); 1491 registerCatch(body.pos(), startseg, 1492 env.info.gaps.next().intValue(), 1493 catchallpc, 0); 1494 code.emitop0(athrow); 1495 code.markDead(); 1496 1497 // If there are jsr's to this finalizer, ... 1498 if (env.info.cont != null) { 1499 // Resolve all jsr's. 1500 code.resolve(env.info.cont); 1501 1502 // Mark statement line number 1503 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1504 code.markStatBegin(); 1505 1506 // Save return address. 1507 LocalItem retVar = makeTemp(syms.throwableType); 1508 retVar.store(); 1509 1510 // Generate finalizer code. 1511 env.info.finalize.genLast(); 1512 1513 // Return. 1514 code.emitop1w(ret, retVar.reg); 1515 code.markDead(); 1516 } 1517 } 1518 // Resolve all breaks. 1519 code.resolve(exitChain); 1520 1521 code.endScopes(limit); 1522 } 1523 1524 /** Generate code for a catch clause. 1525 * @param tree The catch clause. 1526 * @param env The environment current in the enclosing try. 1527 * @param startpc Start pc of try-block. 1528 * @param endpc End pc of try-block. 1529 */ 1530 void genCatch(JCCatch tree, 1531 Env<GenContext> env, 1532 int startpc, int endpc, 1533 List<Integer> gaps) { 1534 if (startpc != endpc) { 1535 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs 1536 = catchTypesWithAnnotations(tree); 1537 while (gaps.nonEmpty()) { 1538 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1539 JCExpression subCatch = subCatch1.snd; 1540 int catchType = makeRef(tree.pos(), subCatch.type); 1541 int end = gaps.head.intValue(); 1542 registerCatch(tree.pos(), 1543 startpc, end, code.curCP(), 1544 catchType); 1545 for (Attribute.TypeCompound tc : subCatch1.fst) { 1546 tc.position.setCatchInfo(catchType, startpc); 1547 } 1548 } 1549 gaps = gaps.tail; 1550 startpc = gaps.head.intValue(); 1551 gaps = gaps.tail; 1552 } 1553 if (startpc < endpc) { 1554 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1555 JCExpression subCatch = subCatch1.snd; 1556 int catchType = makeRef(tree.pos(), subCatch.type); 1557 registerCatch(tree.pos(), 1558 startpc, endpc, code.curCP(), 1559 catchType); 1560 for (Attribute.TypeCompound tc : subCatch1.fst) { 1561 tc.position.setCatchInfo(catchType, startpc); 1562 } 1563 } 1564 } 1565 VarSymbol exparam = tree.param.sym; 1566 code.statBegin(tree.pos); 1567 code.markStatBegin(); 1568 int limit = code.nextreg; 1569 code.newLocal(exparam); 1570 items.makeLocalItem(exparam).store(); 1571 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1572 genStat(tree.body, env, CRT_BLOCK); 1573 code.endScopes(limit); 1574 code.statBegin(TreeInfo.endPos(tree.body)); 1575 } 1576 } 1577 // where 1578 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) { 1579 return TreeInfo.isMultiCatch(tree) ? 1580 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) : 1581 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype)); 1582 } 1583 // where 1584 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) { 1585 List<JCExpression> alts = tree.alternatives; 1586 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head)); 1587 alts = alts.tail; 1588 1589 while(alts != null && alts.head != null) { 1590 JCExpression alt = alts.head; 1591 if (alt instanceof JCAnnotatedType) { 1592 JCAnnotatedType a = (JCAnnotatedType)alt; 1593 res = res.prepend(new Pair<>(annotate.fromAnnotations(a.annotations), alt)); 1594 } else { 1595 res = res.prepend(new Pair<>(List.nil(), alt)); 1596 } 1597 alts = alts.tail; 1598 } 1599 return res.reverse(); 1600 } 1601 1602 /** Register a catch clause in the "Exceptions" code-attribute. 1603 */ 1604 void registerCatch(DiagnosticPosition pos, 1605 int startpc, int endpc, 1606 int handler_pc, int catch_type) { 1607 char startpc1 = (char)startpc; 1608 char endpc1 = (char)endpc; 1609 char handler_pc1 = (char)handler_pc; 1610 if (startpc1 == startpc && 1611 endpc1 == endpc && 1612 handler_pc1 == handler_pc) { 1613 code.addCatch(startpc1, endpc1, handler_pc1, 1614 (char)catch_type); 1615 } else { 1616 log.error(pos, Errors.LimitCodeTooLargeForTryStmt); 1617 nerrs++; 1618 } 1619 } 1620 1621 public void visitIf(JCIf tree) { 1622 int limit = code.nextreg; 1623 Chain thenExit = null; 1624 Assert.check(code.isStatementStart()); 1625 CondItem c = genCond(TreeInfo.skipParens(tree.cond), 1626 CRT_FLOW_CONTROLLER); 1627 Chain elseChain = c.jumpFalse(); 1628 Assert.check(code.isStatementStart()); 1629 if (!c.isFalse()) { 1630 code.resolve(c.trueJumps); 1631 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); 1632 thenExit = code.branch(goto_); 1633 } 1634 if (elseChain != null) { 1635 code.resolve(elseChain); 1636 if (tree.elsepart != null) { 1637 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); 1638 } 1639 } 1640 code.resolve(thenExit); 1641 code.endScopes(limit); 1642 Assert.check(code.isStatementStart()); 1643 } 1644 1645 public void visitExec(JCExpressionStatement tree) { 1646 // Optimize x++ to ++x and x-- to --x. 1647 JCExpression e = tree.expr; 1648 switch (e.getTag()) { 1649 case POSTINC: 1650 ((JCUnary) e).setTag(PREINC); 1651 break; 1652 case POSTDEC: 1653 ((JCUnary) e).setTag(PREDEC); 1654 break; 1655 } 1656 Assert.check(code.isStatementStart()); 1657 genExpr(tree.expr, tree.expr.type).drop(); 1658 Assert.check(code.isStatementStart()); 1659 } 1660 1661 public void visitBreak(JCBreak tree) { 1662 int tmpPos = code.pendingStatPos; 1663 Assert.check(code.isStatementStart()); 1664 Env<GenContext> targetEnv = unwind(tree.target, env); 1665 code.pendingStatPos = tmpPos; 1666 if (tree.isValueBreak()) { 1667 if (inCondSwitchExpression) { 1668 CondItem value = genCond(tree.value, CRT_FLOW_TARGET); 1669 Chain falseJumps = value.jumpFalse(); 1670 code.resolve(value.trueJumps); 1671 Chain trueJumps = code.branch(goto_); 1672 if (switchExpressionTrueChain == null) { 1673 switchExpressionTrueChain = trueJumps; 1674 } else { 1675 switchExpressionTrueChain = 1676 Code.mergeChains(switchExpressionTrueChain, trueJumps); 1677 } 1678 if (switchExpressionFalseChain == null) { 1679 switchExpressionFalseChain = falseJumps; 1680 } else { 1681 switchExpressionFalseChain = 1682 Code.mergeChains(switchExpressionFalseChain, falseJumps); 1683 } 1684 } else { 1685 genExpr(tree.value, pt).load(); 1686 code.state.forceStackTop(tree.target.type); 1687 targetEnv.info.addExit(code.branch(goto_)); 1688 } 1689 } else { 1690 targetEnv.info.addExit(code.branch(goto_)); 1691 } 1692 endFinalizerGaps(env, targetEnv); 1693 } 1694 1695 public void visitContinue(JCContinue tree) { 1696 int tmpPos = code.pendingStatPos; 1697 Env<GenContext> targetEnv = unwind(tree.target, env); 1698 code.pendingStatPos = tmpPos; 1699 Assert.check(code.isStatementStart()); 1700 targetEnv.info.addCont(code.branch(goto_)); 1701 endFinalizerGaps(env, targetEnv); 1702 } 1703 1704 public void visitReturn(JCReturn tree) { 1705 int limit = code.nextreg; 1706 final Env<GenContext> targetEnv; 1707 1708 /* Save and then restore the location of the return in case a finally 1709 * is expanded (with unwind()) in the middle of our bytecodes. 1710 */ 1711 int tmpPos = code.pendingStatPos; 1712 if (tree.expr != null) { 1713 Assert.check(code.isStatementStart()); 1714 Item r = genExpr(tree.expr, pt).load(); 1715 if (hasFinally(env.enclMethod, env)) { 1716 r = makeTemp(pt); 1717 r.store(); 1718 } 1719 targetEnv = unwind(env.enclMethod, env); 1720 code.pendingStatPos = tmpPos; 1721 r.load(); 1722 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 1723 } else { 1724 targetEnv = unwind(env.enclMethod, env); 1725 code.pendingStatPos = tmpPos; 1726 code.emitop0(return_); 1727 } 1728 endFinalizerGaps(env, targetEnv); 1729 code.endScopes(limit); 1730 } 1731 1732 public void visitThrow(JCThrow tree) { 1733 Assert.check(code.isStatementStart()); 1734 genExpr(tree.expr, tree.expr.type).load(); 1735 code.emitop0(athrow); 1736 Assert.check(code.isStatementStart()); 1737 } 1738 1739 /* ************************************************************************ 1740 * Visitor methods for expressions 1741 *************************************************************************/ 1742 1743 public void visitApply(JCMethodInvocation tree) { 1744 setTypeAnnotationPositions(tree.pos); 1745 // Generate code for method. 1746 Item m = genExpr(tree.meth, methodType); 1747 // Generate code for all arguments, where the expected types are 1748 // the parameters of the method's external type (that is, any implicit 1749 // outer instance of a super(...) call appears as first parameter). 1750 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 1751 genArgs(tree.args, 1752 msym.externalType(types).getParameterTypes()); 1753 if (!msym.isDynamic()) { 1754 code.statBegin(tree.pos); 1755 } 1756 result = m.invoke(); 1757 } 1758 1759 public void visitConditional(JCConditional tree) { 1760 Chain thenExit = null; 1761 code.statBegin(tree.cond.pos); 1762 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 1763 Chain elseChain = c.jumpFalse(); 1764 if (!c.isFalse()) { 1765 code.resolve(c.trueJumps); 1766 int startpc = genCrt ? code.curCP() : 0; 1767 code.statBegin(tree.truepart.pos); 1768 genExpr(tree.truepart, pt).load(); 1769 code.state.forceStackTop(tree.type); 1770 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 1771 startpc, code.curCP()); 1772 thenExit = code.branch(goto_); 1773 } 1774 if (elseChain != null) { 1775 code.resolve(elseChain); 1776 int startpc = genCrt ? code.curCP() : 0; 1777 code.statBegin(tree.falsepart.pos); 1778 genExpr(tree.falsepart, pt).load(); 1779 code.state.forceStackTop(tree.type); 1780 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 1781 startpc, code.curCP()); 1782 } 1783 code.resolve(thenExit); 1784 result = items.makeStackItem(pt); 1785 } 1786 1787 private void setTypeAnnotationPositions(int treePos) { 1788 MethodSymbol meth = code.meth; 1789 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 1790 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 1791 1792 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 1793 if (ta.hasUnknownPosition()) 1794 ta.tryFixPosition(); 1795 1796 if (ta.position.matchesPos(treePos)) 1797 ta.position.updatePosOffset(code.cp); 1798 } 1799 1800 if (!initOrClinit) 1801 return; 1802 1803 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 1804 if (ta.hasUnknownPosition()) 1805 ta.tryFixPosition(); 1806 1807 if (ta.position.matchesPos(treePos)) 1808 ta.position.updatePosOffset(code.cp); 1809 } 1810 1811 ClassSymbol clazz = meth.enclClass(); 1812 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 1813 if (!s.getKind().isField()) 1814 continue; 1815 1816 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 1817 if (ta.hasUnknownPosition()) 1818 ta.tryFixPosition(); 1819 1820 if (ta.position.matchesPos(treePos)) 1821 ta.position.updatePosOffset(code.cp); 1822 } 1823 } 1824 } 1825 1826 public void visitNewClass(JCNewClass tree) { 1827 // Enclosing instances or anonymous classes should have been eliminated 1828 // by now. 1829 Assert.check(tree.encl == null && tree.def == null); 1830 setTypeAnnotationPositions(tree.pos); 1831 1832 code.emitop2(new_, makeRef(tree.pos(), tree.type)); 1833 code.emitop0(dup); 1834 1835 // Generate code for all arguments, where the expected types are 1836 // the parameters of the constructor's external type (that is, 1837 // any implicit outer instance appears as first parameter). 1838 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 1839 1840 items.makeMemberItem(tree.constructor, true).invoke(); 1841 result = items.makeStackItem(tree.type); 1842 } 1843 1844 public void visitNewArray(JCNewArray tree) { 1845 setTypeAnnotationPositions(tree.pos); 1846 1847 if (tree.elems != null) { 1848 Type elemtype = types.elemtype(tree.type); 1849 loadIntConst(tree.elems.length()); 1850 Item arr = makeNewArray(tree.pos(), tree.type, 1); 1851 int i = 0; 1852 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 1853 arr.duplicate(); 1854 loadIntConst(i); 1855 i++; 1856 genExpr(l.head, elemtype).load(); 1857 items.makeIndexedItem(elemtype).store(); 1858 } 1859 result = arr; 1860 } else { 1861 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 1862 genExpr(l.head, syms.intType).load(); 1863 } 1864 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 1865 } 1866 } 1867 //where 1868 /** Generate code to create an array with given element type and number 1869 * of dimensions. 1870 */ 1871 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 1872 Type elemtype = types.elemtype(type); 1873 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 1874 log.error(pos, Errors.LimitDimensions); 1875 nerrs++; 1876 } 1877 int elemcode = Code.arraycode(elemtype); 1878 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { 1879 code.emitAnewarray(makeRef(pos, elemtype), type); 1880 } else if (elemcode == 1) { 1881 code.emitMultianewarray(ndims, makeRef(pos, type), type); 1882 } else { 1883 code.emitNewarray(elemcode, type); 1884 } 1885 return items.makeStackItem(type); 1886 } 1887 1888 public void visitParens(JCParens tree) { 1889 result = genExpr(tree.expr, tree.expr.type); 1890 } 1891 1892 public void visitAssign(JCAssign tree) { 1893 Item l = genExpr(tree.lhs, tree.lhs.type); 1894 genExpr(tree.rhs, tree.lhs.type).load(); 1895 if (tree.rhs.type.hasTag(BOT)) { 1896 /* This is just a case of widening reference conversion that per 5.1.5 simply calls 1897 for "regarding a reference as having some other type in a manner that can be proved 1898 correct at compile time." 1899 */ 1900 code.state.forceStackTop(tree.lhs.type); 1901 } 1902 result = items.makeAssignItem(l); 1903 } 1904 1905 public void visitAssignop(JCAssignOp tree) { 1906 OperatorSymbol operator = tree.operator; 1907 Item l; 1908 if (operator.opcode == string_add) { 1909 l = concat.makeConcat(tree); 1910 } else { 1911 // Generate code for first expression 1912 l = genExpr(tree.lhs, tree.lhs.type); 1913 1914 // If we have an increment of -32768 to +32767 of a local 1915 // int variable we can use an incr instruction instead of 1916 // proceeding further. 1917 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 1918 l instanceof LocalItem && 1919 tree.lhs.type.getTag().isSubRangeOf(INT) && 1920 tree.rhs.type.getTag().isSubRangeOf(INT) && 1921 tree.rhs.type.constValue() != null) { 1922 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 1923 if (tree.hasTag(MINUS_ASG)) ival = -ival; 1924 ((LocalItem)l).incr(ival); 1925 result = l; 1926 return; 1927 } 1928 // Otherwise, duplicate expression, load one copy 1929 // and complete binary operation. 1930 l.duplicate(); 1931 l.coerce(operator.type.getParameterTypes().head).load(); 1932 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 1933 } 1934 result = items.makeAssignItem(l); 1935 } 1936 1937 public void visitUnary(JCUnary tree) { 1938 OperatorSymbol operator = tree.operator; 1939 if (tree.hasTag(NOT)) { 1940 CondItem od = genCond(tree.arg, false); 1941 result = od.negate(); 1942 } else { 1943 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 1944 switch (tree.getTag()) { 1945 case POS: 1946 result = od.load(); 1947 break; 1948 case NEG: 1949 result = od.load(); 1950 code.emitop0(operator.opcode); 1951 break; 1952 case COMPL: 1953 result = od.load(); 1954 emitMinusOne(od.typecode); 1955 code.emitop0(operator.opcode); 1956 break; 1957 case PREINC: case PREDEC: 1958 od.duplicate(); 1959 if (od instanceof LocalItem && 1960 (operator.opcode == iadd || operator.opcode == isub)) { 1961 ((LocalItem)od).incr(tree.hasTag(PREINC) ? 1 : -1); 1962 result = od; 1963 } else { 1964 od.load(); 1965 code.emitop0(one(od.typecode)); 1966 code.emitop0(operator.opcode); 1967 // Perform narrowing primitive conversion if byte, 1968 // char, or short. Fix for 4304655. 1969 if (od.typecode != INTcode && 1970 Code.truncate(od.typecode) == INTcode) 1971 code.emitop0(int2byte + od.typecode - BYTEcode); 1972 result = items.makeAssignItem(od); 1973 } 1974 break; 1975 case POSTINC: case POSTDEC: 1976 od.duplicate(); 1977 if (od instanceof LocalItem && 1978 (operator.opcode == iadd || operator.opcode == isub)) { 1979 Item res = od.load(); 1980 ((LocalItem)od).incr(tree.hasTag(POSTINC) ? 1 : -1); 1981 result = res; 1982 } else { 1983 Item res = od.load(); 1984 od.stash(od.typecode); 1985 code.emitop0(one(od.typecode)); 1986 code.emitop0(operator.opcode); 1987 // Perform narrowing primitive conversion if byte, 1988 // char, or short. Fix for 4304655. 1989 if (od.typecode != INTcode && 1990 Code.truncate(od.typecode) == INTcode) 1991 code.emitop0(int2byte + od.typecode - BYTEcode); 1992 od.store(); 1993 result = res; 1994 } 1995 break; 1996 case NULLCHK: 1997 result = od.load(); 1998 code.emitop0(dup); 1999 genNullCheck(tree); 2000 break; 2001 default: 2002 Assert.error(); 2003 } 2004 } 2005 } 2006 2007 /** Generate a null check from the object value at stack top. */ 2008 private void genNullCheck(JCTree tree) { 2009 code.statBegin(tree.pos); 2010 callMethod(tree.pos(), syms.objectsType, names.requireNonNull, 2011 List.of(syms.objectType), true); 2012 code.emitop0(pop); 2013 } 2014 2015 public void visitBinary(JCBinary tree) { 2016 OperatorSymbol operator = tree.operator; 2017 if (operator.opcode == string_add) { 2018 result = concat.makeConcat(tree); 2019 } else if (tree.hasTag(AND)) { 2020 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2021 if (!lcond.isFalse()) { 2022 Chain falseJumps = lcond.jumpFalse(); 2023 code.resolve(lcond.trueJumps); 2024 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2025 result = items. 2026 makeCondItem(rcond.opcode, 2027 rcond.trueJumps, 2028 Code.mergeChains(falseJumps, 2029 rcond.falseJumps)); 2030 } else { 2031 result = lcond; 2032 } 2033 } else if (tree.hasTag(OR)) { 2034 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2035 if (!lcond.isTrue()) { 2036 Chain trueJumps = lcond.jumpTrue(); 2037 code.resolve(lcond.falseJumps); 2038 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2039 result = items. 2040 makeCondItem(rcond.opcode, 2041 Code.mergeChains(trueJumps, rcond.trueJumps), 2042 rcond.falseJumps); 2043 } else { 2044 result = lcond; 2045 } 2046 } else { 2047 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2048 od.load(); 2049 result = completeBinop(tree.lhs, tree.rhs, operator); 2050 } 2051 } 2052 2053 2054 /** Complete generating code for operation, with left operand 2055 * already on stack. 2056 * @param lhs The tree representing the left operand. 2057 * @param rhs The tree representing the right operand. 2058 * @param operator The operator symbol. 2059 */ 2060 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2061 MethodType optype = (MethodType)operator.type; 2062 int opcode = operator.opcode; 2063 if (opcode >= if_icmpeq && opcode <= if_icmple && 2064 rhs.type.constValue() instanceof Number && 2065 ((Number) rhs.type.constValue()).intValue() == 0) { 2066 opcode = opcode + (ifeq - if_icmpeq); 2067 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2068 TreeInfo.isNull(rhs)) { 2069 opcode = opcode + (if_acmp_null - if_acmpeq); 2070 } else { 2071 // The expected type of the right operand is 2072 // the second parameter type of the operator, except for 2073 // shifts with long shiftcount, where we convert the opcode 2074 // to a short shift and the expected type to int. 2075 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2076 if (opcode >= ishll && opcode <= lushrl) { 2077 opcode = opcode + (ishl - ishll); 2078 rtype = syms.intType; 2079 } 2080 // Generate code for right operand and load. 2081 genExpr(rhs, rtype).load(); 2082 // If there are two consecutive opcode instructions, 2083 // emit the first now. 2084 if (opcode >= (1 << preShift)) { 2085 code.emitop0(opcode >> preShift); 2086 opcode = opcode & 0xFF; 2087 } 2088 } 2089 if (opcode >= ifeq && opcode <= if_acmpne || 2090 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2091 return items.makeCondItem(opcode); 2092 } else { 2093 code.emitop0(opcode); 2094 return items.makeStackItem(optype.restype); 2095 } 2096 } 2097 2098 public void visitTypeCast(JCTypeCast tree) { 2099 result = genExpr(tree.expr, tree.clazz.type).load(); 2100 setTypeAnnotationPositions(tree.pos); 2101 // Additional code is only needed if we cast to a reference type 2102 // which is not statically a supertype of the expression's type. 2103 // For basic types, the coerce(...) in genExpr(...) will do 2104 // the conversion. 2105 if (!tree.clazz.type.isPrimitive() && 2106 !types.isSameType(tree.expr.type, tree.clazz.type) && 2107 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { 2108 code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type)); 2109 } 2110 } 2111 2112 public void visitWildcard(JCWildcard tree) { 2113 throw new AssertionError(this.getClass().getName()); 2114 } 2115 2116 public void visitTypeTest(JCInstanceOf tree) { 2117 genExpr(tree.expr, tree.expr.type).load(); 2118 setTypeAnnotationPositions(tree.pos); 2119 code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type)); 2120 result = items.makeStackItem(syms.booleanType); 2121 } 2122 2123 public void visitIndexed(JCArrayAccess tree) { 2124 genExpr(tree.indexed, tree.indexed.type).load(); 2125 genExpr(tree.index, syms.intType).load(); 2126 result = items.makeIndexedItem(tree.type); 2127 } 2128 2129 public void visitIdent(JCIdent tree) { 2130 Symbol sym = tree.sym; 2131 if (tree.name == names._this || tree.name == names._super) { 2132 Item res = tree.name == names._this 2133 ? items.makeThisItem() 2134 : items.makeSuperItem(); 2135 if (sym.kind == MTH) { 2136 // Generate code to address the constructor. 2137 res.load(); 2138 res = items.makeMemberItem(sym, true); 2139 } 2140 result = res; 2141 } else if (sym.kind == VAR && sym.owner.kind == MTH) { 2142 result = items.makeLocalItem((VarSymbol)sym); 2143 } else if (isInvokeDynamic(sym)) { 2144 result = items.makeDynamicItem(sym); 2145 } else if ((sym.flags() & STATIC) != 0) { 2146 if (!isAccessSuper(env.enclMethod)) 2147 sym = binaryQualifier(sym, env.enclClass.type); 2148 result = items.makeStaticItem(sym); 2149 } else { 2150 items.makeThisItem().load(); 2151 sym = binaryQualifier(sym, env.enclClass.type); 2152 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym)); 2153 } 2154 } 2155 2156 //where 2157 private boolean nonVirtualForPrivateAccess(Symbol sym) { 2158 boolean useVirtual = target.hasVirtualPrivateInvoke() && 2159 !disableVirtualizedPrivateInvoke; 2160 return !useVirtual && ((sym.flags() & PRIVATE) != 0); 2161 } 2162 2163 public void visitSelect(JCFieldAccess tree) { 2164 Symbol sym = tree.sym; 2165 2166 if (tree.name == names._class) { 2167 code.emitLdc(makeRef(tree.pos(), tree.selected.type)); 2168 result = items.makeStackItem(pt); 2169 return; 2170 } 2171 2172 Symbol ssym = TreeInfo.symbol(tree.selected); 2173 2174 // Are we selecting via super? 2175 boolean selectSuper = 2176 ssym != null && (ssym.kind == TYP || ssym.name == names._super); 2177 2178 // Are we accessing a member of the superclass in an access method 2179 // resulting from a qualified super? 2180 boolean accessSuper = isAccessSuper(env.enclMethod); 2181 2182 Item base = (selectSuper) 2183 ? items.makeSuperItem() 2184 : genExpr(tree.selected, tree.selected.type); 2185 2186 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { 2187 // We are seeing a variable that is constant but its selecting 2188 // expression is not. 2189 if ((sym.flags() & STATIC) != 0) { 2190 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2191 base = base.load(); 2192 base.drop(); 2193 } else { 2194 base.load(); 2195 genNullCheck(tree.selected); 2196 } 2197 result = items. 2198 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2199 } else { 2200 if (isInvokeDynamic(sym)) { 2201 result = items.makeDynamicItem(sym); 2202 return; 2203 } else { 2204 sym = binaryQualifier(sym, tree.selected.type); 2205 } 2206 if ((sym.flags() & STATIC) != 0) { 2207 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2208 base = base.load(); 2209 base.drop(); 2210 result = items.makeStaticItem(sym); 2211 } else { 2212 base.load(); 2213 if (sym == syms.lengthVar) { 2214 code.emitop0(arraylength); 2215 result = items.makeStackItem(syms.intType); 2216 } else { 2217 result = items. 2218 makeMemberItem(sym, 2219 nonVirtualForPrivateAccess(sym) || 2220 selectSuper || accessSuper); 2221 } 2222 } 2223 } 2224 } 2225 2226 public boolean isInvokeDynamic(Symbol sym) { 2227 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2228 } 2229 2230 public void visitLiteral(JCLiteral tree) { 2231 if (tree.type.hasTag(BOT)) { 2232 code.emitop0(aconst_null); 2233 result = items.makeStackItem(tree.type); 2234 } 2235 else 2236 result = items.makeImmediateItem(tree.type, tree.value); 2237 } 2238 2239 public void visitLetExpr(LetExpr tree) { 2240 int limit = code.nextreg; 2241 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 2242 try { 2243 genStats(tree.defs, env); 2244 } finally { 2245 code.setLetExprStackPos(prevLetExprStart); 2246 } 2247 result = genExpr(tree.expr, tree.expr.type).load(); 2248 code.endScopes(limit); 2249 } 2250 2251 private void generateReferencesToPrunedTree(ClassSymbol classSymbol, Pool pool) { 2252 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2253 if (prunedInfo != null) { 2254 for (JCTree prunedTree: prunedInfo) { 2255 prunedTree.accept(classReferenceVisitor); 2256 } 2257 } 2258 } 2259 2260 /* ************************************************************************ 2261 * main method 2262 *************************************************************************/ 2263 2264 /** Generate code for a class definition. 2265 * @param env The attribution environment that belongs to the 2266 * outermost class containing this class definition. 2267 * We need this for resolving some additional symbols. 2268 * @param cdef The tree representing the class definition. 2269 * @return True if code is generated with no errors. 2270 */ 2271 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2272 try { 2273 attrEnv = env; 2274 ClassSymbol c = cdef.sym; 2275 this.toplevel = env.toplevel; 2276 this.endPosTable = toplevel.endPositions; 2277 c.pool = pool; 2278 pool.reset(); 2279 /* method normalizeDefs() can add references to external classes into the constant pool 2280 */ 2281 cdef.defs = normalizeDefs(cdef.defs, c); 2282 generateReferencesToPrunedTree(c, pool); 2283 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2284 localEnv.toplevel = env.toplevel; 2285 localEnv.enclClass = cdef; 2286 2287 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2288 genDef(l.head, localEnv); 2289 } 2290 if (pool.numEntries() > Pool.MAX_ENTRIES) { 2291 log.error(cdef.pos(), Errors.LimitPool); 2292 nerrs++; 2293 } 2294 if (nerrs != 0) { 2295 // if errors, discard code 2296 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2297 if (l.head.hasTag(METHODDEF)) 2298 ((JCMethodDecl) l.head).sym.code = null; 2299 } 2300 } 2301 cdef.defs = List.nil(); // discard trees 2302 return nerrs == 0; 2303 } finally { 2304 // note: this method does NOT support recursion. 2305 attrEnv = null; 2306 this.env = null; 2307 toplevel = null; 2308 endPosTable = null; 2309 nerrs = 0; 2310 } 2311 } 2312 2313 /* ************************************************************************ 2314 * Auxiliary classes 2315 *************************************************************************/ 2316 2317 /** An abstract class for finalizer generation. 2318 */ 2319 abstract class GenFinalizer { 2320 /** Generate code to clean up when unwinding. */ 2321 abstract void gen(); 2322 2323 /** Generate code to clean up at last. */ 2324 abstract void genLast(); 2325 2326 /** Does this finalizer have some nontrivial cleanup to perform? */ 2327 boolean hasFinalizer() { return true; } 2328 2329 /** Should be invoked after the try's body has been visited. */ 2330 void afterBody() {} 2331 } 2332 2333 /** code generation contexts, 2334 * to be used as type parameter for environments. 2335 */ 2336 static class GenContext { 2337 2338 /** A chain for all unresolved jumps that exit the current environment. 2339 */ 2340 Chain exit = null; 2341 2342 /** A chain for all unresolved jumps that continue in the 2343 * current environment. 2344 */ 2345 Chain cont = null; 2346 2347 /** A closure that generates the finalizer of the current environment. 2348 * Only set for Synchronized and Try contexts. 2349 */ 2350 GenFinalizer finalize = null; 2351 2352 /** Is this a switch statement? If so, allocate registers 2353 * even when the variable declaration is unreachable. 2354 */ 2355 boolean isSwitch = false; 2356 2357 /** A list buffer containing all gaps in the finalizer range, 2358 * where a catch all exception should not apply. 2359 */ 2360 ListBuffer<Integer> gaps = null; 2361 2362 /** Add given chain to exit chain. 2363 */ 2364 void addExit(Chain c) { 2365 exit = Code.mergeChains(c, exit); 2366 } 2367 2368 /** Add given chain to cont chain. 2369 */ 2370 void addCont(Chain c) { 2371 cont = Code.mergeChains(c, cont); 2372 } 2373 } 2374 2375 }