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 String 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 = "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 qualifiedSymbolCache = new HashMap<>(); 140 } 141 142 /** Switches 143 */ 144 private final boolean lineDebugInfo; 145 private final boolean varDebugInfo; 146 private final boolean genCrt; 147 private final boolean debugCode; 148 private boolean disableVirtualizedPrivateInvoke; 149 150 /** Code buffer, set by genMethod. 151 */ 152 private Code code; 153 154 /** Items structure, set by genMethod. 155 */ 156 private Items items; 157 158 /** Environment for symbol lookup, set by genClass 159 */ 160 private Env<AttrContext> attrEnv; 161 162 /** The top level tree. 163 */ 164 private JCCompilationUnit toplevel; 165 166 /** The number of code-gen errors in this class. 167 */ 168 private int nerrs = 0; 169 170 /** An object containing mappings of syntax trees to their 171 * ending source positions. 172 */ 173 EndPosTable endPosTable; 174 175 boolean inCondSwitchExpression; 176 Chain switchExpressionTrueChain; 177 Chain switchExpressionFalseChain; 178 List<LocalItem> stackBeforeSwitchExpression; 179 LocalItem switchResult; 180 Set<JCMethodInvocation> invocationsWithPatternMatchingCatch = Set.of(); 181 ListBuffer<int[]> patternMatchingInvocationRanges; 182 183 boolean allowPrimitiveClasses; 184 185 /** Cache the symbol to reflect the qualifying type. 186 * key: corresponding type 187 * value: qualified symbol 188 */ 189 Map<Type, Symbol> qualifiedSymbolCache; 190 191 /** Generate code to load an integer constant. 192 * @param n The integer to be loaded. 193 */ 194 void loadIntConst(int n) { 195 items.makeImmediateItem(syms.intType, n).load(); 196 } 197 198 /** The opcode that loads a zero constant of a given type code. 199 * @param tc The given type code (@see ByteCode). 200 */ 201 public static int zero(int tc) { 202 switch(tc) { 203 case INTcode: case BYTEcode: case SHORTcode: case CHARcode: 204 return iconst_0; 205 case LONGcode: 206 return lconst_0; 207 case FLOATcode: 208 return fconst_0; 209 case DOUBLEcode: 210 return dconst_0; 211 default: 212 throw new AssertionError("zero"); 213 } 214 } 215 216 /** The opcode that loads a one constant of a given type code. 217 * @param tc The given type code (@see ByteCode). 218 */ 219 public static int one(int tc) { 220 return zero(tc) + 1; 221 } 222 223 /** Generate code to load -1 of the given type code (either int or long). 224 * @param tc The given type code (@see ByteCode). 225 */ 226 void emitMinusOne(int tc) { 227 if (tc == LONGcode) { 228 items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load(); 229 } else { 230 code.emitop0(iconst_m1); 231 } 232 } 233 234 /** Construct a symbol to reflect the qualifying type that should 235 * appear in the byte code as per JLS 13.1. 236 * 237 * For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except 238 * for those cases where we need to work around VM bugs). 239 * 240 * For {@literal target <= 1.1}: If qualified variable or method is defined in a 241 * non-accessible class, clone it with the qualifier class as owner. 242 * 243 * @param sym The accessed symbol 244 * @param site The qualifier's type. 245 */ 246 Symbol binaryQualifier(Symbol sym, Type site) { 247 248 if (site.hasTag(ARRAY)) { 249 if (sym == syms.lengthVar || 250 sym.owner != syms.arrayClass) 251 return sym; 252 // array clone can be qualified by the array type in later targets 253 Symbol qualifier; 254 if ((qualifier = qualifiedSymbolCache.get(site)) == null) { 255 qualifier = new ClassSymbol(Flags.PUBLIC, site.tsym.name, site, syms.noSymbol); 256 qualifiedSymbolCache.put(site, qualifier); 257 } 258 return sym.clone(qualifier); 259 } 260 261 if (sym.owner == site.tsym || 262 (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) { 263 return sym; 264 } 265 266 // leave alone methods inherited from Object 267 // JLS 13.1. 268 if (sym.owner == syms.objectType.tsym) 269 return sym; 270 271 return sym.clone(site.tsym); 272 } 273 274 /** Insert a reference to given type in the constant pool, 275 * checking for an array with too many dimensions; 276 * return the reference's index. 277 * @param type The type for which a reference is inserted. 278 */ 279 int makeRef(DiagnosticPosition pos, Type type, boolean emitQtype) { 280 checkDimension(pos, type); 281 if (emitQtype) { 282 return poolWriter.putClass(new ConstantPoolQType(type, types)); 283 } else { 284 return poolWriter.putClass(type); 285 } 286 } 287 288 /** Insert a reference to given type in the constant pool, 289 * checking for an array with too many dimensions; 290 * return the reference's index. 291 * @param type The type for which a reference is inserted. 292 */ 293 int makeRef(DiagnosticPosition pos, Type type) { 294 return makeRef(pos, type, false); 295 } 296 297 /** Check if the given type is an array with too many dimensions. 298 */ 299 private Type checkDimension(DiagnosticPosition pos, Type t) { 300 checkDimensionInternal(pos, t); 301 return t; 302 } 303 304 private void checkDimensionInternal(DiagnosticPosition pos, Type t) { 305 switch (t.getTag()) { 306 case METHOD: 307 checkDimension(pos, t.getReturnType()); 308 for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail) 309 checkDimension(pos, args.head); 310 break; 311 case ARRAY: 312 if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) { 313 log.error(pos, Errors.LimitDimensions); 314 nerrs++; 315 } 316 break; 317 default: 318 break; 319 } 320 } 321 322 /** Create a temporary variable. 323 * @param type The variable's type. 324 */ 325 LocalItem makeTemp(Type type) { 326 VarSymbol v = new VarSymbol(Flags.SYNTHETIC, 327 names.empty, 328 type, 329 env.enclMethod.sym); 330 code.newLocal(v); 331 return items.makeLocalItem(v); 332 } 333 334 /** Generate code to call a non-private method or constructor. 335 * @param pos Position to be used for error reporting. 336 * @param site The type of which the method is a member. 337 * @param name The method's name. 338 * @param argtypes The method's argument types. 339 * @param isStatic A flag that indicates whether we call a 340 * static or instance method. 341 */ 342 void callMethod(DiagnosticPosition pos, 343 Type site, Name name, List<Type> argtypes, 344 boolean isStatic) { 345 Symbol msym = rs. 346 resolveInternalMethod(pos, attrEnv, site, name, argtypes, null); 347 if (isStatic) items.makeStaticItem(msym).invoke(); 348 else items.makeMemberItem(msym, names.isInitOrVNew(name)).invoke(); 349 } 350 351 /** Is the given method definition an access method 352 * resulting from a qualified super? This is signified by an odd 353 * access code. 354 */ 355 private boolean isAccessSuper(JCMethodDecl enclMethod) { 356 return 357 (enclMethod.mods.flags & SYNTHETIC) != 0 && 358 isOddAccessName(enclMethod.name); 359 } 360 361 /** Does given name start with "access$" and end in an odd digit? 362 */ 363 private boolean isOddAccessName(Name name) { 364 final String string = name.toString(); 365 return 366 string.startsWith(accessDollar) && 367 (string.charAt(string.length() - 1) & 1) != 0; 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 class HasTryScanner extends TreeScanner { 1342 private boolean hasTry; 1343 1344 @Override 1345 public void visitTry(JCTry tree) { 1346 hasTry = true; 1347 } 1348 1349 @Override 1350 public void visitSynchronized(JCSynchronized tree) { 1351 hasTry = true; 1352 } 1353 1354 @Override 1355 public void visitClassDef(JCClassDecl tree) { 1356 } 1357 1358 @Override 1359 public void visitLambda(JCLambda tree) { 1360 } 1361 }; 1362 1363 HasTryScanner hasTryScanner = new HasTryScanner(); 1364 1365 hasTryScanner.scan(tree); 1366 return hasTryScanner.hasTry; 1367 } 1368 1369 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases, 1370 boolean patternSwitch) { 1371 int limit = code.nextreg; 1372 Assert.check(!selector.type.hasTag(CLASS)); 1373 int switchStart = patternSwitch ? code.entryPoint() : -1; 1374 int startpcCrt = genCrt ? code.curCP() : 0; 1375 Assert.check(code.isStatementStart()); 1376 Item sel = genExpr(selector, syms.intType); 1377 if (cases.isEmpty()) { 1378 // We are seeing: switch <sel> {} 1379 sel.load().drop(); 1380 if (genCrt) 1381 code.crt.put(TreeInfo.skipParens(selector), 1382 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1383 } else { 1384 // We are seeing a nonempty switch. 1385 sel.load(); 1386 if (genCrt) 1387 code.crt.put(TreeInfo.skipParens(selector), 1388 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1389 Env<GenContext> switchEnv = env.dup(swtch, new GenContext()); 1390 switchEnv.info.isSwitch = true; 1391 1392 // Compute number of labels and minimum and maximum label values. 1393 // For each case, store its label in an array. 1394 int lo = Integer.MAX_VALUE; // minimum label. 1395 int hi = Integer.MIN_VALUE; // maximum label. 1396 int nlabels = 0; // number of labels. 1397 1398 int[] labels = new int[cases.length()]; // the label array. 1399 int defaultIndex = -1; // the index of the default clause. 1400 1401 List<JCCase> l = cases; 1402 for (int i = 0; i < labels.length; i++) { 1403 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) { 1404 Assert.check(l.head.labels.size() == 1); 1405 int val = ((Number) constLabel.expr.type.constValue()).intValue(); 1406 labels[i] = val; 1407 if (val < lo) lo = val; 1408 if (hi < val) hi = val; 1409 nlabels++; 1410 } else { 1411 Assert.check(defaultIndex == -1); 1412 defaultIndex = i; 1413 } 1414 l = l.tail; 1415 } 1416 1417 // Determine whether to issue a tableswitch or a lookupswitch 1418 // instruction. 1419 long table_space_cost = 4 + ((long) hi - lo + 1); // words 1420 long table_time_cost = 3; // comparisons 1421 long lookup_space_cost = 3 + 2 * (long) nlabels; 1422 long lookup_time_cost = nlabels; 1423 int opcode = 1424 nlabels > 0 && 1425 table_space_cost + 3 * table_time_cost <= 1426 lookup_space_cost + 3 * lookup_time_cost 1427 ? 1428 tableswitch : lookupswitch; 1429 1430 int startpc = code.curCP(); // the position of the selector operation 1431 code.emitop0(opcode); 1432 code.align(4); 1433 int tableBase = code.curCP(); // the start of the jump table 1434 int[] offsets = null; // a table of offsets for a lookupswitch 1435 code.emit4(-1); // leave space for default offset 1436 if (opcode == tableswitch) { 1437 code.emit4(lo); // minimum label 1438 code.emit4(hi); // maximum label 1439 for (long i = lo; i <= hi; i++) { // leave space for jump table 1440 code.emit4(-1); 1441 } 1442 } else { 1443 code.emit4(nlabels); // number of labels 1444 for (int i = 0; i < nlabels; i++) { 1445 code.emit4(-1); code.emit4(-1); // leave space for lookup table 1446 } 1447 offsets = new int[labels.length]; 1448 } 1449 Code.State stateSwitch = code.state.dup(); 1450 code.markDead(); 1451 1452 // For each case do: 1453 l = cases; 1454 for (int i = 0; i < labels.length; i++) { 1455 JCCase c = l.head; 1456 l = l.tail; 1457 1458 int pc = code.entryPoint(stateSwitch); 1459 // Insert offset directly into code or else into the 1460 // offsets table. 1461 if (i != defaultIndex) { 1462 if (opcode == tableswitch) { 1463 code.put4( 1464 tableBase + 4 * (labels[i] - lo + 3), 1465 pc - startpc); 1466 } else { 1467 offsets[i] = pc - startpc; 1468 } 1469 } else { 1470 code.put4(tableBase, pc - startpc); 1471 } 1472 1473 // Generate code for the statements in this case. 1474 genStats(c.stats, switchEnv, CRT_FLOW_TARGET); 1475 } 1476 1477 if (switchEnv.info.cont != null) { 1478 Assert.check(patternSwitch); 1479 code.resolve(switchEnv.info.cont, switchStart); 1480 } 1481 1482 // Resolve all breaks. 1483 Chain exit = switchEnv.info.exit; 1484 if (exit != null) { 1485 code.resolve(exit); 1486 exit.state.defined.excludeFrom(limit); 1487 } 1488 1489 // If we have not set the default offset, we do so now. 1490 if (code.get4(tableBase) == -1) { 1491 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1492 } 1493 1494 if (opcode == tableswitch) { 1495 // Let any unfilled slots point to the default case. 1496 int defaultOffset = code.get4(tableBase); 1497 for (long i = lo; i <= hi; i++) { 1498 int t = (int)(tableBase + 4 * (i - lo + 3)); 1499 if (code.get4(t) == -1) 1500 code.put4(t, defaultOffset); 1501 } 1502 } else { 1503 // Sort non-default offsets and copy into lookup table. 1504 if (defaultIndex >= 0) 1505 for (int i = defaultIndex; i < labels.length - 1; i++) { 1506 labels[i] = labels[i+1]; 1507 offsets[i] = offsets[i+1]; 1508 } 1509 if (nlabels > 0) 1510 qsort2(labels, offsets, 0, nlabels - 1); 1511 for (int i = 0; i < nlabels; i++) { 1512 int caseidx = tableBase + 8 * (i + 1); 1513 code.put4(caseidx, labels[i]); 1514 code.put4(caseidx + 4, offsets[i]); 1515 } 1516 } 1517 } 1518 code.endScopes(limit); 1519 } 1520 //where 1521 /** Sort (int) arrays of keys and values 1522 */ 1523 static void qsort2(int[] keys, int[] values, int lo, int hi) { 1524 int i = lo; 1525 int j = hi; 1526 int pivot = keys[(i+j)/2]; 1527 do { 1528 while (keys[i] < pivot) i++; 1529 while (pivot < keys[j]) j--; 1530 if (i <= j) { 1531 int temp1 = keys[i]; 1532 keys[i] = keys[j]; 1533 keys[j] = temp1; 1534 int temp2 = values[i]; 1535 values[i] = values[j]; 1536 values[j] = temp2; 1537 i++; 1538 j--; 1539 } 1540 } while (i <= j); 1541 if (lo < j) qsort2(keys, values, lo, j); 1542 if (i < hi) qsort2(keys, values, i, hi); 1543 } 1544 1545 public void visitSynchronized(JCSynchronized tree) { 1546 int limit = code.nextreg; 1547 // Generate code to evaluate lock and save in temporary variable. 1548 final LocalItem lockVar = makeTemp(syms.objectType); 1549 Assert.check(code.isStatementStart()); 1550 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1551 lockVar.store(); 1552 1553 // Generate code to enter monitor. 1554 code.emitop0(monitorenter); 1555 code.state.lock(lockVar.reg); 1556 1557 // Generate code for a try statement with given body, no catch clauses 1558 // in a new environment with the "exit-monitor" operation as finalizer. 1559 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1560 syncEnv.info.finalize = new GenFinalizer() { 1561 void gen() { 1562 genLast(); 1563 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1564 syncEnv.info.gaps.append(code.curCP()); 1565 } 1566 void genLast() { 1567 if (code.isAlive()) { 1568 lockVar.load(); 1569 code.emitop0(monitorexit); 1570 code.state.unlock(lockVar.reg); 1571 } 1572 } 1573 }; 1574 syncEnv.info.gaps = new ListBuffer<>(); 1575 genTry(tree.body, List.nil(), syncEnv); 1576 code.endScopes(limit); 1577 } 1578 1579 public void visitTry(final JCTry tree) { 1580 // Generate code for a try statement with given body and catch clauses, 1581 // in a new environment which calls the finally block if there is one. 1582 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1583 final Env<GenContext> oldEnv = env; 1584 tryEnv.info.finalize = new GenFinalizer() { 1585 void gen() { 1586 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1587 tryEnv.info.gaps.append(code.curCP()); 1588 genLast(); 1589 } 1590 void genLast() { 1591 if (tree.finalizer != null) 1592 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1593 } 1594 boolean hasFinalizer() { 1595 return tree.finalizer != null; 1596 } 1597 1598 @Override 1599 void afterBody() { 1600 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) { 1601 //for body-only finally, remove the GenFinalizer after try body 1602 //so that the finally is not generated to catch bodies: 1603 tryEnv.info.finalize = null; 1604 } 1605 } 1606 1607 }; 1608 tryEnv.info.gaps = new ListBuffer<>(); 1609 genTry(tree.body, tree.catchers, tryEnv); 1610 } 1611 //where 1612 /** Generate code for a try or synchronized statement 1613 * @param body The body of the try or synchronized statement. 1614 * @param catchers The list of catch clauses. 1615 * @param env The current environment of the body. 1616 */ 1617 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1618 int limit = code.nextreg; 1619 int startpc = code.curCP(); 1620 Code.State stateTry = code.state.dup(); 1621 genStat(body, env, CRT_BLOCK); 1622 int endpc = code.curCP(); 1623 List<Integer> gaps = env.info.gaps.toList(); 1624 code.statBegin(TreeInfo.endPos(body)); 1625 genFinalizer(env); 1626 code.statBegin(TreeInfo.endPos(env.tree)); 1627 Chain exitChain; 1628 boolean actualTry = env.tree.hasTag(TRY); 1629 if (startpc == endpc && actualTry) { 1630 exitChain = code.branch(dontgoto); 1631 } else { 1632 exitChain = code.branch(goto_); 1633 } 1634 endFinalizerGap(env); 1635 env.info.finalize.afterBody(); 1636 boolean hasFinalizer = 1637 env.info.finalize != null && 1638 env.info.finalize.hasFinalizer(); 1639 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) { 1640 // start off with exception on stack 1641 code.entryPoint(stateTry, l.head.param.sym.type); 1642 genCatch(l.head, env, startpc, endpc, gaps); 1643 genFinalizer(env); 1644 if (hasFinalizer || l.tail.nonEmpty()) { 1645 code.statBegin(TreeInfo.endPos(env.tree)); 1646 exitChain = Code.mergeChains(exitChain, 1647 code.branch(goto_)); 1648 } 1649 endFinalizerGap(env); 1650 } 1651 if (hasFinalizer && (startpc != endpc || !actualTry)) { 1652 // Create a new register segment to avoid allocating 1653 // the same variables in finalizers and other statements. 1654 code.newRegSegment(); 1655 1656 // Add a catch-all clause. 1657 1658 // start off with exception on stack 1659 int catchallpc = code.entryPoint(stateTry, syms.throwableType); 1660 1661 // Register all exception ranges for catch all clause. 1662 // The range of the catch all clause is from the beginning 1663 // of the try or synchronized block until the present 1664 // code pointer excluding all gaps in the current 1665 // environment's GenContext. 1666 int startseg = startpc; 1667 while (env.info.gaps.nonEmpty()) { 1668 int endseg = env.info.gaps.next().intValue(); 1669 registerCatch(body.pos(), startseg, endseg, 1670 catchallpc, 0); 1671 startseg = env.info.gaps.next().intValue(); 1672 } 1673 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1674 code.markStatBegin(); 1675 1676 Item excVar = makeTemp(syms.throwableType); 1677 excVar.store(); 1678 genFinalizer(env); 1679 code.resolvePending(); 1680 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS)); 1681 code.markStatBegin(); 1682 1683 excVar.load(); 1684 registerCatch(body.pos(), startseg, 1685 env.info.gaps.next().intValue(), 1686 catchallpc, 0); 1687 code.emitop0(athrow); 1688 code.markDead(); 1689 1690 // If there are jsr's to this finalizer, ... 1691 if (env.info.cont != null) { 1692 // Resolve all jsr's. 1693 code.resolve(env.info.cont); 1694 1695 // Mark statement line number 1696 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1697 code.markStatBegin(); 1698 1699 // Save return address. 1700 LocalItem retVar = makeTemp(syms.throwableType); 1701 retVar.store(); 1702 1703 // Generate finalizer code. 1704 env.info.finalize.genLast(); 1705 1706 // Return. 1707 code.emitop1w(ret, retVar.reg); 1708 code.markDead(); 1709 } 1710 } 1711 // Resolve all breaks. 1712 code.resolve(exitChain); 1713 1714 code.endScopes(limit); 1715 } 1716 1717 /** Generate code for a catch clause. 1718 * @param tree The catch clause. 1719 * @param env The environment current in the enclosing try. 1720 * @param startpc Start pc of try-block. 1721 * @param endpc End pc of try-block. 1722 */ 1723 void genCatch(JCCatch tree, 1724 Env<GenContext> env, 1725 int startpc, int endpc, 1726 List<Integer> gaps) { 1727 if (startpc != endpc) { 1728 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs 1729 = catchTypesWithAnnotations(tree); 1730 while (gaps.nonEmpty()) { 1731 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1732 JCExpression subCatch = subCatch1.snd; 1733 int catchType = makeRef(tree.pos(), subCatch.type); 1734 int end = gaps.head.intValue(); 1735 registerCatch(tree.pos(), 1736 startpc, end, code.curCP(), 1737 catchType); 1738 for (Attribute.TypeCompound tc : subCatch1.fst) { 1739 tc.position.setCatchInfo(catchType, startpc); 1740 } 1741 } 1742 gaps = gaps.tail; 1743 startpc = gaps.head.intValue(); 1744 gaps = gaps.tail; 1745 } 1746 if (startpc < endpc) { 1747 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1748 JCExpression subCatch = subCatch1.snd; 1749 int catchType = makeRef(tree.pos(), subCatch.type); 1750 registerCatch(tree.pos(), 1751 startpc, endpc, code.curCP(), 1752 catchType); 1753 for (Attribute.TypeCompound tc : subCatch1.fst) { 1754 tc.position.setCatchInfo(catchType, startpc); 1755 } 1756 } 1757 } 1758 genCatchBlock(tree, env); 1759 } 1760 } 1761 void genPatternMatchingCatch(JCCatch tree, 1762 Env<GenContext> env, 1763 List<int[]> ranges) { 1764 for (int[] range : ranges) { 1765 JCExpression subCatch = tree.param.vartype; 1766 int catchType = makeRef(tree.pos(), subCatch.type); 1767 registerCatch(tree.pos(), 1768 range[0], range[1], code.curCP(), 1769 catchType); 1770 } 1771 genCatchBlock(tree, env); 1772 } 1773 void genCatchBlock(JCCatch tree, Env<GenContext> env) { 1774 VarSymbol exparam = tree.param.sym; 1775 code.statBegin(tree.pos); 1776 code.markStatBegin(); 1777 int limit = code.nextreg; 1778 code.newLocal(exparam); 1779 items.makeLocalItem(exparam).store(); 1780 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1781 genStat(tree.body, env, CRT_BLOCK); 1782 code.endScopes(limit); 1783 code.statBegin(TreeInfo.endPos(tree.body)); 1784 } 1785 // where 1786 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) { 1787 return TreeInfo.isMultiCatch(tree) ? 1788 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) : 1789 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype)); 1790 } 1791 // where 1792 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) { 1793 List<JCExpression> alts = tree.alternatives; 1794 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head)); 1795 alts = alts.tail; 1796 1797 while(alts != null && alts.head != null) { 1798 JCExpression alt = alts.head; 1799 if (alt instanceof JCAnnotatedType annotatedType) { 1800 res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt)); 1801 } else { 1802 res = res.prepend(new Pair<>(List.nil(), alt)); 1803 } 1804 alts = alts.tail; 1805 } 1806 return res.reverse(); 1807 } 1808 1809 /** Register a catch clause in the "Exceptions" code-attribute. 1810 */ 1811 void registerCatch(DiagnosticPosition pos, 1812 int startpc, int endpc, 1813 int handler_pc, int catch_type) { 1814 char startpc1 = (char)startpc; 1815 char endpc1 = (char)endpc; 1816 char handler_pc1 = (char)handler_pc; 1817 if (startpc1 == startpc && 1818 endpc1 == endpc && 1819 handler_pc1 == handler_pc) { 1820 code.addCatch(startpc1, endpc1, handler_pc1, 1821 (char)catch_type); 1822 } else { 1823 log.error(pos, Errors.LimitCodeTooLargeForTryStmt); 1824 nerrs++; 1825 } 1826 } 1827 1828 public void visitIf(JCIf tree) { 1829 int limit = code.nextreg; 1830 Chain thenExit = null; 1831 Assert.check(code.isStatementStart()); 1832 CondItem c = genCond(TreeInfo.skipParens(tree.cond), 1833 CRT_FLOW_CONTROLLER); 1834 Chain elseChain = c.jumpFalse(); 1835 Assert.check(code.isStatementStart()); 1836 if (!c.isFalse()) { 1837 code.resolve(c.trueJumps); 1838 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); 1839 thenExit = code.branch(goto_); 1840 } 1841 if (elseChain != null) { 1842 code.resolve(elseChain); 1843 if (tree.elsepart != null) { 1844 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); 1845 } 1846 } 1847 code.resolve(thenExit); 1848 code.endScopes(limit); 1849 Assert.check(code.isStatementStart()); 1850 } 1851 1852 public void visitExec(JCExpressionStatement tree) { 1853 // Optimize x++ to ++x and x-- to --x. 1854 JCExpression e = tree.expr; 1855 switch (e.getTag()) { 1856 case POSTINC: 1857 ((JCUnary) e).setTag(PREINC); 1858 break; 1859 case POSTDEC: 1860 ((JCUnary) e).setTag(PREDEC); 1861 break; 1862 } 1863 Assert.check(code.isStatementStart()); 1864 genExpr(tree.expr, tree.expr.type).drop(); 1865 Assert.check(code.isStatementStart()); 1866 } 1867 1868 public void visitBreak(JCBreak tree) { 1869 Assert.check(code.isStatementStart()); 1870 final Env<GenContext> targetEnv = unwindBreak(tree.target); 1871 targetEnv.info.addExit(code.branch(goto_)); 1872 endFinalizerGaps(env, targetEnv); 1873 } 1874 1875 public void visitYield(JCYield tree) { 1876 Assert.check(code.isStatementStart()); 1877 final Env<GenContext> targetEnv; 1878 if (inCondSwitchExpression) { 1879 CondItem value = genCond(tree.value, CRT_FLOW_TARGET); 1880 Chain falseJumps = value.jumpFalse(); 1881 1882 code.resolve(value.trueJumps); 1883 Env<GenContext> localEnv = unwindBreak(tree.target); 1884 reloadStackBeforeSwitchExpr(); 1885 Chain trueJumps = code.branch(goto_); 1886 1887 endFinalizerGaps(env, localEnv); 1888 1889 code.resolve(falseJumps); 1890 targetEnv = unwindBreak(tree.target); 1891 reloadStackBeforeSwitchExpr(); 1892 falseJumps = code.branch(goto_); 1893 1894 if (switchExpressionTrueChain == null) { 1895 switchExpressionTrueChain = trueJumps; 1896 } else { 1897 switchExpressionTrueChain = 1898 Code.mergeChains(switchExpressionTrueChain, trueJumps); 1899 } 1900 if (switchExpressionFalseChain == null) { 1901 switchExpressionFalseChain = falseJumps; 1902 } else { 1903 switchExpressionFalseChain = 1904 Code.mergeChains(switchExpressionFalseChain, falseJumps); 1905 } 1906 } else { 1907 genExpr(tree.value, pt).load(); 1908 if (switchResult != null) 1909 switchResult.store(); 1910 1911 targetEnv = unwindBreak(tree.target); 1912 1913 if (code.isAlive()) { 1914 reloadStackBeforeSwitchExpr(); 1915 if (switchResult != null) 1916 switchResult.load(); 1917 1918 code.state.forceStackTop(tree.target.type); 1919 targetEnv.info.addExit(code.branch(goto_)); 1920 code.markDead(); 1921 } 1922 } 1923 endFinalizerGaps(env, targetEnv); 1924 } 1925 //where: 1926 /** As side-effect, might mark code as dead disabling any further emission. 1927 */ 1928 private Env<GenContext> unwindBreak(JCTree target) { 1929 int tmpPos = code.pendingStatPos; 1930 Env<GenContext> targetEnv = unwind(target, env); 1931 code.pendingStatPos = tmpPos; 1932 return targetEnv; 1933 } 1934 1935 private void reloadStackBeforeSwitchExpr() { 1936 for (LocalItem li : stackBeforeSwitchExpression) 1937 li.load(); 1938 } 1939 1940 public void visitContinue(JCContinue tree) { 1941 int tmpPos = code.pendingStatPos; 1942 Env<GenContext> targetEnv = unwind(tree.target, env); 1943 code.pendingStatPos = tmpPos; 1944 Assert.check(code.isStatementStart()); 1945 targetEnv.info.addCont(code.branch(goto_)); 1946 endFinalizerGaps(env, targetEnv); 1947 } 1948 1949 public void visitReturn(JCReturn tree) { 1950 int limit = code.nextreg; 1951 final Env<GenContext> targetEnv; 1952 1953 /* Save and then restore the location of the return in case a finally 1954 * is expanded (with unwind()) in the middle of our bytecodes. 1955 */ 1956 int tmpPos = code.pendingStatPos; 1957 if (tree.expr != null) { 1958 Assert.check(code.isStatementStart()); 1959 Item r = genExpr(tree.expr, pt).load(); 1960 if (hasFinally(env.enclMethod, env)) { 1961 r = makeTemp(pt); 1962 r.store(); 1963 } 1964 targetEnv = unwind(env.enclMethod, env); 1965 code.pendingStatPos = tmpPos; 1966 r.load(); 1967 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 1968 } else { 1969 targetEnv = unwind(env.enclMethod, env); 1970 code.pendingStatPos = tmpPos; 1971 code.emitop0(return_); 1972 } 1973 endFinalizerGaps(env, targetEnv); 1974 code.endScopes(limit); 1975 } 1976 1977 public void visitThrow(JCThrow tree) { 1978 Assert.check(code.isStatementStart()); 1979 genExpr(tree.expr, tree.expr.type).load(); 1980 code.emitop0(athrow); 1981 Assert.check(code.isStatementStart()); 1982 } 1983 1984 /* ************************************************************************ 1985 * Visitor methods for expressions 1986 *************************************************************************/ 1987 1988 public void visitApply(JCMethodInvocation tree) { 1989 setTypeAnnotationPositions(tree.pos); 1990 // Generate code for method. 1991 Item m = genExpr(tree.meth, methodType); 1992 // Generate code for all arguments, where the expected types are 1993 // the parameters of the method's external type (that is, any implicit 1994 // outer instance of a super(...) call appears as first parameter). 1995 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 1996 genArgs(tree.args, 1997 msym.externalType(types).getParameterTypes()); 1998 if (!msym.isDynamic()) { 1999 code.statBegin(tree.pos); 2000 } 2001 if (invocationsWithPatternMatchingCatch.contains(tree)) { 2002 int start = code.curCP(); 2003 result = m.invoke(); 2004 patternMatchingInvocationRanges.add(new int[] {start, code.curCP()}); 2005 } else { 2006 result = m.invoke(); 2007 } 2008 } 2009 2010 public void visitConditional(JCConditional tree) { 2011 Chain thenExit = null; 2012 code.statBegin(tree.cond.pos); 2013 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 2014 Chain elseChain = c.jumpFalse(); 2015 if (!c.isFalse()) { 2016 code.resolve(c.trueJumps); 2017 int startpc = genCrt ? code.curCP() : 0; 2018 code.statBegin(tree.truepart.pos); 2019 genExpr(tree.truepart, pt).load(); 2020 code.state.forceStackTop(tree.type); 2021 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 2022 startpc, code.curCP()); 2023 thenExit = code.branch(goto_); 2024 } 2025 if (elseChain != null) { 2026 code.resolve(elseChain); 2027 int startpc = genCrt ? code.curCP() : 0; 2028 code.statBegin(tree.falsepart.pos); 2029 genExpr(tree.falsepart, pt).load(); 2030 code.state.forceStackTop(tree.type); 2031 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 2032 startpc, code.curCP()); 2033 } 2034 code.resolve(thenExit); 2035 result = items.makeStackItem(pt); 2036 } 2037 2038 private void setTypeAnnotationPositions(int treePos) { 2039 MethodSymbol meth = code.meth; 2040 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 2041 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 2042 2043 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 2044 if (ta.hasUnknownPosition()) 2045 ta.tryFixPosition(); 2046 2047 if (ta.position.matchesPos(treePos)) 2048 ta.position.updatePosOffset(code.cp); 2049 } 2050 2051 if (!initOrClinit) 2052 return; 2053 2054 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 2055 if (ta.hasUnknownPosition()) 2056 ta.tryFixPosition(); 2057 2058 if (ta.position.matchesPos(treePos)) 2059 ta.position.updatePosOffset(code.cp); 2060 } 2061 2062 ClassSymbol clazz = meth.enclClass(); 2063 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 2064 if (!s.getKind().isField()) 2065 continue; 2066 2067 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 2068 if (ta.hasUnknownPosition()) 2069 ta.tryFixPosition(); 2070 2071 if (ta.position.matchesPos(treePos)) 2072 ta.position.updatePosOffset(code.cp); 2073 } 2074 } 2075 } 2076 2077 public void visitNewClass(JCNewClass tree) { 2078 // Enclosing instances or anonymous classes should have been eliminated 2079 // by now. 2080 Assert.check(tree.encl == null && tree.def == null); 2081 setTypeAnnotationPositions(tree.pos); 2082 2083 code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass); 2084 code.emitop0(dup); 2085 2086 // Generate code for all arguments, where the expected types are 2087 // the parameters of the constructor's external type (that is, 2088 // any implicit outer instance appears as first parameter). 2089 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 2090 2091 items.makeMemberItem(tree.constructor, true).invoke(); 2092 result = items.makeStackItem(tree.type); 2093 } 2094 2095 public void visitNewArray(JCNewArray tree) { 2096 setTypeAnnotationPositions(tree.pos); 2097 2098 if (tree.elems != null) { 2099 Type elemtype = types.elemtype(tree.type); 2100 loadIntConst(tree.elems.length()); 2101 Item arr = makeNewArray(tree.pos(), tree.type, 1); 2102 int i = 0; 2103 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 2104 arr.duplicate(); 2105 loadIntConst(i); 2106 i++; 2107 genExpr(l.head, elemtype).load(); 2108 items.makeIndexedItem(elemtype).store(); 2109 } 2110 result = arr; 2111 } else { 2112 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2113 genExpr(l.head, syms.intType).load(); 2114 } 2115 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 2116 } 2117 } 2118 //where 2119 /** Generate code to create an array with given element type and number 2120 * of dimensions. 2121 */ 2122 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 2123 Type elemtype = types.elemtype(type); 2124 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 2125 log.error(pos, Errors.LimitDimensions); 2126 nerrs++; 2127 } 2128 int elemcode = Code.arraycode(elemtype); 2129 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { 2130 code.emitAnewarray(makeRef(pos, elemtype, elemtype.isPrimitiveClass()), type); 2131 } else if (elemcode == 1) { 2132 code.emitMultianewarray(ndims, makeRef(pos, type), type); 2133 } else { 2134 code.emitNewarray(elemcode, type); 2135 } 2136 return items.makeStackItem(type); 2137 } 2138 2139 public void visitParens(JCParens tree) { 2140 result = genExpr(tree.expr, tree.expr.type); 2141 } 2142 2143 public void visitAssign(JCAssign tree) { 2144 Item l = genExpr(tree.lhs, tree.lhs.type); 2145 genExpr(tree.rhs, tree.lhs.type).load(); 2146 if (tree.rhs.type.hasTag(BOT)) { 2147 /* This is just a case of widening reference conversion that per 5.1.5 simply calls 2148 for "regarding a reference as having some other type in a manner that can be proved 2149 correct at compile time." 2150 */ 2151 code.state.forceStackTop(tree.lhs.type); 2152 } 2153 result = items.makeAssignItem(l); 2154 } 2155 2156 public void visitAssignop(JCAssignOp tree) { 2157 OperatorSymbol operator = tree.operator; 2158 Item l; 2159 if (operator.opcode == string_add) { 2160 l = concat.makeConcat(tree); 2161 } else { 2162 // Generate code for first expression 2163 l = genExpr(tree.lhs, tree.lhs.type); 2164 2165 // If we have an increment of -32768 to +32767 of a local 2166 // int variable we can use an incr instruction instead of 2167 // proceeding further. 2168 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 2169 l instanceof LocalItem localItem && 2170 tree.lhs.type.getTag().isSubRangeOf(INT) && 2171 tree.rhs.type.getTag().isSubRangeOf(INT) && 2172 tree.rhs.type.constValue() != null) { 2173 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 2174 if (tree.hasTag(MINUS_ASG)) ival = -ival; 2175 localItem.incr(ival); 2176 result = l; 2177 return; 2178 } 2179 // Otherwise, duplicate expression, load one copy 2180 // and complete binary operation. 2181 l.duplicate(); 2182 l.coerce(operator.type.getParameterTypes().head).load(); 2183 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 2184 } 2185 result = items.makeAssignItem(l); 2186 } 2187 2188 public void visitUnary(JCUnary tree) { 2189 OperatorSymbol operator = tree.operator; 2190 if (tree.hasTag(NOT)) { 2191 CondItem od = genCond(tree.arg, false); 2192 result = od.negate(); 2193 } else { 2194 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 2195 switch (tree.getTag()) { 2196 case POS: 2197 result = od.load(); 2198 break; 2199 case NEG: 2200 result = od.load(); 2201 code.emitop0(operator.opcode); 2202 break; 2203 case COMPL: 2204 result = od.load(); 2205 emitMinusOne(od.typecode); 2206 code.emitop0(operator.opcode); 2207 break; 2208 case PREINC: case PREDEC: 2209 od.duplicate(); 2210 if (od instanceof LocalItem localItem && 2211 (operator.opcode == iadd || operator.opcode == isub)) { 2212 localItem.incr(tree.hasTag(PREINC) ? 1 : -1); 2213 result = od; 2214 } else { 2215 od.load(); 2216 code.emitop0(one(od.typecode)); 2217 code.emitop0(operator.opcode); 2218 // Perform narrowing primitive conversion if byte, 2219 // char, or short. Fix for 4304655. 2220 if (od.typecode != INTcode && 2221 Code.truncate(od.typecode) == INTcode) 2222 code.emitop0(int2byte + od.typecode - BYTEcode); 2223 result = items.makeAssignItem(od); 2224 } 2225 break; 2226 case POSTINC: case POSTDEC: 2227 od.duplicate(); 2228 if (od instanceof LocalItem localItem && 2229 (operator.opcode == iadd || operator.opcode == isub)) { 2230 Item res = od.load(); 2231 localItem.incr(tree.hasTag(POSTINC) ? 1 : -1); 2232 result = res; 2233 } else { 2234 Item res = od.load(); 2235 od.stash(od.typecode); 2236 code.emitop0(one(od.typecode)); 2237 code.emitop0(operator.opcode); 2238 // Perform narrowing primitive conversion if byte, 2239 // char, or short. Fix for 4304655. 2240 if (od.typecode != INTcode && 2241 Code.truncate(od.typecode) == INTcode) 2242 code.emitop0(int2byte + od.typecode - BYTEcode); 2243 od.store(); 2244 result = res; 2245 } 2246 break; 2247 case NULLCHK: 2248 result = od.load(); 2249 code.emitop0(dup); 2250 genNullCheck(tree); 2251 break; 2252 default: 2253 Assert.error(); 2254 } 2255 } 2256 } 2257 2258 /** Generate a null check from the object value at stack top. */ 2259 private void genNullCheck(JCTree tree) { 2260 code.statBegin(tree.pos); 2261 callMethod(tree.pos(), syms.objectsType, names.requireNonNull, 2262 List.of(syms.objectType), true); 2263 code.emitop0(pop); 2264 } 2265 2266 public void visitBinary(JCBinary tree) { 2267 OperatorSymbol operator = tree.operator; 2268 if (operator.opcode == string_add) { 2269 result = concat.makeConcat(tree); 2270 } else if (tree.hasTag(AND)) { 2271 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2272 if (!lcond.isFalse()) { 2273 Chain falseJumps = lcond.jumpFalse(); 2274 code.resolve(lcond.trueJumps); 2275 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2276 result = items. 2277 makeCondItem(rcond.opcode, 2278 rcond.trueJumps, 2279 Code.mergeChains(falseJumps, 2280 rcond.falseJumps)); 2281 } else { 2282 result = lcond; 2283 } 2284 } else if (tree.hasTag(OR)) { 2285 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2286 if (!lcond.isTrue()) { 2287 Chain trueJumps = lcond.jumpTrue(); 2288 code.resolve(lcond.falseJumps); 2289 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2290 result = items. 2291 makeCondItem(rcond.opcode, 2292 Code.mergeChains(trueJumps, rcond.trueJumps), 2293 rcond.falseJumps); 2294 } else { 2295 result = lcond; 2296 } 2297 } else { 2298 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2299 od.load(); 2300 result = completeBinop(tree.lhs, tree.rhs, operator); 2301 } 2302 } 2303 2304 2305 /** Complete generating code for operation, with left operand 2306 * already on stack. 2307 * @param lhs The tree representing the left operand. 2308 * @param rhs The tree representing the right operand. 2309 * @param operator The operator symbol. 2310 */ 2311 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2312 MethodType optype = (MethodType)operator.type; 2313 int opcode = operator.opcode; 2314 if (opcode >= if_icmpeq && opcode <= if_icmple && 2315 rhs.type.constValue() instanceof Number number && 2316 number.intValue() == 0) { 2317 opcode = opcode + (ifeq - if_icmpeq); 2318 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2319 TreeInfo.isNull(rhs)) { 2320 opcode = opcode + (if_acmp_null - if_acmpeq); 2321 } else { 2322 // The expected type of the right operand is 2323 // the second parameter type of the operator, except for 2324 // shifts with long shiftcount, where we convert the opcode 2325 // to a short shift and the expected type to int. 2326 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2327 if (opcode >= ishll && opcode <= lushrl) { 2328 opcode = opcode + (ishl - ishll); 2329 rtype = syms.intType; 2330 } 2331 // Generate code for right operand and load. 2332 genExpr(rhs, rtype).load(); 2333 // If there are two consecutive opcode instructions, 2334 // emit the first now. 2335 if (opcode >= (1 << preShift)) { 2336 code.emitop0(opcode >> preShift); 2337 opcode = opcode & 0xFF; 2338 } 2339 } 2340 if (opcode >= ifeq && opcode <= if_acmpne || 2341 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2342 return items.makeCondItem(opcode); 2343 } else { 2344 code.emitop0(opcode); 2345 return items.makeStackItem(optype.restype); 2346 } 2347 } 2348 2349 public void visitTypeCast(JCTypeCast tree) { 2350 result = genExpr(tree.expr, tree.clazz.type).load(); 2351 setTypeAnnotationPositions(tree.pos); 2352 // Additional code is only needed if we cast to a reference type 2353 // which is not statically a supertype of the expression's type. 2354 // For basic types, the coerce(...) in genExpr(...) will do 2355 // the conversion. 2356 // primitive reference conversion is a nop when we bifurcate the primitive class, as the VM sees a subtyping relationship. 2357 if (!tree.clazz.type.isPrimitive() && 2358 !types.isSameType(tree.expr.type, tree.clazz.type) && 2359 (!tree.clazz.type.isReferenceProjection() || !types.isSameType(tree.clazz.type.valueProjection(), tree.expr.type) || true) && 2360 !types.isSubtype(tree.expr.type, tree.clazz.type)) { 2361 checkDimension(tree.pos(), tree.clazz.type); 2362 if (tree.clazz.type.isPrimitiveClass()) { 2363 code.emitop2(checkcast, new ConstantPoolQType(tree.clazz.type, types), PoolWriter::putClass); 2364 } else { 2365 code.emitop2(checkcast, tree.clazz.type, PoolWriter::putClass); 2366 } 2367 2368 } 2369 } 2370 2371 public void visitWildcard(JCWildcard tree) { 2372 throw new AssertionError(this.getClass().getName()); 2373 } 2374 2375 public void visitTypeTest(JCInstanceOf tree) { 2376 genExpr(tree.expr, tree.expr.type).load(); 2377 setTypeAnnotationPositions(tree.pos); 2378 code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type)); 2379 result = items.makeStackItem(syms.booleanType); 2380 } 2381 2382 public void visitIndexed(JCArrayAccess tree) { 2383 genExpr(tree.indexed, tree.indexed.type).load(); 2384 genExpr(tree.index, syms.intType).load(); 2385 result = items.makeIndexedItem(tree.type); 2386 } 2387 2388 public void visitIdent(JCIdent tree) { 2389 Symbol sym = tree.sym; 2390 if (tree.name == names._this || tree.name == names._super) { 2391 Item res = tree.name == names._this 2392 ? items.makeThisItem() 2393 : items.makeSuperItem(); 2394 if (sym.kind == MTH) { 2395 // Generate code to address the constructor. 2396 res.load(); 2397 res = items.makeMemberItem(sym, true); 2398 } 2399 result = res; 2400 } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) { 2401 if (isConstantDynamic(sym)) { 2402 setTypeAnnotationPositions(tree.pos); 2403 } 2404 result = items.makeDynamicItem(sym); 2405 } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) { 2406 result = items.makeLocalItem((VarSymbol)sym); 2407 } else if ((sym.flags() & STATIC) != 0) { 2408 if (!isAccessSuper(env.enclMethod)) 2409 sym = binaryQualifier(sym, env.enclClass.type); 2410 result = items.makeStaticItem(sym); 2411 } else { 2412 items.makeThisItem().load(); 2413 sym = binaryQualifier(sym, env.enclClass.type); 2414 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym)); 2415 } 2416 } 2417 2418 //where 2419 private boolean nonVirtualForPrivateAccess(Symbol sym) { 2420 boolean useVirtual = target.hasVirtualPrivateInvoke() && 2421 !disableVirtualizedPrivateInvoke; 2422 return !useVirtual && ((sym.flags() & PRIVATE) != 0); 2423 } 2424 2425 public void visitSelect(JCFieldAccess tree) { 2426 Symbol sym = tree.sym; 2427 2428 if (tree.name == names._class) { 2429 code.emitLdc((LoadableConstant) tree.selected.type, makeRef(tree.pos(), tree.selected.type, tree.selected.type.isPrimitiveClass())); 2430 result = items.makeStackItem(pt); 2431 return; 2432 } 2433 2434 Symbol ssym = TreeInfo.symbol(tree.selected); 2435 2436 // Are we selecting via super? 2437 boolean selectSuper = 2438 ssym != null && (ssym.kind == TYP || ssym.name == names._super); 2439 2440 // Are we accessing a member of the superclass in an access method 2441 // resulting from a qualified super? 2442 boolean accessSuper = isAccessSuper(env.enclMethod); 2443 2444 Item base = (selectSuper) 2445 ? items.makeSuperItem() 2446 : genExpr(tree.selected, tree.selected.type); 2447 2448 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { 2449 // We are seeing a variable that is constant but its selecting 2450 // expression is not. 2451 if ((sym.flags() & STATIC) != 0) { 2452 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2453 base = base.load(); 2454 base.drop(); 2455 } else { 2456 base.load(); 2457 genNullCheck(tree.selected); 2458 } 2459 result = items. 2460 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2461 } else { 2462 if (isInvokeDynamic(sym)) { 2463 result = items.makeDynamicItem(sym); 2464 return; 2465 } else { 2466 sym = binaryQualifier(sym, tree.selected.type); 2467 } 2468 if ((sym.flags() & STATIC) != 0) { 2469 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2470 base = base.load(); 2471 base.drop(); 2472 result = items.makeStaticItem(sym); 2473 } else { 2474 base.load(); 2475 if (sym == syms.lengthVar) { 2476 code.emitop0(arraylength); 2477 result = items.makeStackItem(syms.intType); 2478 } else { 2479 result = items. 2480 makeMemberItem(sym, 2481 nonVirtualForPrivateAccess(sym) || 2482 selectSuper || accessSuper); 2483 } 2484 } 2485 } 2486 } 2487 2488 public void visitDefaultValue(JCDefaultValue tree) { 2489 if (tree.type.isValueClass()) { 2490 code.emitop2(aconst_init, checkDimension(tree.pos(), tree.type), PoolWriter::putClass); 2491 } else if (tree.type.isReference()) { 2492 code.emitop0(aconst_null); 2493 } else { 2494 code.emitop0(zero(Code.typecode(tree.type))); 2495 } 2496 result = items.makeStackItem(tree.type); 2497 return; 2498 } 2499 2500 public boolean isInvokeDynamic(Symbol sym) { 2501 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2502 } 2503 2504 public void visitLiteral(JCLiteral tree) { 2505 if (tree.type.hasTag(BOT)) { 2506 code.emitop0(aconst_null); 2507 result = items.makeStackItem(tree.type); 2508 } 2509 else 2510 result = items.makeImmediateItem(tree.type, tree.value); 2511 } 2512 2513 public void visitLetExpr(LetExpr tree) { 2514 code.resolvePending(); 2515 2516 int limit = code.nextreg; 2517 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 2518 try { 2519 genStats(tree.defs, env); 2520 } finally { 2521 code.setLetExprStackPos(prevLetExprStart); 2522 } 2523 result = genExpr(tree.expr, tree.expr.type).load(); 2524 code.endScopes(limit); 2525 } 2526 2527 private void generateReferencesToPrunedTree(ClassSymbol classSymbol) { 2528 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2529 if (prunedInfo != null) { 2530 for (JCTree prunedTree: prunedInfo) { 2531 prunedTree.accept(classReferenceVisitor); 2532 } 2533 } 2534 } 2535 2536 /* ************************************************************************ 2537 * main method 2538 *************************************************************************/ 2539 2540 /** Generate code for a class definition. 2541 * @param env The attribution environment that belongs to the 2542 * outermost class containing this class definition. 2543 * We need this for resolving some additional symbols. 2544 * @param cdef The tree representing the class definition. 2545 * @return True if code is generated with no errors. 2546 */ 2547 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2548 try { 2549 attrEnv = env; 2550 ClassSymbol c = cdef.sym; 2551 this.toplevel = env.toplevel; 2552 this.endPosTable = toplevel.endPositions; 2553 /* method normalizeDefs() can add references to external classes into the constant pool 2554 */ 2555 cdef.defs = normalizeDefs(cdef.defs, c); 2556 cdef = transValues.translateTopLevelClass(cdef, make); 2557 generateReferencesToPrunedTree(c); 2558 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2559 localEnv.toplevel = env.toplevel; 2560 localEnv.enclClass = cdef; 2561 2562 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2563 genDef(l.head, localEnv); 2564 } 2565 if (poolWriter.size() > PoolWriter.MAX_ENTRIES) { 2566 log.error(cdef.pos(), Errors.LimitPool); 2567 nerrs++; 2568 } 2569 if (nerrs != 0) { 2570 // if errors, discard code 2571 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2572 if (l.head.hasTag(METHODDEF)) 2573 ((JCMethodDecl) l.head).sym.code = null; 2574 } 2575 } 2576 cdef.defs = List.nil(); // discard trees 2577 return nerrs == 0; 2578 } finally { 2579 // note: this method does NOT support recursion. 2580 attrEnv = null; 2581 this.env = null; 2582 toplevel = null; 2583 endPosTable = null; 2584 nerrs = 0; 2585 qualifiedSymbolCache.clear(); 2586 } 2587 } 2588 2589 /* ************************************************************************ 2590 * Auxiliary classes 2591 *************************************************************************/ 2592 2593 /** An abstract class for finalizer generation. 2594 */ 2595 abstract class GenFinalizer { 2596 /** Generate code to clean up when unwinding. */ 2597 abstract void gen(); 2598 2599 /** Generate code to clean up at last. */ 2600 abstract void genLast(); 2601 2602 /** Does this finalizer have some nontrivial cleanup to perform? */ 2603 boolean hasFinalizer() { return true; } 2604 2605 /** Should be invoked after the try's body has been visited. */ 2606 void afterBody() {} 2607 } 2608 2609 /** code generation contexts, 2610 * to be used as type parameter for environments. 2611 */ 2612 static class GenContext { 2613 2614 /** A chain for all unresolved jumps that exit the current environment. 2615 */ 2616 Chain exit = null; 2617 2618 /** A chain for all unresolved jumps that continue in the 2619 * current environment. 2620 */ 2621 Chain cont = null; 2622 2623 /** A closure that generates the finalizer of the current environment. 2624 * Only set for Synchronized and Try contexts. 2625 */ 2626 GenFinalizer finalize = null; 2627 2628 /** Is this a switch statement? If so, allocate registers 2629 * even when the variable declaration is unreachable. 2630 */ 2631 boolean isSwitch = false; 2632 2633 /** A list buffer containing all gaps in the finalizer range, 2634 * where a catch all exception should not apply. 2635 */ 2636 ListBuffer<Integer> gaps = null; 2637 2638 /** Add given chain to exit chain. 2639 */ 2640 void addExit(Chain c) { 2641 exit = Code.mergeChains(c, exit); 2642 } 2643 2644 /** Add given chain to cont chain. 2645 */ 2646 void addCont(Chain c) { 2647 cont = Code.mergeChains(c, cont); 2648 } 2649 } 2650 2651 } --- EOF ---