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