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