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