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