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.endpos = 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.endpos == Position.NOPOS) 579 md.body.endpos = 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 return result; 816 } else { 817 CondItem result = genExpr(_tree, syms.booleanType).mkCond(); 818 if (markBranches) result.tree = _tree; 819 return result; 820 } 821 } 822 823 public Code getCode() { 824 return code; 825 } 826 827 public Items getItems() { 828 return items; 829 } 830 831 public Env<AttrContext> getAttrEnv() { 832 return attrEnv; 833 } 834 835 /** Visitor class for expressions which might be constant expressions. 836 * This class is a subset of TreeScanner. Intended to visit trees pruned by 837 * Lower as long as constant expressions looking for references to any 838 * ClassSymbol. Any such reference will be added to the constant pool so 839 * automated tools can detect class dependencies better. 840 */ 841 class ClassReferenceVisitor extends JCTree.Visitor { 842 843 @Override 844 public void visitTree(JCTree tree) {} 845 846 @Override 847 public void visitBinary(JCBinary tree) { 848 tree.lhs.accept(this); 849 tree.rhs.accept(this); 850 } 851 852 @Override 853 public void visitSelect(JCFieldAccess tree) { 854 if (tree.selected.type.hasTag(CLASS)) { 855 makeRef(tree.selected.pos(), tree.selected.type); 856 } 857 } 858 859 @Override 860 public void visitIdent(JCIdent tree) { 861 if (tree.sym.owner instanceof ClassSymbol classSymbol) { 862 poolWriter.putClass(classSymbol); 863 } 864 } 865 866 @Override 867 public void visitConditional(JCConditional tree) { 868 tree.cond.accept(this); 869 tree.truepart.accept(this); 870 tree.falsepart.accept(this); 871 } 872 873 @Override 874 public void visitUnary(JCUnary tree) { 875 tree.arg.accept(this); 876 } 877 878 @Override 879 public void visitParens(JCParens tree) { 880 tree.expr.accept(this); 881 } 882 883 @Override 884 public void visitTypeCast(JCTypeCast tree) { 885 tree.expr.accept(this); 886 } 887 } 888 889 private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor(); 890 891 /** Visitor method: generate code for an expression, catching and reporting 892 * any completion failures. 893 * @param tree The expression to be visited. 894 * @param pt The expression's expected type (proto-type). 895 */ 896 public Item genExpr(JCTree tree, Type pt) { 897 if (!code.isAlive()) { 898 return items.makeStackItem(pt); 899 } 900 901 Type prevPt = this.pt; 902 try { 903 if (tree.type.constValue() != null) { 904 // Short circuit any expressions which are constants 905 tree.accept(classReferenceVisitor); 906 checkStringConstant(tree.pos(), tree.type.constValue()); 907 Symbol sym = TreeInfo.symbol(tree); 908 if (sym != null && isConstantDynamic(sym)) { 909 result = items.makeDynamicItem(sym); 910 } else { 911 result = items.makeImmediateItem(tree.type, tree.type.constValue()); 912 } 913 } else { 914 this.pt = pt; 915 tree.accept(this); 916 } 917 return result.coerce(pt); 918 } catch (CompletionFailure ex) { 919 chk.completionError(tree.pos(), ex); 920 code.state.stacksize = 1; 921 return items.makeStackItem(pt); 922 } finally { 923 this.pt = prevPt; 924 } 925 } 926 927 public boolean isConstantDynamic(Symbol sym) { 928 return sym.kind == VAR && 929 sym instanceof DynamicVarSymbol dynamicVarSymbol && 930 dynamicVarSymbol.isDynamic(); 931 } 932 933 /** Derived visitor method: generate code for a list of method arguments. 934 * @param trees The argument expressions to be visited. 935 * @param pts The expression's expected types (i.e. the formal parameter 936 * types of the invoked method). 937 */ 938 public void genArgs(List<JCExpression> trees, List<Type> pts) { 939 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { 940 genExpr(l.head, pts.head).load(); 941 pts = pts.tail; 942 } 943 // require lists be of same length 944 Assert.check(pts.isEmpty()); 945 } 946 947 /* ************************************************************************ 948 * Visitor methods for statements and definitions 949 *************************************************************************/ 950 951 /** Thrown when the byte code size exceeds limit. 952 */ 953 public static class CodeSizeOverflow extends RuntimeException { 954 private static final long serialVersionUID = 0; 955 public CodeSizeOverflow() {} 956 } 957 958 public void visitMethodDef(JCMethodDecl tree) { 959 // Create a new local environment that points pack at method 960 // definition. 961 Env<GenContext> localEnv = env.dup(tree); 962 localEnv.enclMethod = tree; 963 // The expected type of every return statement in this method 964 // is the method's return type. 965 this.pt = tree.sym.erasure(types).getReturnType(); 966 967 checkDimension(tree.pos(), tree.sym.erasure(types)); 968 genMethod(tree, localEnv, false); 969 } 970 //where 971 /** Generate code for a method. 972 * @param tree The tree representing the method definition. 973 * @param env The environment current for the method body. 974 * @param fatcode A flag that indicates whether all jumps are 975 * within 32K. We first invoke this method under 976 * the assumption that fatcode == false, i.e. all 977 * jumps are within 32K. If this fails, fatcode 978 * is set to true and we try again. 979 */ 980 void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 981 MethodSymbol meth = tree.sym; 982 int extras = 0; 983 // Count up extra parameters 984 if (meth.isConstructor()) { 985 extras++; 986 if (meth.enclClass().isInner() && 987 !meth.enclClass().isStatic()) { 988 extras++; 989 } 990 } else if ((tree.mods.flags & STATIC) == 0) { 991 extras++; 992 } 993 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG 994 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras > 995 ClassFile.MAX_PARAMETERS) { 996 log.error(tree.pos(), Errors.LimitParameters); 997 nerrs++; 998 } 999 1000 else if (tree.body != null) { 1001 // Create a new code structure and initialize it. 1002 int startpcCrt = initCode(tree, env, fatcode); 1003 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields; 1004 if (meth.isConstructor()) { 1005 code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body); 1006 code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body); 1007 } 1008 1009 try { 1010 genStat(tree.body, env); 1011 } catch (CodeSizeOverflow e) { 1012 // Failed due to code limit, try again with jsr/ret 1013 startpcCrt = initCode(tree, env, fatcode); 1014 genStat(tree.body, env); 1015 } finally { 1016 code.currentUnsetFields = prevUnsetFields; 1017 } 1018 1019 if (code.state.stacksize != 0) { 1020 log.error(tree.body.pos(), Errors.StackSimError(tree.sym)); 1021 throw new AssertionError(); 1022 } 1023 1024 // If last statement could complete normally, insert a 1025 // return at the end. 1026 if (code.isAlive()) { 1027 code.statBegin(TreeInfo.endPos(tree.body)); 1028 if (env.enclMethod == null || 1029 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) { 1030 code.emitop0(return_); 1031 } else { 1032 // sometime dead code seems alive (4415991); 1033 // generate a small loop instead 1034 int startpc = code.entryPoint(); 1035 CondItem c = items.makeCondItem(goto_); 1036 code.resolve(c.jumpTrue(), startpc); 1037 } 1038 } 1039 if (genCrt) 1040 code.crt.put(tree.body, 1041 CRT_BLOCK, 1042 startpcCrt, 1043 code.curCP()); 1044 1045 code.endScopes(0); 1046 1047 // If we exceeded limits, panic 1048 if (code.checkLimits(tree.pos(), log)) { 1049 nerrs++; 1050 return; 1051 } 1052 1053 // If we generated short code but got a long jump, do it again 1054 // with fatCode = true. 1055 if (!fatcode && code.fatcode) genMethod(tree, env, true); 1056 1057 // Clean up 1058 if(stackMap == StackMapFormat.JSR202) { 1059 code.lastFrame = null; 1060 code.frameBeforeLast = null; 1061 } 1062 1063 // Compress exception table 1064 code.compressCatchTable(); 1065 1066 // Fill in type annotation positions for exception parameters 1067 code.fillExceptionParameterPositions(); 1068 } 1069 } 1070 1071 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 1072 MethodSymbol meth = tree.sym; 1073 1074 // Create a new code structure. 1075 meth.code = code = new Code(meth, 1076 fatcode, 1077 lineDebugInfo ? toplevel.lineMap : null, 1078 varDebugInfo, 1079 stackMap, 1080 debugCode, 1081 genCrt ? new CRTable(tree, env.toplevel.endPositions) 1082 : null, 1083 syms, 1084 types, 1085 poolWriter, 1086 generateEarlyLarvalFrame); 1087 items = new Items(poolWriter, code, syms, types); 1088 if (code.debugCode) { 1089 System.err.println(meth + " for body " + tree); 1090 } 1091 1092 // If method is not static, create a new local variable address 1093 // for `this'. 1094 if ((tree.mods.flags & STATIC) == 0) { 1095 Type selfType = meth.owner.type; 1096 if (meth.isConstructor() && selfType != syms.objectType) 1097 selfType = UninitializedType.uninitializedThis(selfType); 1098 code.setDefined( 1099 code.newLocal( 1100 new VarSymbol(FINAL, names._this, selfType, meth.owner))); 1101 } 1102 1103 // Mark all parameters as defined from the beginning of 1104 // the method. 1105 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 1106 checkDimension(l.head.pos(), l.head.sym.type); 1107 code.setDefined(code.newLocal(l.head.sym)); 1108 } 1109 1110 // Get ready to generate code for method body. 1111 int startpcCrt = genCrt ? code.curCP() : 0; 1112 code.entryPoint(); 1113 1114 // Suppress initial stackmap 1115 code.pendingStackMap = false; 1116 1117 return startpcCrt; 1118 } 1119 1120 public void visitVarDef(JCVariableDecl tree) { 1121 VarSymbol v = tree.sym; 1122 if (tree.init != null) { 1123 checkStringConstant(tree.init.pos(), v.getConstValue()); 1124 if (v.getConstValue() == null || varDebugInfo) { 1125 Assert.check(code.isStatementStart()); 1126 code.newLocal(v); 1127 genExpr(tree.init, v.erasure(types)).load(); 1128 items.makeLocalItem(v).store(); 1129 Assert.check(code.isStatementStart()); 1130 } 1131 } else { 1132 code.newLocal(v); 1133 } 1134 checkDimension(tree.pos(), v.type); 1135 } 1136 1137 public void visitSkip(JCSkip tree) { 1138 } 1139 1140 public void visitBlock(JCBlock tree) { 1141 /* this method is heavily invoked, as expected, for deeply nested blocks, if blocks doesn't happen to have 1142 * patterns there will be an unnecessary tax on memory consumption every time this method is executed, for this 1143 * reason we have created helper methods and here at a higher level we just discriminate depending on the 1144 * presence, or not, of patterns in a given block 1145 */ 1146 if (tree.patternMatchingCatch != null) { 1147 visitBlockWithPatterns(tree); 1148 } else { 1149 internalVisitBlock(tree); 1150 } 1151 } 1152 1153 private void visitBlockWithPatterns(JCBlock tree) { 1154 PatternMatchingCatchConfiguration prevConfiguration = patternMatchingCatchConfiguration; 1155 try { 1156 patternMatchingCatchConfiguration = 1157 new PatternMatchingCatchConfiguration(tree.patternMatchingCatch.calls2Handle(), 1158 new ListBuffer<int[]>(), 1159 tree.patternMatchingCatch.handler(), 1160 code.state.dup()); 1161 internalVisitBlock(tree); 1162 } finally { 1163 generatePatternMatchingCatch(env); 1164 patternMatchingCatchConfiguration = prevConfiguration; 1165 } 1166 } 1167 1168 private void generatePatternMatchingCatch(Env<GenContext> env) { 1169 if (patternMatchingCatchConfiguration.handler != null && 1170 !patternMatchingCatchConfiguration.ranges.isEmpty()) { 1171 Chain skipCatch = code.branch(goto_); 1172 JCCatch handler = patternMatchingCatchConfiguration.handler(); 1173 code.entryPoint(patternMatchingCatchConfiguration.startState(), 1174 handler.param.sym.type); 1175 genPatternMatchingCatch(handler, 1176 env, 1177 patternMatchingCatchConfiguration.ranges.toList()); 1178 code.resolve(skipCatch); 1179 } 1180 } 1181 1182 private void internalVisitBlock(JCBlock tree) { 1183 int limit = code.nextreg; 1184 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1185 genStats(tree.stats, localEnv); 1186 // End the scope of all block-local variables in variable info. 1187 if (!env.tree.hasTag(METHODDEF)) { 1188 code.statBegin(tree.endpos); 1189 code.endScopes(limit); 1190 code.pendingStatPos = Position.NOPOS; 1191 } 1192 } 1193 1194 public void visitDoLoop(JCDoWhileLoop tree) { 1195 genLoop(tree, tree.body, tree.cond, List.nil(), false); 1196 } 1197 1198 public void visitWhileLoop(JCWhileLoop tree) { 1199 genLoop(tree, tree.body, tree.cond, List.nil(), true); 1200 } 1201 1202 public void visitForLoop(JCForLoop tree) { 1203 int limit = code.nextreg; 1204 genStats(tree.init, env); 1205 genLoop(tree, tree.body, tree.cond, tree.step, true); 1206 code.endScopes(limit); 1207 } 1208 //where 1209 /** Generate code for a loop. 1210 * @param loop The tree representing the loop. 1211 * @param body The loop's body. 1212 * @param cond The loop's controlling condition. 1213 * @param step "Step" statements to be inserted at end of 1214 * each iteration. 1215 * @param testFirst True if the loop test belongs before the body. 1216 */ 1217 private void genLoop(JCStatement loop, 1218 JCStatement body, 1219 JCExpression cond, 1220 List<JCExpressionStatement> step, 1221 boolean testFirst) { 1222 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields; 1223 try { 1224 genLoopHelper(loop, body, cond, step, testFirst); 1225 } finally { 1226 code.currentUnsetFields = prevCodeUnsetFields; 1227 } 1228 } 1229 1230 private void genLoopHelper(JCStatement loop, 1231 JCStatement body, 1232 JCExpression cond, 1233 List<JCExpressionStatement> step, 1234 boolean testFirst) { 1235 Env<GenContext> loopEnv = env.dup(loop, new GenContext()); 1236 int startpc = code.entryPoint(); 1237 if (testFirst) { //while or for loop 1238 CondItem c; 1239 if (cond != null) { 1240 code.statBegin(cond.pos); 1241 Assert.check(code.isStatementStart()); 1242 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1243 } else { 1244 c = items.makeCondItem(goto_); 1245 } 1246 Chain loopDone = c.jumpFalse(); 1247 code.resolve(c.trueJumps); 1248 Assert.check(code.isStatementStart()); 1249 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1250 code.resolve(loopEnv.info.cont); 1251 genStats(step, loopEnv); 1252 code.resolve(code.branch(goto_), startpc); 1253 code.resolve(loopDone); 1254 } else { 1255 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1256 code.resolve(loopEnv.info.cont); 1257 genStats(step, loopEnv); 1258 if (code.isAlive()) { 1259 CondItem c; 1260 if (cond != null) { 1261 code.statBegin(cond.pos); 1262 Assert.check(code.isStatementStart()); 1263 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1264 } else { 1265 c = items.makeCondItem(goto_); 1266 } 1267 code.resolve(c.jumpTrue(), startpc); 1268 Assert.check(code.isStatementStart()); 1269 code.resolve(c.falseJumps); 1270 } 1271 } 1272 code.resolve(loopEnv.info.exit); 1273 } 1274 1275 public void visitForeachLoop(JCEnhancedForLoop tree) { 1276 throw new AssertionError(); // should have been removed by Lower. 1277 } 1278 1279 public void visitLabelled(JCLabeledStatement tree) { 1280 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1281 genStat(tree.body, localEnv, CRT_STATEMENT); 1282 code.resolve(localEnv.info.exit); 1283 } 1284 1285 public void visitSwitch(JCSwitch tree) { 1286 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch); 1287 } 1288 1289 @Override 1290 public void visitSwitchExpression(JCSwitchExpression tree) { 1291 code.resolvePending(); 1292 boolean prevInCondSwitchExpression = inCondSwitchExpression; 1293 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields; 1294 try { 1295 inCondSwitchExpression = false; 1296 doHandleSwitchExpression(tree); 1297 } finally { 1298 inCondSwitchExpression = prevInCondSwitchExpression; 1299 code.currentUnsetFields = prevCodeUnsetFields; 1300 } 1301 result = items.makeStackItem(pt); 1302 } 1303 1304 private void doHandleSwitchExpression(JCSwitchExpression tree) { 1305 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression; 1306 LocalItem prevSwitchResult = switchResult; 1307 int limit = code.nextreg; 1308 try { 1309 stackBeforeSwitchExpression = List.nil(); 1310 switchResult = null; 1311 if (hasTry(tree)) { 1312 //if the switch expression contains try-catch, the catch handlers need to have 1313 //an empty stack. So stash whole stack to local variables, and restore it before 1314 //breaks: 1315 while (code.state.stacksize > 0) { 1316 Type type = code.state.peek(); 1317 Name varName = names.fromString(target.syntheticNameChar() + 1318 "stack" + 1319 target.syntheticNameChar() + 1320 tree.pos + 1321 target.syntheticNameChar() + 1322 code.state.stacksize); 1323 VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type, 1324 this.env.enclMethod.sym); 1325 LocalItem item = items.new LocalItem(type, code.newLocal(var)); 1326 stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item); 1327 item.store(); 1328 } 1329 switchResult = makeTemp(tree.type); 1330 } 1331 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 1332 try { 1333 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch); 1334 } finally { 1335 code.setLetExprStackPos(prevLetExprStart); 1336 } 1337 } finally { 1338 stackBeforeSwitchExpression = prevStackBeforeSwitchExpression; 1339 switchResult = prevSwitchResult; 1340 code.endScopes(limit); 1341 } 1342 } 1343 //where: 1344 private boolean hasTry(JCSwitchExpression tree) { 1345 class HasTryScanner extends TreeScanner { 1346 private boolean hasTry; 1347 1348 @Override 1349 public void visitTry(JCTry tree) { 1350 hasTry = true; 1351 } 1352 1353 @Override 1354 public void visitSynchronized(JCSynchronized tree) { 1355 hasTry = true; 1356 } 1357 1358 @Override 1359 public void visitClassDef(JCClassDecl tree) { 1360 } 1361 1362 @Override 1363 public void visitLambda(JCLambda tree) { 1364 } 1365 }; 1366 1367 HasTryScanner hasTryScanner = new HasTryScanner(); 1368 1369 hasTryScanner.scan(tree); 1370 return hasTryScanner.hasTry; 1371 } 1372 1373 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases, 1374 boolean patternSwitch) { 1375 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields; 1376 try { 1377 handleSwitchHelper(swtch, selector, cases, patternSwitch); 1378 } finally { 1379 code.currentUnsetFields = prevCodeUnsetFields; 1380 } 1381 } 1382 1383 void handleSwitchHelper(JCTree swtch, JCExpression selector, List<JCCase> cases, 1384 boolean patternSwitch) { 1385 int limit = code.nextreg; 1386 Assert.check(!selector.type.hasTag(CLASS)); 1387 int switchStart = patternSwitch ? code.entryPoint() : -1; 1388 int startpcCrt = genCrt ? code.curCP() : 0; 1389 Assert.check(code.isStatementStart()); 1390 Item sel = genExpr(selector, syms.intType); 1391 if (cases.isEmpty()) { 1392 // We are seeing: switch <sel> {} 1393 sel.load().drop(); 1394 if (genCrt) 1395 code.crt.put(TreeInfo.skipParens(selector), 1396 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1397 } else { 1398 // We are seeing a nonempty switch. 1399 sel.load(); 1400 if (genCrt) 1401 code.crt.put(TreeInfo.skipParens(selector), 1402 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1403 Env<GenContext> switchEnv = env.dup(swtch, new GenContext()); 1404 switchEnv.info.isSwitch = true; 1405 1406 // Compute number of labels and minimum and maximum label values. 1407 // For each case, store its label in an array. 1408 int lo = Integer.MAX_VALUE; // minimum label. 1409 int hi = Integer.MIN_VALUE; // maximum label. 1410 int nlabels = 0; // number of labels. 1411 1412 int[] labels = new int[cases.length()]; // the label array. 1413 int defaultIndex = -1; // the index of the default clause. 1414 1415 List<JCCase> l = cases; 1416 for (int i = 0; i < labels.length; i++) { 1417 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) { 1418 Assert.check(l.head.labels.size() == 1); 1419 int val = ((Number) constLabel.expr.type.constValue()).intValue(); 1420 labels[i] = val; 1421 if (val < lo) lo = val; 1422 if (hi < val) hi = val; 1423 nlabels++; 1424 } else { 1425 Assert.check(defaultIndex == -1); 1426 defaultIndex = i; 1427 } 1428 l = l.tail; 1429 } 1430 1431 // Determine whether to issue a tableswitch or a lookupswitch 1432 // instruction. 1433 long table_space_cost = 4 + ((long) hi - lo + 1); // words 1434 long table_time_cost = 3; // comparisons 1435 long lookup_space_cost = 3 + 2 * (long) nlabels; 1436 long lookup_time_cost = nlabels; 1437 int opcode = 1438 nlabels > 0 && 1439 table_space_cost + 3 * table_time_cost <= 1440 lookup_space_cost + 3 * lookup_time_cost 1441 ? 1442 tableswitch : lookupswitch; 1443 1444 int startpc = code.curCP(); // the position of the selector operation 1445 code.emitop0(opcode); 1446 code.align(4); 1447 int tableBase = code.curCP(); // the start of the jump table 1448 int[] offsets = null; // a table of offsets for a lookupswitch 1449 code.emit4(-1); // leave space for default offset 1450 if (opcode == tableswitch) { 1451 code.emit4(lo); // minimum label 1452 code.emit4(hi); // maximum label 1453 for (long i = lo; i <= hi; i++) { // leave space for jump table 1454 code.emit4(-1); 1455 } 1456 } else { 1457 code.emit4(nlabels); // number of labels 1458 for (int i = 0; i < nlabels; i++) { 1459 code.emit4(-1); code.emit4(-1); // leave space for lookup table 1460 } 1461 offsets = new int[labels.length]; 1462 } 1463 Code.State stateSwitch = code.state.dup(); 1464 code.markDead(); 1465 1466 // For each case do: 1467 l = cases; 1468 for (int i = 0; i < labels.length; i++) { 1469 JCCase c = l.head; 1470 l = l.tail; 1471 1472 int pc = code.entryPoint(stateSwitch); 1473 // Insert offset directly into code or else into the 1474 // offsets table. 1475 if (i != defaultIndex) { 1476 if (opcode == tableswitch) { 1477 code.put4( 1478 tableBase + 4 * (labels[i] - lo + 3), 1479 pc - startpc); 1480 } else { 1481 offsets[i] = pc - startpc; 1482 } 1483 } else { 1484 code.put4(tableBase, pc - startpc); 1485 } 1486 1487 // Generate code for the statements in this case. 1488 genStats(c.stats, switchEnv, CRT_FLOW_TARGET); 1489 } 1490 1491 if (switchEnv.info.cont != null) { 1492 Assert.check(patternSwitch); 1493 code.resolve(switchEnv.info.cont, switchStart); 1494 } 1495 1496 // Resolve all breaks. 1497 code.resolve(switchEnv.info.exit); 1498 1499 // If we have not set the default offset, we do so now. 1500 if (code.get4(tableBase) == -1) { 1501 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1502 } 1503 1504 if (opcode == tableswitch) { 1505 // Let any unfilled slots point to the default case. 1506 int defaultOffset = code.get4(tableBase); 1507 for (long i = lo; i <= hi; i++) { 1508 int t = (int)(tableBase + 4 * (i - lo + 3)); 1509 if (code.get4(t) == -1) 1510 code.put4(t, defaultOffset); 1511 } 1512 } else { 1513 // Sort non-default offsets and copy into lookup table. 1514 if (defaultIndex >= 0) 1515 for (int i = defaultIndex; i < labels.length - 1; i++) { 1516 labels[i] = labels[i+1]; 1517 offsets[i] = offsets[i+1]; 1518 } 1519 if (nlabels > 0) 1520 qsort2(labels, offsets, 0, nlabels - 1); 1521 for (int i = 0; i < nlabels; i++) { 1522 int caseidx = tableBase + 8 * (i + 1); 1523 code.put4(caseidx, labels[i]); 1524 code.put4(caseidx + 4, offsets[i]); 1525 } 1526 } 1527 1528 if (swtch instanceof JCSwitchExpression) { 1529 // Emit line position for the end of a switch expression 1530 code.statBegin(TreeInfo.endPos(swtch)); 1531 } 1532 } 1533 code.endScopes(limit); 1534 } 1535 //where 1536 /** Sort (int) arrays of keys and values 1537 */ 1538 static void qsort2(int[] keys, int[] values, int lo, int hi) { 1539 int i = lo; 1540 int j = hi; 1541 int pivot = keys[(i+j)/2]; 1542 do { 1543 while (keys[i] < pivot) i++; 1544 while (pivot < keys[j]) j--; 1545 if (i <= j) { 1546 int temp1 = keys[i]; 1547 keys[i] = keys[j]; 1548 keys[j] = temp1; 1549 int temp2 = values[i]; 1550 values[i] = values[j]; 1551 values[j] = temp2; 1552 i++; 1553 j--; 1554 } 1555 } while (i <= j); 1556 if (lo < j) qsort2(keys, values, lo, j); 1557 if (i < hi) qsort2(keys, values, i, hi); 1558 } 1559 1560 public void visitSynchronized(JCSynchronized tree) { 1561 int limit = code.nextreg; 1562 // Generate code to evaluate lock and save in temporary variable. 1563 final LocalItem lockVar = makeTemp(syms.objectType); 1564 Assert.check(code.isStatementStart()); 1565 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1566 lockVar.store(); 1567 1568 // Generate code to enter monitor. 1569 code.emitop0(monitorenter); 1570 code.state.lock(lockVar.reg); 1571 1572 // Generate code for a try statement with given body, no catch clauses 1573 // in a new environment with the "exit-monitor" operation as finalizer. 1574 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1575 syncEnv.info.finalize = new GenFinalizer() { 1576 void gen() { 1577 genLast(); 1578 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1579 syncEnv.info.gaps.append(code.curCP()); 1580 } 1581 void genLast() { 1582 if (code.isAlive()) { 1583 lockVar.load(); 1584 code.emitop0(monitorexit); 1585 code.state.unlock(lockVar.reg); 1586 } 1587 } 1588 }; 1589 syncEnv.info.gaps = new ListBuffer<>(); 1590 genTry(tree.body, List.nil(), syncEnv); 1591 code.endScopes(limit); 1592 } 1593 1594 public void visitTry(final JCTry tree) { 1595 // Generate code for a try statement with given body and catch clauses, 1596 // in a new environment which calls the finally block if there is one. 1597 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1598 final Env<GenContext> oldEnv = env; 1599 tryEnv.info.finalize = new GenFinalizer() { 1600 void gen() { 1601 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1602 tryEnv.info.gaps.append(code.curCP()); 1603 genLast(); 1604 } 1605 void genLast() { 1606 if (tree.finalizer != null) 1607 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1608 } 1609 boolean hasFinalizer() { 1610 return tree.finalizer != null; 1611 } 1612 1613 @Override 1614 void afterBody() { 1615 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) { 1616 //for body-only finally, remove the GenFinalizer after try body 1617 //so that the finally is not generated to catch bodies: 1618 tryEnv.info.finalize = null; 1619 } 1620 } 1621 1622 }; 1623 tryEnv.info.gaps = new ListBuffer<>(); 1624 genTry(tree.body, tree.catchers, tryEnv); 1625 } 1626 //where 1627 /** Generate code for a try or synchronized statement 1628 * @param body The body of the try or synchronized statement. 1629 * @param catchers The list of catch clauses. 1630 * @param env The current environment of the body. 1631 */ 1632 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1633 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields; 1634 try { 1635 genTryHelper(body, catchers, env); 1636 } finally { 1637 code.currentUnsetFields = prevCodeUnsetFields; 1638 } 1639 } 1640 1641 void genTryHelper(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1642 int limit = code.nextreg; 1643 int startpc = code.curCP(); 1644 Code.State stateTry = code.state.dup(); 1645 genStat(body, env, CRT_BLOCK); 1646 int endpc = code.curCP(); 1647 List<Integer> gaps = env.info.gaps.toList(); 1648 code.statBegin(TreeInfo.endPos(body)); 1649 genFinalizer(env); 1650 code.statBegin(TreeInfo.endPos(env.tree)); 1651 Chain exitChain; 1652 boolean actualTry = env.tree.hasTag(TRY); 1653 if (startpc == endpc && actualTry) { 1654 exitChain = code.branch(dontgoto); 1655 } else { 1656 exitChain = code.branch(goto_); 1657 } 1658 endFinalizerGap(env); 1659 env.info.finalize.afterBody(); 1660 boolean hasFinalizer = 1661 env.info.finalize != null && 1662 env.info.finalize.hasFinalizer(); 1663 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) { 1664 // start off with exception on stack 1665 code.entryPoint(stateTry, l.head.param.sym.type); 1666 genCatch(l.head, env, startpc, endpc, gaps); 1667 genFinalizer(env); 1668 if (hasFinalizer || l.tail.nonEmpty()) { 1669 code.statBegin(TreeInfo.endPos(env.tree)); 1670 exitChain = Code.mergeChains(exitChain, 1671 code.branch(goto_)); 1672 } 1673 endFinalizerGap(env); 1674 } 1675 if (hasFinalizer && (startpc != endpc || !actualTry)) { 1676 // Create a new register segment to avoid allocating 1677 // the same variables in finalizers and other statements. 1678 code.newRegSegment(); 1679 1680 // Add a catch-all clause. 1681 1682 // start off with exception on stack 1683 int catchallpc = code.entryPoint(stateTry, syms.throwableType); 1684 1685 // Register all exception ranges for catch all clause. 1686 // The range of the catch all clause is from the beginning 1687 // of the try or synchronized block until the present 1688 // code pointer excluding all gaps in the current 1689 // environment's GenContext. 1690 int startseg = startpc; 1691 while (env.info.gaps.nonEmpty()) { 1692 int endseg = env.info.gaps.next().intValue(); 1693 registerCatch(body.pos(), startseg, endseg, 1694 catchallpc, 0); 1695 startseg = env.info.gaps.next().intValue(); 1696 } 1697 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1698 code.markStatBegin(); 1699 1700 Item excVar = makeTemp(syms.throwableType); 1701 excVar.store(); 1702 genFinalizer(env); 1703 code.resolvePending(); 1704 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS)); 1705 code.markStatBegin(); 1706 1707 excVar.load(); 1708 registerCatch(body.pos(), startseg, 1709 env.info.gaps.next().intValue(), 1710 catchallpc, 0); 1711 code.emitop0(athrow); 1712 code.markDead(); 1713 1714 // If there are jsr's to this finalizer, ... 1715 if (env.info.cont != null) { 1716 // Resolve all jsr's. 1717 code.resolve(env.info.cont); 1718 1719 // Mark statement line number 1720 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1721 code.markStatBegin(); 1722 1723 // Save return address. 1724 LocalItem retVar = makeTemp(syms.throwableType); 1725 retVar.store(); 1726 1727 // Generate finalizer code. 1728 env.info.finalize.genLast(); 1729 1730 // Return. 1731 code.emitop1w(ret, retVar.reg); 1732 code.markDead(); 1733 } 1734 } 1735 // Resolve all breaks. 1736 code.resolve(exitChain); 1737 1738 code.endScopes(limit); 1739 } 1740 1741 /** Generate code for a catch clause. 1742 * @param tree The catch clause. 1743 * @param env The environment current in the enclosing try. 1744 * @param startpc Start pc of try-block. 1745 * @param endpc End pc of try-block. 1746 */ 1747 void genCatch(JCCatch tree, 1748 Env<GenContext> env, 1749 int startpc, int endpc, 1750 List<Integer> gaps) { 1751 if (startpc != endpc) { 1752 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs 1753 = catchTypesWithAnnotations(tree); 1754 while (gaps.nonEmpty()) { 1755 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1756 JCExpression subCatch = subCatch1.snd; 1757 int catchType = makeRef(tree.pos(), subCatch.type); 1758 int end = gaps.head.intValue(); 1759 registerCatch(tree.pos(), 1760 startpc, end, code.curCP(), 1761 catchType); 1762 for (Attribute.TypeCompound tc : subCatch1.fst) { 1763 tc.position.setCatchInfo(catchType, startpc); 1764 } 1765 } 1766 gaps = gaps.tail; 1767 startpc = gaps.head.intValue(); 1768 gaps = gaps.tail; 1769 } 1770 if (startpc < endpc) { 1771 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1772 JCExpression subCatch = subCatch1.snd; 1773 int catchType = makeRef(tree.pos(), subCatch.type); 1774 registerCatch(tree.pos(), 1775 startpc, endpc, code.curCP(), 1776 catchType); 1777 for (Attribute.TypeCompound tc : subCatch1.fst) { 1778 tc.position.setCatchInfo(catchType, startpc); 1779 } 1780 } 1781 } 1782 genCatchBlock(tree, env); 1783 } 1784 } 1785 void genPatternMatchingCatch(JCCatch tree, 1786 Env<GenContext> env, 1787 List<int[]> ranges) { 1788 for (int[] range : ranges) { 1789 JCExpression subCatch = tree.param.vartype; 1790 int catchType = makeRef(tree.pos(), subCatch.type); 1791 registerCatch(tree.pos(), 1792 range[0], range[1], code.curCP(), 1793 catchType); 1794 } 1795 genCatchBlock(tree, env); 1796 } 1797 void genCatchBlock(JCCatch tree, Env<GenContext> env) { 1798 VarSymbol exparam = tree.param.sym; 1799 code.statBegin(tree.pos); 1800 code.markStatBegin(); 1801 int limit = code.nextreg; 1802 code.newLocal(exparam); 1803 items.makeLocalItem(exparam).store(); 1804 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1805 genStat(tree.body, env, CRT_BLOCK); 1806 code.endScopes(limit); 1807 code.statBegin(TreeInfo.endPos(tree.body)); 1808 } 1809 // where 1810 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) { 1811 return TreeInfo.isMultiCatch(tree) ? 1812 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) : 1813 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype)); 1814 } 1815 // where 1816 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) { 1817 List<JCExpression> alts = tree.alternatives; 1818 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head)); 1819 alts = alts.tail; 1820 1821 while(alts != null && alts.head != null) { 1822 JCExpression alt = alts.head; 1823 if (alt instanceof JCAnnotatedType annotatedType) { 1824 res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt)); 1825 } else { 1826 res = res.prepend(new Pair<>(List.nil(), alt)); 1827 } 1828 alts = alts.tail; 1829 } 1830 return res.reverse(); 1831 } 1832 1833 /** Register a catch clause in the "Exceptions" code-attribute. 1834 */ 1835 void registerCatch(DiagnosticPosition pos, 1836 int startpc, int endpc, 1837 int handler_pc, int catch_type) { 1838 char startpc1 = (char)startpc; 1839 char endpc1 = (char)endpc; 1840 char handler_pc1 = (char)handler_pc; 1841 if (startpc1 == startpc && 1842 endpc1 == endpc && 1843 handler_pc1 == handler_pc) { 1844 code.addCatch(startpc1, endpc1, handler_pc1, 1845 (char)catch_type); 1846 } else { 1847 log.error(pos, Errors.LimitCodeTooLargeForTryStmt); 1848 nerrs++; 1849 } 1850 } 1851 1852 public void visitIf(JCIf tree) { 1853 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields; 1854 try { 1855 visitIfHelper(tree); 1856 } finally { 1857 code.currentUnsetFields = prevCodeUnsetFields; 1858 } 1859 } 1860 1861 public void visitIfHelper(JCIf tree) { 1862 int limit = code.nextreg; 1863 Chain thenExit = null; 1864 Assert.check(code.isStatementStart()); 1865 CondItem c = genCond(TreeInfo.skipParens(tree.cond), 1866 CRT_FLOW_CONTROLLER); 1867 Chain elseChain = c.jumpFalse(); 1868 Assert.check(code.isStatementStart()); 1869 if (!c.isFalse()) { 1870 code.resolve(c.trueJumps); 1871 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); 1872 thenExit = code.branch(goto_); 1873 } 1874 if (elseChain != null) { 1875 code.resolve(elseChain); 1876 if (tree.elsepart != null) { 1877 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); 1878 } 1879 } 1880 code.resolve(thenExit); 1881 code.endScopes(limit); 1882 Assert.check(code.isStatementStart()); 1883 } 1884 1885 public void visitExec(JCExpressionStatement tree) { 1886 // Optimize x++ to ++x and x-- to --x. 1887 JCExpression e = tree.expr; 1888 switch (e.getTag()) { 1889 case POSTINC: 1890 ((JCUnary) e).setTag(PREINC); 1891 break; 1892 case POSTDEC: 1893 ((JCUnary) e).setTag(PREDEC); 1894 break; 1895 } 1896 Assert.check(code.isStatementStart()); 1897 genExpr(tree.expr, tree.expr.type).drop(); 1898 Assert.check(code.isStatementStart()); 1899 } 1900 1901 public void visitBreak(JCBreak tree) { 1902 Assert.check(code.isStatementStart()); 1903 final Env<GenContext> targetEnv = unwindBreak(tree.target); 1904 targetEnv.info.addExit(code.branch(goto_)); 1905 endFinalizerGaps(env, targetEnv); 1906 } 1907 1908 public void visitYield(JCYield tree) { 1909 Assert.check(code.isStatementStart()); 1910 final Env<GenContext> targetEnv; 1911 if (inCondSwitchExpression) { 1912 CondItem value = genCond(tree.value, CRT_FLOW_TARGET); 1913 Chain falseJumps = value.jumpFalse(); 1914 1915 code.resolve(value.trueJumps); 1916 Env<GenContext> localEnv = unwindBreak(tree.target); 1917 reloadStackBeforeSwitchExpr(); 1918 Chain trueJumps = code.branch(goto_); 1919 1920 endFinalizerGaps(env, localEnv); 1921 1922 code.resolve(falseJumps); 1923 targetEnv = unwindBreak(tree.target); 1924 reloadStackBeforeSwitchExpr(); 1925 falseJumps = code.branch(goto_); 1926 1927 if (switchExpressionTrueChain == null) { 1928 switchExpressionTrueChain = trueJumps; 1929 } else { 1930 switchExpressionTrueChain = 1931 Code.mergeChains(switchExpressionTrueChain, trueJumps); 1932 } 1933 if (switchExpressionFalseChain == null) { 1934 switchExpressionFalseChain = falseJumps; 1935 } else { 1936 switchExpressionFalseChain = 1937 Code.mergeChains(switchExpressionFalseChain, falseJumps); 1938 } 1939 } else { 1940 genExpr(tree.value, pt).load(); 1941 if (switchResult != null) 1942 switchResult.store(); 1943 1944 targetEnv = unwindBreak(tree.target); 1945 1946 if (code.isAlive()) { 1947 reloadStackBeforeSwitchExpr(); 1948 if (switchResult != null) 1949 switchResult.load(); 1950 1951 targetEnv.info.addExit(code.branch(goto_)); 1952 code.markDead(); 1953 } 1954 } 1955 endFinalizerGaps(env, targetEnv); 1956 } 1957 //where: 1958 /** As side-effect, might mark code as dead disabling any further emission. 1959 */ 1960 private Env<GenContext> unwindBreak(JCTree target) { 1961 int tmpPos = code.pendingStatPos; 1962 Env<GenContext> targetEnv = unwind(target, env); 1963 code.pendingStatPos = tmpPos; 1964 return targetEnv; 1965 } 1966 1967 private void reloadStackBeforeSwitchExpr() { 1968 for (LocalItem li : stackBeforeSwitchExpression) 1969 li.load(); 1970 } 1971 1972 public void visitContinue(JCContinue tree) { 1973 int tmpPos = code.pendingStatPos; 1974 Env<GenContext> targetEnv = unwind(tree.target, env); 1975 code.pendingStatPos = tmpPos; 1976 Assert.check(code.isStatementStart()); 1977 targetEnv.info.addCont(code.branch(goto_)); 1978 endFinalizerGaps(env, targetEnv); 1979 } 1980 1981 public void visitReturn(JCReturn tree) { 1982 int limit = code.nextreg; 1983 final Env<GenContext> targetEnv; 1984 1985 /* Save and then restore the location of the return in case a finally 1986 * is expanded (with unwind()) in the middle of our bytecodes. 1987 */ 1988 int tmpPos = code.pendingStatPos; 1989 if (tree.expr != null) { 1990 Assert.check(code.isStatementStart()); 1991 Item r = genExpr(tree.expr, pt).load(); 1992 if (hasFinally(env.enclMethod, env)) { 1993 r = makeTemp(pt); 1994 r.store(); 1995 } 1996 targetEnv = unwind(env.enclMethod, env); 1997 code.pendingStatPos = tmpPos; 1998 r.load(); 1999 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 2000 } else { 2001 targetEnv = unwind(env.enclMethod, env); 2002 code.pendingStatPos = tmpPos; 2003 code.emitop0(return_); 2004 } 2005 endFinalizerGaps(env, targetEnv); 2006 code.endScopes(limit); 2007 } 2008 2009 public void visitThrow(JCThrow tree) { 2010 Assert.check(code.isStatementStart()); 2011 genExpr(tree.expr, tree.expr.type).load(); 2012 code.emitop0(athrow); 2013 Assert.check(code.isStatementStart()); 2014 } 2015 2016 /* ************************************************************************ 2017 * Visitor methods for expressions 2018 *************************************************************************/ 2019 2020 public void visitApply(JCMethodInvocation tree) { 2021 setTypeAnnotationPositions(tree.pos); 2022 // Generate code for method. 2023 Item m = genExpr(tree.meth, methodType); 2024 // Generate code for all arguments, where the expected types are 2025 // the parameters of the method's external type (that is, any implicit 2026 // outer instance of a super(...) call appears as first parameter). 2027 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 2028 genArgs(tree.args, 2029 msym.externalType(types).getParameterTypes()); 2030 if (!msym.isDynamic()) { 2031 code.statBegin(tree.pos); 2032 } 2033 if (patternMatchingCatchConfiguration.invocations().contains(tree)) { 2034 int start = code.curCP(); 2035 result = m.invoke(); 2036 patternMatchingCatchConfiguration.ranges().add(new int[] {start, code.curCP()}); 2037 } else { 2038 if (msym.isConstructor() && TreeInfo.isConstructorCall(tree)) { 2039 //if this is a this(...) or super(...) call, there is a pending 2040 //"uninitialized this" before this call. One catch handler cannot 2041 //handle exceptions that may come from places with "uninitialized this" 2042 //and (initialized) this, hence generate one set of handlers here 2043 //for the "uninitialized this" case, and another set of handlers 2044 //will be generated at the end of the method for the initialized this, 2045 //if needed: 2046 generatePatternMatchingCatch(env); 2047 result = m.invoke(); 2048 patternMatchingCatchConfiguration = 2049 patternMatchingCatchConfiguration.restart(code.state.dup()); 2050 } else { 2051 result = m.invoke(); 2052 } 2053 } 2054 } 2055 2056 public void visitConditional(JCConditional tree) { 2057 Chain thenExit = null; 2058 code.statBegin(tree.cond.pos); 2059 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 2060 Chain elseChain = c.jumpFalse(); 2061 if (!c.isFalse()) { 2062 code.resolve(c.trueJumps); 2063 int startpc = genCrt ? code.curCP() : 0; 2064 code.statBegin(tree.truepart.pos); 2065 genExpr(tree.truepart, pt).load(); 2066 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 2067 startpc, code.curCP()); 2068 thenExit = code.branch(goto_); 2069 } 2070 if (elseChain != null) { 2071 code.resolve(elseChain); 2072 int startpc = genCrt ? code.curCP() : 0; 2073 code.statBegin(tree.falsepart.pos); 2074 genExpr(tree.falsepart, pt).load(); 2075 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 2076 startpc, code.curCP()); 2077 } 2078 code.resolve(thenExit); 2079 result = items.makeStackItem(pt); 2080 } 2081 2082 private void setTypeAnnotationPositions(int treePos) { 2083 MethodSymbol meth = code.meth; 2084 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 2085 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 2086 2087 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 2088 if (ta.hasUnknownPosition()) 2089 ta.tryFixPosition(); 2090 2091 if (ta.position.matchesPos(treePos)) 2092 ta.position.updatePosOffset(code.cp); 2093 } 2094 2095 if (!initOrClinit) 2096 return; 2097 2098 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 2099 if (ta.hasUnknownPosition()) 2100 ta.tryFixPosition(); 2101 2102 if (ta.position.matchesPos(treePos)) 2103 ta.position.updatePosOffset(code.cp); 2104 } 2105 2106 ClassSymbol clazz = meth.enclClass(); 2107 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 2108 if (!s.getKind().isField()) 2109 continue; 2110 2111 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 2112 if (ta.hasUnknownPosition()) 2113 ta.tryFixPosition(); 2114 2115 if (ta.position.matchesPos(treePos)) 2116 ta.position.updatePosOffset(code.cp); 2117 } 2118 } 2119 } 2120 2121 public void visitNewClass(JCNewClass tree) { 2122 // Enclosing instances or anonymous classes should have been eliminated 2123 // by now. 2124 Assert.check(tree.encl == null && tree.def == null); 2125 setTypeAnnotationPositions(tree.pos); 2126 2127 code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass); 2128 code.emitop0(dup); 2129 2130 // Generate code for all arguments, where the expected types are 2131 // the parameters of the constructor's external type (that is, 2132 // any implicit outer instance appears as first parameter). 2133 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 2134 2135 items.makeMemberItem(tree.constructor, true).invoke(); 2136 result = items.makeStackItem(tree.type); 2137 } 2138 2139 public void visitNewArray(JCNewArray tree) { 2140 setTypeAnnotationPositions(tree.pos); 2141 2142 if (tree.elems != null) { 2143 Type elemtype = types.elemtype(tree.type); 2144 loadIntConst(tree.elems.length()); 2145 Item arr = makeNewArray(tree.pos(), tree.type, 1); 2146 int i = 0; 2147 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 2148 arr.duplicate(); 2149 loadIntConst(i); 2150 i++; 2151 genExpr(l.head, elemtype).load(); 2152 items.makeIndexedItem(elemtype).store(); 2153 } 2154 result = arr; 2155 } else { 2156 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2157 genExpr(l.head, syms.intType).load(); 2158 } 2159 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 2160 } 2161 } 2162 //where 2163 /** Generate code to create an array with given element type and number 2164 * of dimensions. 2165 */ 2166 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 2167 Type elemtype = types.elemtype(type); 2168 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 2169 log.error(pos, Errors.LimitDimensions); 2170 nerrs++; 2171 } 2172 int elemcode = Code.arraycode(elemtype); 2173 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { 2174 code.emitAnewarray(makeRef(pos, elemtype), type); 2175 } else if (elemcode == 1) { 2176 code.emitMultianewarray(ndims, makeRef(pos, type), type); 2177 } else { 2178 code.emitNewarray(elemcode, type); 2179 } 2180 return items.makeStackItem(type); 2181 } 2182 2183 public void visitParens(JCParens tree) { 2184 result = genExpr(tree.expr, tree.expr.type); 2185 } 2186 2187 public void visitAssign(JCAssign tree) { 2188 Item l = genExpr(tree.lhs, tree.lhs.type); 2189 genExpr(tree.rhs, tree.lhs.type).load(); 2190 Set<VarSymbol> tmpUnsetSymbols = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree); 2191 code.currentUnsetFields = tmpUnsetSymbols != null ? tmpUnsetSymbols : code.currentUnsetFields; 2192 if (tree.rhs.type.hasTag(BOT)) { 2193 /* This is just a case of widening reference conversion that per 5.1.5 simply calls 2194 for "regarding a reference as having some other type in a manner that can be proved 2195 correct at compile time." 2196 */ 2197 code.state.forceStackTop(tree.lhs.type); 2198 } 2199 result = items.makeAssignItem(l); 2200 } 2201 2202 public void visitAssignop(JCAssignOp tree) { 2203 OperatorSymbol operator = tree.operator; 2204 Item l; 2205 if (operator.opcode == string_add) { 2206 l = concat.makeConcat(tree); 2207 } else { 2208 // Generate code for first expression 2209 l = genExpr(tree.lhs, tree.lhs.type); 2210 2211 // If we have an increment of -32768 to +32767 of a local 2212 // int variable we can use an incr instruction instead of 2213 // proceeding further. 2214 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 2215 l instanceof LocalItem localItem && 2216 tree.lhs.type.getTag().isSubRangeOf(INT) && 2217 tree.rhs.type.getTag().isSubRangeOf(INT) && 2218 tree.rhs.type.constValue() != null) { 2219 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 2220 if (tree.hasTag(MINUS_ASG)) ival = -ival; 2221 localItem.incr(ival); 2222 result = l; 2223 return; 2224 } 2225 // Otherwise, duplicate expression, load one copy 2226 // and complete binary operation. 2227 l.duplicate(); 2228 l.coerce(operator.type.getParameterTypes().head).load(); 2229 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 2230 } 2231 result = items.makeAssignItem(l); 2232 } 2233 2234 public void visitUnary(JCUnary tree) { 2235 OperatorSymbol operator = tree.operator; 2236 if (tree.hasTag(NOT)) { 2237 CondItem od = genCond(tree.arg, false); 2238 result = od.negate(); 2239 } else { 2240 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 2241 switch (tree.getTag()) { 2242 case POS: 2243 result = od.load(); 2244 break; 2245 case NEG: 2246 result = od.load(); 2247 code.emitop0(operator.opcode); 2248 break; 2249 case COMPL: 2250 result = od.load(); 2251 emitMinusOne(od.typecode); 2252 code.emitop0(operator.opcode); 2253 break; 2254 case PREINC: case PREDEC: 2255 od.duplicate(); 2256 if (od instanceof LocalItem localItem && 2257 (operator.opcode == iadd || operator.opcode == isub)) { 2258 localItem.incr(tree.hasTag(PREINC) ? 1 : -1); 2259 result = od; 2260 } else { 2261 od.load(); 2262 code.emitop0(one(od.typecode)); 2263 code.emitop0(operator.opcode); 2264 // Perform narrowing primitive conversion if byte, 2265 // char, or short. Fix for 4304655. 2266 if (od.typecode != INTcode && 2267 Code.truncate(od.typecode) == INTcode) 2268 code.emitop0(int2byte + od.typecode - BYTEcode); 2269 result = items.makeAssignItem(od); 2270 } 2271 break; 2272 case POSTINC: case POSTDEC: 2273 od.duplicate(); 2274 if (od instanceof LocalItem localItem && 2275 (operator.opcode == iadd || operator.opcode == isub)) { 2276 Item res = od.load(); 2277 localItem.incr(tree.hasTag(POSTINC) ? 1 : -1); 2278 result = res; 2279 } else { 2280 Item res = od.load(); 2281 od.stash(od.typecode); 2282 code.emitop0(one(od.typecode)); 2283 code.emitop0(operator.opcode); 2284 // Perform narrowing primitive conversion if byte, 2285 // char, or short. Fix for 4304655. 2286 if (od.typecode != INTcode && 2287 Code.truncate(od.typecode) == INTcode) 2288 code.emitop0(int2byte + od.typecode - BYTEcode); 2289 od.store(); 2290 result = res; 2291 } 2292 break; 2293 case NULLCHK: 2294 result = od.load(); 2295 code.emitop0(dup); 2296 genNullCheck(tree); 2297 break; 2298 default: 2299 Assert.error(); 2300 } 2301 } 2302 } 2303 2304 /** Generate a null check from the object value at stack top. */ 2305 private void genNullCheck(JCTree tree) { 2306 code.statBegin(tree.pos); 2307 callMethod(tree.pos(), syms.objectsType, names.requireNonNull, 2308 List.of(syms.objectType), true); 2309 code.emitop0(pop); 2310 } 2311 2312 public void visitBinary(JCBinary tree) { 2313 OperatorSymbol operator = tree.operator; 2314 if (operator.opcode == string_add) { 2315 result = concat.makeConcat(tree); 2316 } else if (tree.hasTag(AND)) { 2317 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2318 if (!lcond.isFalse()) { 2319 Chain falseJumps = lcond.jumpFalse(); 2320 code.resolve(lcond.trueJumps); 2321 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2322 result = items. 2323 makeCondItem(rcond.opcode, 2324 rcond.trueJumps, 2325 Code.mergeChains(falseJumps, 2326 rcond.falseJumps)); 2327 } else { 2328 result = lcond; 2329 } 2330 } else if (tree.hasTag(OR)) { 2331 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2332 if (!lcond.isTrue()) { 2333 Chain trueJumps = lcond.jumpTrue(); 2334 code.resolve(lcond.falseJumps); 2335 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2336 result = items. 2337 makeCondItem(rcond.opcode, 2338 Code.mergeChains(trueJumps, rcond.trueJumps), 2339 rcond.falseJumps); 2340 } else { 2341 result = lcond; 2342 } 2343 } else { 2344 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2345 od.load(); 2346 result = completeBinop(tree.lhs, tree.rhs, operator); 2347 } 2348 } 2349 2350 2351 /** Complete generating code for operation, with left operand 2352 * already on stack. 2353 * @param lhs The tree representing the left operand. 2354 * @param rhs The tree representing the right operand. 2355 * @param operator The operator symbol. 2356 */ 2357 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2358 MethodType optype = (MethodType)operator.type; 2359 int opcode = operator.opcode; 2360 if (opcode >= if_icmpeq && opcode <= if_icmple && 2361 rhs.type.constValue() instanceof Number number && 2362 number.intValue() == 0) { 2363 opcode = opcode + (ifeq - if_icmpeq); 2364 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2365 TreeInfo.isNull(rhs)) { 2366 opcode = opcode + (if_acmp_null - if_acmpeq); 2367 } else { 2368 // The expected type of the right operand is 2369 // the second parameter type of the operator, except for 2370 // shifts with long shiftcount, where we convert the opcode 2371 // to a short shift and the expected type to int. 2372 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2373 if (opcode >= ishll && opcode <= lushrl) { 2374 opcode = opcode + (ishl - ishll); 2375 rtype = syms.intType; 2376 } 2377 // Generate code for right operand and load. 2378 genExpr(rhs, rtype).load(); 2379 // If there are two consecutive opcode instructions, 2380 // emit the first now. 2381 if (opcode >= (1 << preShift)) { 2382 code.emitop0(opcode >> preShift); 2383 opcode = opcode & 0xFF; 2384 } 2385 } 2386 if (opcode >= ifeq && opcode <= if_acmpne || 2387 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2388 return items.makeCondItem(opcode); 2389 } else { 2390 code.emitop0(opcode); 2391 return items.makeStackItem(optype.restype); 2392 } 2393 } 2394 2395 public void visitTypeCast(JCTypeCast tree) { 2396 result = genExpr(tree.expr, tree.clazz.type).load(); 2397 setTypeAnnotationPositions(tree.pos); 2398 // Additional code is only needed if we cast to a reference type 2399 // which is not statically a supertype of the expression's type. 2400 // For basic types, the coerce(...) in genExpr(...) will do 2401 // the conversion. 2402 if (!tree.clazz.type.isPrimitive() && 2403 !types.isSameType(tree.expr.type, tree.clazz.type) && 2404 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { 2405 code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass); 2406 } 2407 } 2408 2409 public void visitWildcard(JCWildcard tree) { 2410 throw new AssertionError(this.getClass().getName()); 2411 } 2412 2413 public void visitTypeTest(JCInstanceOf tree) { 2414 genExpr(tree.expr, tree.expr.type).load(); 2415 setTypeAnnotationPositions(tree.pos); 2416 code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type)); 2417 result = items.makeStackItem(syms.booleanType); 2418 } 2419 2420 public void visitIndexed(JCArrayAccess tree) { 2421 genExpr(tree.indexed, tree.indexed.type).load(); 2422 genExpr(tree.index, syms.intType).load(); 2423 result = items.makeIndexedItem(tree.type); 2424 } 2425 2426 public void visitIdent(JCIdent tree) { 2427 Symbol sym = tree.sym; 2428 if (tree.name == names._this || tree.name == names._super) { 2429 Item res = tree.name == names._this 2430 ? items.makeThisItem() 2431 : items.makeSuperItem(); 2432 if (sym.kind == MTH) { 2433 // Generate code to address the constructor. 2434 res.load(); 2435 res = items.makeMemberItem(sym, true); 2436 } 2437 result = res; 2438 } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) { 2439 if (isConstantDynamic(sym)) { 2440 setTypeAnnotationPositions(tree.pos); 2441 } 2442 result = items.makeDynamicItem(sym); 2443 } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) { 2444 result = items.makeLocalItem((VarSymbol)sym); 2445 } else if ((sym.flags() & STATIC) != 0) { 2446 if (!isAccessSuper(env.enclMethod)) 2447 sym = binaryQualifier(sym, env.enclClass.type); 2448 result = items.makeStaticItem(sym); 2449 } else { 2450 items.makeThisItem().load(); 2451 sym = binaryQualifier(sym, env.enclClass.type); 2452 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym)); 2453 } 2454 } 2455 2456 //where 2457 private boolean nonVirtualForPrivateAccess(Symbol sym) { 2458 boolean useVirtual = target.hasVirtualPrivateInvoke() && 2459 !disableVirtualizedPrivateInvoke; 2460 return !useVirtual && ((sym.flags() & PRIVATE) != 0); 2461 } 2462 2463 public void visitSelect(JCFieldAccess tree) { 2464 Symbol sym = tree.sym; 2465 2466 if (tree.name == names._class) { 2467 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type)); 2468 result = items.makeStackItem(pt); 2469 return; 2470 } 2471 2472 Symbol ssym = TreeInfo.symbol(tree.selected); 2473 2474 // Are we selecting via super? 2475 boolean selectSuper = 2476 ssym != null && (ssym.kind == TYP || ssym.name == names._super); 2477 2478 // Are we accessing a member of the superclass in an access method 2479 // resulting from a qualified super? 2480 boolean accessSuper = isAccessSuper(env.enclMethod); 2481 2482 Item base = (selectSuper) 2483 ? items.makeSuperItem() 2484 : genExpr(tree.selected, tree.selected.type); 2485 2486 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { 2487 // We are seeing a variable that is constant but its selecting 2488 // expression is not. 2489 if ((sym.flags() & STATIC) != 0) { 2490 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2491 base = base.load(); 2492 base.drop(); 2493 } else { 2494 base.load(); 2495 genNullCheck(tree.selected); 2496 } 2497 result = items. 2498 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2499 } else { 2500 if (isInvokeDynamic(sym)) { 2501 result = items.makeDynamicItem(sym); 2502 return; 2503 } else { 2504 sym = binaryQualifier(sym, tree.selected.type); 2505 } 2506 if ((sym.flags() & STATIC) != 0) { 2507 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2508 base = base.load(); 2509 base.drop(); 2510 result = items.makeStaticItem(sym); 2511 } else { 2512 base.load(); 2513 if (sym == syms.lengthVar) { 2514 code.emitop0(arraylength); 2515 result = items.makeStackItem(syms.intType); 2516 } else { 2517 result = items. 2518 makeMemberItem(sym, 2519 nonVirtualForPrivateAccess(sym) || 2520 selectSuper || accessSuper); 2521 } 2522 } 2523 } 2524 } 2525 2526 public boolean isInvokeDynamic(Symbol sym) { 2527 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2528 } 2529 2530 public void visitLiteral(JCLiteral tree) { 2531 if (tree.type.hasTag(BOT)) { 2532 code.emitop0(aconst_null); 2533 result = items.makeStackItem(tree.type); 2534 } 2535 else 2536 result = items.makeImmediateItem(tree.type, tree.value); 2537 } 2538 2539 public void visitLetExpr(LetExpr tree) { 2540 code.resolvePending(); 2541 2542 int limit = code.nextreg; 2543 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 2544 try { 2545 genStats(tree.defs, env); 2546 } finally { 2547 code.setLetExprStackPos(prevLetExprStart); 2548 } 2549 result = genExpr(tree.expr, tree.expr.type).load(); 2550 code.endScopes(limit); 2551 } 2552 2553 private void generateReferencesToPrunedTree(ClassSymbol classSymbol) { 2554 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2555 if (prunedInfo != null) { 2556 for (JCTree prunedTree: prunedInfo) { 2557 prunedTree.accept(classReferenceVisitor); 2558 } 2559 } 2560 } 2561 2562 /* ************************************************************************ 2563 * main method 2564 *************************************************************************/ 2565 2566 /** Generate code for a class definition. 2567 * @param env The attribution environment that belongs to the 2568 * outermost class containing this class definition. 2569 * We need this for resolving some additional symbols. 2570 * @param cdef The tree representing the class definition. 2571 * @return True if code is generated with no errors. 2572 */ 2573 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2574 try { 2575 attrEnv = env; 2576 ClassSymbol c = cdef.sym; 2577 this.toplevel = env.toplevel; 2578 this.endPosTable = toplevel.endPositions; 2579 /* method normalizeDefs() can add references to external classes into the constant pool 2580 */ 2581 cdef.defs = normalizeDefs(cdef.defs, c); 2582 generateReferencesToPrunedTree(c); 2583 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2584 localEnv.toplevel = env.toplevel; 2585 localEnv.enclClass = cdef; 2586 2587 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2588 genDef(l.head, localEnv); 2589 } 2590 if (poolWriter.size() > PoolWriter.MAX_ENTRIES) { 2591 log.error(cdef.pos(), Errors.LimitPool); 2592 nerrs++; 2593 } 2594 if (nerrs != 0) { 2595 // if errors, discard code 2596 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2597 if (l.head.hasTag(METHODDEF)) 2598 ((JCMethodDecl) l.head).sym.code = null; 2599 } 2600 } 2601 cdef.defs = List.nil(); // discard trees 2602 return nerrs == 0; 2603 } finally { 2604 // note: this method does NOT support recursion. 2605 attrEnv = null; 2606 this.env = null; 2607 toplevel = null; 2608 endPosTable = null; 2609 nerrs = 0; 2610 qualifiedSymbolCache.clear(); 2611 } 2612 } 2613 2614 /* ************************************************************************ 2615 * Auxiliary classes 2616 *************************************************************************/ 2617 2618 /** An abstract class for finalizer generation. 2619 */ 2620 abstract class GenFinalizer { 2621 /** Generate code to clean up when unwinding. */ 2622 abstract void gen(); 2623 2624 /** Generate code to clean up at last. */ 2625 abstract void genLast(); 2626 2627 /** Does this finalizer have some nontrivial cleanup to perform? */ 2628 boolean hasFinalizer() { return true; } 2629 2630 /** Should be invoked after the try's body has been visited. */ 2631 void afterBody() {} 2632 } 2633 2634 /** code generation contexts, 2635 * to be used as type parameter for environments. 2636 */ 2637 final class GenContext { 2638 2639 /** 2640 * The top defined local variables for exit or continue branches to merge into. 2641 * It may contain uninitialized variables to be initialized by branched code, 2642 * so we cannot use Code.State.defined bits. 2643 */ 2644 final int limit; 2645 2646 /** A chain for all unresolved jumps that exit the current environment. 2647 */ 2648 Chain exit = null; 2649 2650 /** A chain for all unresolved jumps that continue in the 2651 * current environment. 2652 */ 2653 Chain cont = null; 2654 2655 /** A closure that generates the finalizer of the current environment. 2656 * Only set for Synchronized and Try contexts. 2657 */ 2658 GenFinalizer finalize = null; 2659 2660 /** Is this a switch statement? If so, allocate registers 2661 * even when the variable declaration is unreachable. 2662 */ 2663 boolean isSwitch = false; 2664 2665 /** A list buffer containing all gaps in the finalizer range, 2666 * where a catch all exception should not apply. 2667 */ 2668 ListBuffer<Integer> gaps = null; 2669 2670 GenContext() { 2671 var code = Gen.this.code; 2672 this.limit = code == null ? 0 : code.nextreg; 2673 } 2674 2675 /** Add given chain to exit chain. 2676 */ 2677 void addExit(Chain c) { 2678 if (c != null) { 2679 c.state.defined.excludeFrom(limit); 2680 } 2681 exit = Code.mergeChains(c, exit); 2682 } 2683 2684 /** Add given chain to cont chain. 2685 */ 2686 void addCont(Chain c) { 2687 if (c != null) { 2688 c.state.defined.excludeFrom(limit); 2689 } 2690 cont = Code.mergeChains(c, cont); 2691 } 2692 } 2693 2694 record PatternMatchingCatchConfiguration(Set<JCMethodInvocation> invocations, 2695 ListBuffer<int[]> ranges, 2696 JCCatch handler, 2697 State startState) { 2698 public PatternMatchingCatchConfiguration restart(State newState) { 2699 return new PatternMatchingCatchConfiguration(invocations(), 2700 new ListBuffer<int[]>(), 2701 handler(), 2702 newState); 2703 } 2704 } 2705 }