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