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