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         Type localType = v.erasure(types);
1117         if (localType.requiresPreload(env.enclClass.sym)) {
1118             poolWriter.enterPreloadClass((ClassSymbol) localType.tsym);
1119         }
1120     }
1121 
1122     public void visitSkip(JCSkip tree) {
1123     }
1124 
1125     public void visitBlock(JCBlock tree) {
1126         if (tree.patternMatchingCatch != null) {
1127             Set<JCMethodInvocation> prevInvocationsWithPatternMatchingCatch = invocationsWithPatternMatchingCatch;
1128             ListBuffer<int[]> prevRanges = patternMatchingInvocationRanges;
1129             State startState = code.state.dup();
1130             try {
1131                 invocationsWithPatternMatchingCatch = tree.patternMatchingCatch.calls2Handle();
1132                 patternMatchingInvocationRanges = new ListBuffer<>();
1133                 doVisitBlock(tree);
1134             } finally {
1135                 Chain skipCatch = code.branch(goto_);
1136                 JCCatch handler = tree.patternMatchingCatch.handler();
1137                 code.entryPoint(startState, handler.param.sym.type);
1138                 genPatternMatchingCatch(handler, env, patternMatchingInvocationRanges.toList());
1139                 code.resolve(skipCatch);
1140                 invocationsWithPatternMatchingCatch = prevInvocationsWithPatternMatchingCatch;
1141                 patternMatchingInvocationRanges = prevRanges;
1142             }
1143         } else {
1144             doVisitBlock(tree);
1145         }
1146     }
1147 
1148     private void doVisitBlock(JCBlock tree) {
1149         int limit = code.nextreg;
1150         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1151         genStats(tree.stats, localEnv);
1152         // End the scope of all block-local variables in variable info.
1153         if (!env.tree.hasTag(METHODDEF)) {
1154             code.statBegin(tree.endpos);
1155             code.endScopes(limit);
1156             code.pendingStatPos = Position.NOPOS;
1157         }
1158     }
1159 
1160     public void visitDoLoop(JCDoWhileLoop tree) {
1161         genLoop(tree, tree.body, tree.cond, List.nil(), false);
1162     }
1163 
1164     public void visitWhileLoop(JCWhileLoop tree) {
1165         genLoop(tree, tree.body, tree.cond, List.nil(), true);
1166     }
1167 
1168     public void visitForLoop(JCForLoop tree) {
1169         int limit = code.nextreg;
1170         genStats(tree.init, env);
1171         genLoop(tree, tree.body, tree.cond, tree.step, true);
1172         code.endScopes(limit);
1173     }
1174     //where
1175         /** Generate code for a loop.
1176          *  @param loop       The tree representing the loop.
1177          *  @param body       The loop's body.
1178          *  @param cond       The loop's controlling condition.
1179          *  @param step       "Step" statements to be inserted at end of
1180          *                    each iteration.
1181          *  @param testFirst  True if the loop test belongs before the body.
1182          */
1183         private void genLoop(JCStatement loop,
1184                              JCStatement body,
1185                              JCExpression cond,
1186                              List<JCExpressionStatement> step,
1187                              boolean testFirst) {
1188             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1189             int startpc = code.entryPoint();
1190             if (testFirst) { //while or for loop
1191                 CondItem c;
1192                 if (cond != null) {
1193                     code.statBegin(cond.pos);
1194                     Assert.check(code.isStatementStart());
1195                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1196                 } else {
1197                     c = items.makeCondItem(goto_);
1198                 }
1199                 Chain loopDone = c.jumpFalse();
1200                 code.resolve(c.trueJumps);
1201                 Assert.check(code.isStatementStart());
1202                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1203                 code.resolve(loopEnv.info.cont);
1204                 genStats(step, loopEnv);
1205                 code.resolve(code.branch(goto_), startpc);
1206                 code.resolve(loopDone);
1207             } else {
1208                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1209                 code.resolve(loopEnv.info.cont);
1210                 genStats(step, loopEnv);
1211                 if (code.isAlive()) {
1212                     CondItem c;
1213                     if (cond != null) {
1214                         code.statBegin(cond.pos);
1215                         Assert.check(code.isStatementStart());
1216                         c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1217                     } else {
1218                         c = items.makeCondItem(goto_);
1219                     }
1220                     code.resolve(c.jumpTrue(), startpc);
1221                     Assert.check(code.isStatementStart());
1222                     code.resolve(c.falseJumps);
1223                 }
1224             }
1225             Chain exit = loopEnv.info.exit;
1226             if (exit != null) {
1227                 code.resolve(exit);
1228                 exit.state.defined.excludeFrom(code.nextreg);
1229             }
1230         }
1231 
1232     public void visitForeachLoop(JCEnhancedForLoop tree) {
1233         throw new AssertionError(); // should have been removed by Lower.
1234     }
1235 
1236     public void visitLabelled(JCLabeledStatement tree) {
1237         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1238         genStat(tree.body, localEnv, CRT_STATEMENT);
1239         Chain exit = localEnv.info.exit;
1240         if (exit != null) {
1241             code.resolve(exit);
1242             exit.state.defined.excludeFrom(code.nextreg);
1243         }
1244     }
1245 
1246     public void visitSwitch(JCSwitch tree) {
1247         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1248     }
1249 
1250     @Override
1251     public void visitSwitchExpression(JCSwitchExpression tree) {
1252         code.resolvePending();
1253         boolean prevInCondSwitchExpression = inCondSwitchExpression;
1254         try {
1255             inCondSwitchExpression = false;
1256             doHandleSwitchExpression(tree);
1257         } finally {
1258             inCondSwitchExpression = prevInCondSwitchExpression;
1259         }
1260         result = items.makeStackItem(pt);
1261     }
1262 
1263     private void doHandleSwitchExpression(JCSwitchExpression tree) {
1264         List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1265         LocalItem prevSwitchResult = switchResult;
1266         int limit = code.nextreg;
1267         try {
1268             stackBeforeSwitchExpression = List.nil();
1269             switchResult = null;
1270             if (hasTry(tree)) {
1271                 //if the switch expression contains try-catch, the catch handlers need to have
1272                 //an empty stack. So stash whole stack to local variables, and restore it before
1273                 //breaks:
1274                 while (code.state.stacksize > 0) {
1275                     Type type = code.state.peek();
1276                     Name varName = names.fromString(target.syntheticNameChar() +
1277                                                     "stack" +
1278                                                     target.syntheticNameChar() +
1279                                                     tree.pos +
1280                                                     target.syntheticNameChar() +
1281                                                     code.state.stacksize);
1282                     VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type,
1283                                                   this.env.enclMethod.sym);
1284                     LocalItem item = items.new LocalItem(type, code.newLocal(var));
1285                     stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item);
1286                     item.store();
1287                 }
1288                 switchResult = makeTemp(tree.type);
1289             }
1290             int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
1291             try {
1292                 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1293             } finally {
1294                 code.setLetExprStackPos(prevLetExprStart);
1295             }
1296         } finally {
1297             stackBeforeSwitchExpression = prevStackBeforeSwitchExpression;
1298             switchResult = prevSwitchResult;
1299             code.endScopes(limit);
1300         }
1301     }
1302     //where:
1303         private boolean hasTry(JCSwitchExpression tree) {
1304             class HasTryScanner extends TreeScanner {
1305                 private boolean hasTry;
1306 
1307                 @Override
1308                 public void visitTry(JCTry tree) {
1309                     hasTry = true;
1310                 }
1311 
1312                 @Override
1313                 public void visitSynchronized(JCSynchronized tree) {
1314                     hasTry = true;
1315                 }
1316 
1317                 @Override
1318                 public void visitClassDef(JCClassDecl tree) {
1319                 }
1320 
1321                 @Override
1322                 public void visitLambda(JCLambda tree) {
1323                 }
1324             };
1325 
1326             HasTryScanner hasTryScanner = new HasTryScanner();
1327 
1328             hasTryScanner.scan(tree);
1329             return hasTryScanner.hasTry;
1330         }
1331 
1332     private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1333                               boolean patternSwitch) {
1334         int limit = code.nextreg;
1335         Assert.check(!selector.type.hasTag(CLASS));
1336         int switchStart = patternSwitch ? code.entryPoint() : -1;
1337         int startpcCrt = genCrt ? code.curCP() : 0;
1338         Assert.check(code.isStatementStart());
1339         Item sel = genExpr(selector, syms.intType);
1340         if (cases.isEmpty()) {
1341             // We are seeing:  switch <sel> {}
1342             sel.load().drop();
1343             if (genCrt)
1344                 code.crt.put(TreeInfo.skipParens(selector),
1345                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1346         } else {
1347             // We are seeing a nonempty switch.
1348             sel.load();
1349             if (genCrt)
1350                 code.crt.put(TreeInfo.skipParens(selector),
1351                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1352             Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1353             switchEnv.info.isSwitch = true;
1354 
1355             // Compute number of labels and minimum and maximum label values.
1356             // For each case, store its label in an array.
1357             int lo = Integer.MAX_VALUE;  // minimum label.
1358             int hi = Integer.MIN_VALUE;  // maximum label.
1359             int nlabels = 0;               // number of labels.
1360 
1361             int[] labels = new int[cases.length()];  // the label array.
1362             int defaultIndex = -1;     // the index of the default clause.
1363 
1364             List<JCCase> l = cases;
1365             for (int i = 0; i < labels.length; i++) {
1366                 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1367                     Assert.check(l.head.labels.size() == 1);
1368                     int val = ((Number) constLabel.expr.type.constValue()).intValue();
1369                     labels[i] = val;
1370                     if (val < lo) lo = val;
1371                     if (hi < val) hi = val;
1372                     nlabels++;
1373                 } else {
1374                     Assert.check(defaultIndex == -1);
1375                     defaultIndex = i;
1376                 }
1377                 l = l.tail;
1378             }
1379 
1380             // Determine whether to issue a tableswitch or a lookupswitch
1381             // instruction.
1382             long table_space_cost = 4 + ((long) hi - lo + 1); // words
1383             long table_time_cost = 3; // comparisons
1384             long lookup_space_cost = 3 + 2 * (long) nlabels;
1385             long lookup_time_cost = nlabels;
1386             int opcode =
1387                 nlabels > 0 &&
1388                 table_space_cost + 3 * table_time_cost <=
1389                 lookup_space_cost + 3 * lookup_time_cost
1390                 ?
1391                 tableswitch : lookupswitch;
1392 
1393             int startpc = code.curCP();    // the position of the selector operation
1394             code.emitop0(opcode);
1395             code.align(4);
1396             int tableBase = code.curCP();  // the start of the jump table
1397             int[] offsets = null;          // a table of offsets for a lookupswitch
1398             code.emit4(-1);                // leave space for default offset
1399             if (opcode == tableswitch) {
1400                 code.emit4(lo);            // minimum label
1401                 code.emit4(hi);            // maximum label
1402                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
1403                     code.emit4(-1);
1404                 }
1405             } else {
1406                 code.emit4(nlabels);    // number of labels
1407                 for (int i = 0; i < nlabels; i++) {
1408                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
1409                 }
1410                 offsets = new int[labels.length];
1411             }
1412             Code.State stateSwitch = code.state.dup();
1413             code.markDead();
1414 
1415             // For each case do:
1416             l = cases;
1417             for (int i = 0; i < labels.length; i++) {
1418                 JCCase c = l.head;
1419                 l = l.tail;
1420 
1421                 int pc = code.entryPoint(stateSwitch);
1422                 // Insert offset directly into code or else into the
1423                 // offsets table.
1424                 if (i != defaultIndex) {
1425                     if (opcode == tableswitch) {
1426                         code.put4(
1427                             tableBase + 4 * (labels[i] - lo + 3),
1428                             pc - startpc);
1429                     } else {
1430                         offsets[i] = pc - startpc;
1431                     }
1432                 } else {
1433                     code.put4(tableBase, pc - startpc);
1434                 }
1435 
1436                 // Generate code for the statements in this case.
1437                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1438             }
1439 
1440             if (switchEnv.info.cont != null) {
1441                 Assert.check(patternSwitch);
1442                 code.resolve(switchEnv.info.cont, switchStart);
1443             }
1444 
1445             // Resolve all breaks.
1446             Chain exit = switchEnv.info.exit;
1447             if  (exit != null) {
1448                 code.resolve(exit);
1449                 exit.state.defined.excludeFrom(limit);
1450             }
1451 
1452             // If we have not set the default offset, we do so now.
1453             if (code.get4(tableBase) == -1) {
1454                 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc);
1455             }
1456 
1457             if (opcode == tableswitch) {
1458                 // Let any unfilled slots point to the default case.
1459                 int defaultOffset = code.get4(tableBase);
1460                 for (long i = lo; i <= hi; i++) {
1461                     int t = (int)(tableBase + 4 * (i - lo + 3));
1462                     if (code.get4(t) == -1)
1463                         code.put4(t, defaultOffset);
1464                 }
1465             } else {
1466                 // Sort non-default offsets and copy into lookup table.
1467                 if (defaultIndex >= 0)
1468                     for (int i = defaultIndex; i < labels.length - 1; i++) {
1469                         labels[i] = labels[i+1];
1470                         offsets[i] = offsets[i+1];
1471                     }
1472                 if (nlabels > 0)
1473                     qsort2(labels, offsets, 0, nlabels - 1);
1474                 for (int i = 0; i < nlabels; i++) {
1475                     int caseidx = tableBase + 8 * (i + 1);
1476                     code.put4(caseidx, labels[i]);
1477                     code.put4(caseidx + 4, offsets[i]);
1478                 }
1479             }
1480         }
1481         code.endScopes(limit);
1482     }
1483 //where
1484         /** Sort (int) arrays of keys and values
1485          */
1486        static void qsort2(int[] keys, int[] values, int lo, int hi) {
1487             int i = lo;
1488             int j = hi;
1489             int pivot = keys[(i+j)/2];
1490             do {
1491                 while (keys[i] < pivot) i++;
1492                 while (pivot < keys[j]) j--;
1493                 if (i <= j) {
1494                     int temp1 = keys[i];
1495                     keys[i] = keys[j];
1496                     keys[j] = temp1;
1497                     int temp2 = values[i];
1498                     values[i] = values[j];
1499                     values[j] = temp2;
1500                     i++;
1501                     j--;
1502                 }
1503             } while (i <= j);
1504             if (lo < j) qsort2(keys, values, lo, j);
1505             if (i < hi) qsort2(keys, values, i, hi);
1506         }
1507 
1508     public void visitSynchronized(JCSynchronized tree) {
1509         int limit = code.nextreg;
1510         // Generate code to evaluate lock and save in temporary variable.
1511         final LocalItem lockVar = makeTemp(syms.objectType);
1512         Assert.check(code.isStatementStart());
1513         genExpr(tree.lock, tree.lock.type).load().duplicate();
1514         lockVar.store();
1515 
1516         // Generate code to enter monitor.
1517         code.emitop0(monitorenter);
1518         code.state.lock(lockVar.reg);
1519 
1520         // Generate code for a try statement with given body, no catch clauses
1521         // in a new environment with the "exit-monitor" operation as finalizer.
1522         final Env<GenContext> syncEnv = env.dup(tree, new GenContext());
1523         syncEnv.info.finalize = new GenFinalizer() {
1524             void gen() {
1525                 genLast();
1526                 Assert.check(syncEnv.info.gaps.length() % 2 == 0);
1527                 syncEnv.info.gaps.append(code.curCP());
1528             }
1529             void genLast() {
1530                 if (code.isAlive()) {
1531                     lockVar.load();
1532                     code.emitop0(monitorexit);
1533                     code.state.unlock(lockVar.reg);
1534                 }
1535             }
1536         };
1537         syncEnv.info.gaps = new ListBuffer<>();
1538         genTry(tree.body, List.nil(), syncEnv);
1539         code.endScopes(limit);
1540     }
1541 
1542     public void visitTry(final JCTry tree) {
1543         // Generate code for a try statement with given body and catch clauses,
1544         // in a new environment which calls the finally block if there is one.
1545         final Env<GenContext> tryEnv = env.dup(tree, new GenContext());
1546         final Env<GenContext> oldEnv = env;
1547         tryEnv.info.finalize = new GenFinalizer() {
1548             void gen() {
1549                 Assert.check(tryEnv.info.gaps.length() % 2 == 0);
1550                 tryEnv.info.gaps.append(code.curCP());
1551                 genLast();
1552             }
1553             void genLast() {
1554                 if (tree.finalizer != null)
1555                     genStat(tree.finalizer, oldEnv, CRT_BLOCK);
1556             }
1557             boolean hasFinalizer() {
1558                 return tree.finalizer != null;
1559             }
1560 
1561             @Override
1562             void afterBody() {
1563                 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1564                     //for body-only finally, remove the GenFinalizer after try body
1565                     //so that the finally is not generated to catch bodies:
1566                     tryEnv.info.finalize = null;
1567                 }
1568             }
1569 
1570         };
1571         tryEnv.info.gaps = new ListBuffer<>();
1572         genTry(tree.body, tree.catchers, tryEnv);
1573     }
1574     //where
1575         /** Generate code for a try or synchronized statement
1576          *  @param body      The body of the try or synchronized statement.
1577          *  @param catchers  The list of catch clauses.
1578          *  @param env       The current environment of the body.
1579          */
1580         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1581             int limit = code.nextreg;
1582             int startpc = code.curCP();
1583             Code.State stateTry = code.state.dup();
1584             genStat(body, env, CRT_BLOCK);
1585             int endpc = code.curCP();
1586             List<Integer> gaps = env.info.gaps.toList();
1587             code.statBegin(TreeInfo.endPos(body));
1588             genFinalizer(env);
1589             code.statBegin(TreeInfo.endPos(env.tree));
1590             Chain exitChain;
1591             boolean actualTry = env.tree.hasTag(TRY);
1592             if (startpc == endpc && actualTry) {
1593                 exitChain = code.branch(dontgoto);
1594             } else {
1595                 exitChain = code.branch(goto_);
1596             }
1597             endFinalizerGap(env);
1598             env.info.finalize.afterBody();
1599             boolean hasFinalizer =
1600                 env.info.finalize != null &&
1601                 env.info.finalize.hasFinalizer();
1602             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1603                 // start off with exception on stack
1604                 code.entryPoint(stateTry, l.head.param.sym.type);
1605                 genCatch(l.head, env, startpc, endpc, gaps);
1606                 genFinalizer(env);
1607                 if (hasFinalizer || l.tail.nonEmpty()) {
1608                     code.statBegin(TreeInfo.endPos(env.tree));
1609                     exitChain = Code.mergeChains(exitChain,
1610                                                  code.branch(goto_));
1611                 }
1612                 endFinalizerGap(env);
1613             }
1614             if (hasFinalizer && (startpc != endpc || !actualTry)) {
1615                 // Create a new register segment to avoid allocating
1616                 // the same variables in finalizers and other statements.
1617                 code.newRegSegment();
1618 
1619                 // Add a catch-all clause.
1620 
1621                 // start off with exception on stack
1622                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1623 
1624                 // Register all exception ranges for catch all clause.
1625                 // The range of the catch all clause is from the beginning
1626                 // of the try or synchronized block until the present
1627                 // code pointer excluding all gaps in the current
1628                 // environment's GenContext.
1629                 int startseg = startpc;
1630                 while (env.info.gaps.nonEmpty()) {
1631                     int endseg = env.info.gaps.next().intValue();
1632                     registerCatch(body.pos(), startseg, endseg,
1633                                   catchallpc, 0);
1634                     startseg = env.info.gaps.next().intValue();
1635                 }
1636                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1637                 code.markStatBegin();
1638 
1639                 Item excVar = makeTemp(syms.throwableType);
1640                 excVar.store();
1641                 genFinalizer(env);
1642                 code.resolvePending();
1643                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1644                 code.markStatBegin();
1645 
1646                 excVar.load();
1647                 registerCatch(body.pos(), startseg,
1648                               env.info.gaps.next().intValue(),
1649                               catchallpc, 0);
1650                 code.emitop0(athrow);
1651                 code.markDead();
1652 
1653                 // If there are jsr's to this finalizer, ...
1654                 if (env.info.cont != null) {
1655                     // Resolve all jsr's.
1656                     code.resolve(env.info.cont);
1657 
1658                     // Mark statement line number
1659                     code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1660                     code.markStatBegin();
1661 
1662                     // Save return address.
1663                     LocalItem retVar = makeTemp(syms.throwableType);
1664                     retVar.store();
1665 
1666                     // Generate finalizer code.
1667                     env.info.finalize.genLast();
1668 
1669                     // Return.
1670                     code.emitop1w(ret, retVar.reg);
1671                     code.markDead();
1672                 }
1673             }
1674             // Resolve all breaks.
1675             code.resolve(exitChain);
1676 
1677             code.endScopes(limit);
1678         }
1679 
1680         /** Generate code for a catch clause.
1681          *  @param tree     The catch clause.
1682          *  @param env      The environment current in the enclosing try.
1683          *  @param startpc  Start pc of try-block.
1684          *  @param endpc    End pc of try-block.
1685          */
1686         void genCatch(JCCatch tree,
1687                       Env<GenContext> env,
1688                       int startpc, int endpc,
1689                       List<Integer> gaps) {
1690             if (startpc != endpc) {
1691                 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs
1692                         = catchTypesWithAnnotations(tree);
1693                 while (gaps.nonEmpty()) {
1694                     for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1695                         JCExpression subCatch = subCatch1.snd;
1696                         int catchType = makeRef(tree.pos(), subCatch.type);
1697                         int end = gaps.head.intValue();
1698                         registerCatch(tree.pos(),
1699                                       startpc,  end, code.curCP(),
1700                                       catchType);
1701                         for (Attribute.TypeCompound tc :  subCatch1.fst) {
1702                                 tc.position.setCatchInfo(catchType, startpc);
1703                         }
1704                     }
1705                     gaps = gaps.tail;
1706                     startpc = gaps.head.intValue();
1707                     gaps = gaps.tail;
1708                 }
1709                 if (startpc < endpc) {
1710                     for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1711                         JCExpression subCatch = subCatch1.snd;
1712                         int catchType = makeRef(tree.pos(), subCatch.type);
1713                         registerCatch(tree.pos(),
1714                                       startpc, endpc, code.curCP(),
1715                                       catchType);
1716                         for (Attribute.TypeCompound tc :  subCatch1.fst) {
1717                             tc.position.setCatchInfo(catchType, startpc);
1718                         }
1719                     }
1720                 }
1721                 genCatchBlock(tree, env);
1722             }
1723         }
1724         void genPatternMatchingCatch(JCCatch tree,
1725                                      Env<GenContext> env,
1726                                      List<int[]> ranges) {
1727             for (int[] range : ranges) {
1728                 JCExpression subCatch = tree.param.vartype;
1729                 int catchType = makeRef(tree.pos(), subCatch.type);
1730                 registerCatch(tree.pos(),
1731                               range[0], range[1], code.curCP(),
1732                               catchType);
1733             }
1734             genCatchBlock(tree, env);
1735         }
1736         void genCatchBlock(JCCatch tree, Env<GenContext> env) {
1737             VarSymbol exparam = tree.param.sym;
1738             code.statBegin(tree.pos);
1739             code.markStatBegin();
1740             int limit = code.nextreg;
1741             code.newLocal(exparam);
1742             items.makeLocalItem(exparam).store();
1743             code.statBegin(TreeInfo.firstStatPos(tree.body));
1744             genStat(tree.body, env, CRT_BLOCK);
1745             code.endScopes(limit);
1746             code.statBegin(TreeInfo.endPos(tree.body));
1747         }
1748         // where
1749         List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) {
1750             return TreeInfo.isMultiCatch(tree) ?
1751                     catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) :
1752                     List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype));
1753         }
1754         // where
1755         List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) {
1756             List<JCExpression> alts = tree.alternatives;
1757             List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head));
1758             alts = alts.tail;
1759 
1760             while(alts != null && alts.head != null) {
1761                 JCExpression alt = alts.head;
1762                 if (alt instanceof JCAnnotatedType annotatedType) {
1763                     res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt));
1764                 } else {
1765                     res = res.prepend(new Pair<>(List.nil(), alt));
1766                 }
1767                 alts = alts.tail;
1768             }
1769             return res.reverse();
1770         }
1771 
1772         /** Register a catch clause in the "Exceptions" code-attribute.
1773          */
1774         void registerCatch(DiagnosticPosition pos,
1775                            int startpc, int endpc,
1776                            int handler_pc, int catch_type) {
1777             char startpc1 = (char)startpc;
1778             char endpc1 = (char)endpc;
1779             char handler_pc1 = (char)handler_pc;
1780             if (startpc1 == startpc &&
1781                 endpc1 == endpc &&
1782                 handler_pc1 == handler_pc) {
1783                 code.addCatch(startpc1, endpc1, handler_pc1,
1784                               (char)catch_type);
1785             } else {
1786                 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1787                 nerrs++;
1788             }
1789         }
1790 
1791     public void visitIf(JCIf tree) {
1792         int limit = code.nextreg;
1793         Chain thenExit = null;
1794         Assert.check(code.isStatementStart());
1795         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1796                              CRT_FLOW_CONTROLLER);
1797         Chain elseChain = c.jumpFalse();
1798         Assert.check(code.isStatementStart());
1799         if (!c.isFalse()) {
1800             code.resolve(c.trueJumps);
1801             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1802             thenExit = code.branch(goto_);
1803         }
1804         if (elseChain != null) {
1805             code.resolve(elseChain);
1806             if (tree.elsepart != null) {
1807                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1808             }
1809         }
1810         code.resolve(thenExit);
1811         code.endScopes(limit);
1812         Assert.check(code.isStatementStart());
1813     }
1814 
1815     public void visitExec(JCExpressionStatement tree) {
1816         // Optimize x++ to ++x and x-- to --x.
1817         JCExpression e = tree.expr;
1818         switch (e.getTag()) {
1819             case POSTINC:
1820                 ((JCUnary) e).setTag(PREINC);
1821                 break;
1822             case POSTDEC:
1823                 ((JCUnary) e).setTag(PREDEC);
1824                 break;
1825         }
1826         Assert.check(code.isStatementStart());
1827         genExpr(tree.expr, tree.expr.type).drop();
1828         Assert.check(code.isStatementStart());
1829     }
1830 
1831     public void visitBreak(JCBreak tree) {
1832         Assert.check(code.isStatementStart());
1833         final Env<GenContext> targetEnv = unwindBreak(tree.target);
1834         targetEnv.info.addExit(code.branch(goto_));
1835         endFinalizerGaps(env, targetEnv);
1836     }
1837 
1838     public void visitYield(JCYield tree) {
1839         Assert.check(code.isStatementStart());
1840         final Env<GenContext> targetEnv;
1841         if (inCondSwitchExpression) {
1842             CondItem value = genCond(tree.value, CRT_FLOW_TARGET);
1843             Chain falseJumps = value.jumpFalse();
1844 
1845             code.resolve(value.trueJumps);
1846             Env<GenContext> localEnv = unwindBreak(tree.target);
1847             reloadStackBeforeSwitchExpr();
1848             Chain trueJumps = code.branch(goto_);
1849 
1850             endFinalizerGaps(env, localEnv);
1851 
1852             code.resolve(falseJumps);
1853             targetEnv = unwindBreak(tree.target);
1854             reloadStackBeforeSwitchExpr();
1855             falseJumps = code.branch(goto_);
1856 
1857             if (switchExpressionTrueChain == null) {
1858                 switchExpressionTrueChain = trueJumps;
1859             } else {
1860                 switchExpressionTrueChain =
1861                         Code.mergeChains(switchExpressionTrueChain, trueJumps);
1862             }
1863             if (switchExpressionFalseChain == null) {
1864                 switchExpressionFalseChain = falseJumps;
1865             } else {
1866                 switchExpressionFalseChain =
1867                         Code.mergeChains(switchExpressionFalseChain, falseJumps);
1868             }
1869         } else {
1870             genExpr(tree.value, pt).load();
1871             if (switchResult != null)
1872                 switchResult.store();
1873 
1874             targetEnv = unwindBreak(tree.target);
1875 
1876             if (code.isAlive()) {
1877                 reloadStackBeforeSwitchExpr();
1878                 if (switchResult != null)
1879                     switchResult.load();
1880 
1881                 code.state.forceStackTop(tree.target.type);
1882                 targetEnv.info.addExit(code.branch(goto_));
1883                 code.markDead();
1884             }
1885         }
1886         endFinalizerGaps(env, targetEnv);
1887     }
1888     //where:
1889         /** As side-effect, might mark code as dead disabling any further emission.
1890          */
1891         private Env<GenContext> unwindBreak(JCTree target) {
1892             int tmpPos = code.pendingStatPos;
1893             Env<GenContext> targetEnv = unwind(target, env);
1894             code.pendingStatPos = tmpPos;
1895             return targetEnv;
1896         }
1897 
1898         private void reloadStackBeforeSwitchExpr() {
1899             for (LocalItem li : stackBeforeSwitchExpression)
1900                 li.load();
1901         }
1902 
1903     public void visitContinue(JCContinue tree) {
1904         int tmpPos = code.pendingStatPos;
1905         Env<GenContext> targetEnv = unwind(tree.target, env);
1906         code.pendingStatPos = tmpPos;
1907         Assert.check(code.isStatementStart());
1908         targetEnv.info.addCont(code.branch(goto_));
1909         endFinalizerGaps(env, targetEnv);
1910     }
1911 
1912     public void visitReturn(JCReturn tree) {
1913         int limit = code.nextreg;
1914         final Env<GenContext> targetEnv;
1915 
1916         /* Save and then restore the location of the return in case a finally
1917          * is expanded (with unwind()) in the middle of our bytecodes.
1918          */
1919         int tmpPos = code.pendingStatPos;
1920         if (tree.expr != null) {
1921             Assert.check(code.isStatementStart());
1922             Item r = genExpr(tree.expr, pt).load();
1923             if (hasFinally(env.enclMethod, env)) {
1924                 r = makeTemp(pt);
1925                 r.store();
1926             }
1927             targetEnv = unwind(env.enclMethod, env);
1928             code.pendingStatPos = tmpPos;
1929             r.load();
1930             code.emitop0(ireturn + Code.truncate(Code.typecode(pt)));
1931         } else {
1932             targetEnv = unwind(env.enclMethod, env);
1933             code.pendingStatPos = tmpPos;
1934             code.emitop0(return_);
1935         }
1936         endFinalizerGaps(env, targetEnv);
1937         code.endScopes(limit);
1938     }
1939 
1940     public void visitThrow(JCThrow tree) {
1941         Assert.check(code.isStatementStart());
1942         genExpr(tree.expr, tree.expr.type).load();
1943         code.emitop0(athrow);
1944         Assert.check(code.isStatementStart());
1945     }
1946 
1947 /* ************************************************************************
1948  * Visitor methods for expressions
1949  *************************************************************************/
1950 
1951     public void visitApply(JCMethodInvocation tree) {
1952         setTypeAnnotationPositions(tree.pos);
1953         // Generate code for method.
1954         Item m = genExpr(tree.meth, methodType);
1955         // Generate code for all arguments, where the expected types are
1956         // the parameters of the method's external type (that is, any implicit
1957         // outer instance of a super(...) call appears as first parameter).
1958         MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
1959         genArgs(tree.args,
1960                 msym.externalType(types).getParameterTypes());
1961         if (!msym.isDynamic()) {
1962             code.statBegin(tree.pos);
1963         }
1964         if (invocationsWithPatternMatchingCatch.contains(tree)) {
1965             int start = code.curCP();
1966             result = m.invoke();
1967             patternMatchingInvocationRanges.add(new int[] {start, code.curCP()});
1968         } else {
1969             result = m.invoke();
1970         }
1971     }
1972 
1973     public void visitConditional(JCConditional tree) {
1974         Chain thenExit = null;
1975         code.statBegin(tree.cond.pos);
1976         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
1977         Chain elseChain = c.jumpFalse();
1978         if (!c.isFalse()) {
1979             code.resolve(c.trueJumps);
1980             int startpc = genCrt ? code.curCP() : 0;
1981             code.statBegin(tree.truepart.pos);
1982             genExpr(tree.truepart, pt).load();
1983             code.state.forceStackTop(tree.type);
1984             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
1985                                      startpc, code.curCP());
1986             thenExit = code.branch(goto_);
1987         }
1988         if (elseChain != null) {
1989             code.resolve(elseChain);
1990             int startpc = genCrt ? code.curCP() : 0;
1991             code.statBegin(tree.falsepart.pos);
1992             genExpr(tree.falsepart, pt).load();
1993             code.state.forceStackTop(tree.type);
1994             if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET,
1995                                      startpc, code.curCP());
1996         }
1997         code.resolve(thenExit);
1998         result = items.makeStackItem(pt);
1999     }
2000 
2001     private void setTypeAnnotationPositions(int treePos) {
2002         MethodSymbol meth = code.meth;
2003         boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR
2004                 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT;
2005 
2006         for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) {
2007             if (ta.hasUnknownPosition())
2008                 ta.tryFixPosition();
2009 
2010             if (ta.position.matchesPos(treePos))
2011                 ta.position.updatePosOffset(code.cp);
2012         }
2013 
2014         if (!initOrClinit)
2015             return;
2016 
2017         for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) {
2018             if (ta.hasUnknownPosition())
2019                 ta.tryFixPosition();
2020 
2021             if (ta.position.matchesPos(treePos))
2022                 ta.position.updatePosOffset(code.cp);
2023         }
2024 
2025         ClassSymbol clazz = meth.enclClass();
2026         for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
2027             if (!s.getKind().isField())
2028                 continue;
2029 
2030             for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
2031                 if (ta.hasUnknownPosition())
2032                     ta.tryFixPosition();
2033 
2034                 if (ta.position.matchesPos(treePos))
2035                     ta.position.updatePosOffset(code.cp);
2036             }
2037         }
2038     }
2039 
2040     public void visitNewClass(JCNewClass tree) {
2041         // Enclosing instances or anonymous classes should have been eliminated
2042         // by now.
2043         Assert.check(tree.encl == null && tree.def == null);
2044         setTypeAnnotationPositions(tree.pos);
2045 
2046         code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass);
2047         code.emitop0(dup);
2048 
2049         // Generate code for all arguments, where the expected types are
2050         // the parameters of the constructor's external type (that is,
2051         // any implicit outer instance appears as first parameter).
2052         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
2053 
2054         items.makeMemberItem(tree.constructor, true).invoke();
2055         result = items.makeStackItem(tree.type);
2056     }
2057 
2058     public void visitNewArray(JCNewArray tree) {
2059         setTypeAnnotationPositions(tree.pos);
2060 
2061         if (tree.elems != null) {
2062             Type elemtype = types.elemtype(tree.type);
2063             loadIntConst(tree.elems.length());
2064             Item arr = makeNewArray(tree.pos(), tree.type, 1);
2065             int i = 0;
2066             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {
2067                 arr.duplicate();
2068                 loadIntConst(i);
2069                 i++;
2070                 genExpr(l.head, elemtype).load();
2071                 items.makeIndexedItem(elemtype).store();
2072             }
2073             result = arr;
2074         } else {
2075             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2076                 genExpr(l.head, syms.intType).load();
2077             }
2078             result = makeNewArray(tree.pos(), tree.type, tree.dims.length());
2079         }
2080     }
2081 //where
2082         /** Generate code to create an array with given element type and number
2083          *  of dimensions.
2084          */
2085         Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) {
2086             Type elemtype = types.elemtype(type);
2087             if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) {
2088                 log.error(pos, Errors.LimitDimensions);
2089                 nerrs++;
2090             }
2091             int elemcode = Code.arraycode(elemtype);
2092             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2093                 code.emitAnewarray(makeRef(pos, elemtype), type);
2094             } else if (elemcode == 1) {
2095                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2096             } else {
2097                 code.emitNewarray(elemcode, type);
2098             }
2099             return items.makeStackItem(type);
2100         }
2101 
2102     public void visitParens(JCParens tree) {
2103         result = genExpr(tree.expr, tree.expr.type);
2104     }
2105 
2106     public void visitAssign(JCAssign tree) {
2107         Item l = genExpr(tree.lhs, tree.lhs.type);
2108         genExpr(tree.rhs, tree.lhs.type).load();
2109         if (tree.rhs.type.hasTag(BOT)) {
2110             /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2111                for "regarding a reference as having some other type in a manner that can be proved
2112                correct at compile time."
2113             */
2114             code.state.forceStackTop(tree.lhs.type);
2115         }
2116         result = items.makeAssignItem(l);
2117     }
2118 
2119     public void visitAssignop(JCAssignOp tree) {
2120         OperatorSymbol operator = tree.operator;
2121         Item l;
2122         if (operator.opcode == string_add) {
2123             l = concat.makeConcat(tree);
2124         } else {
2125             // Generate code for first expression
2126             l = genExpr(tree.lhs, tree.lhs.type);
2127 
2128             // If we have an increment of -32768 to +32767 of a local
2129             // int variable we can use an incr instruction instead of
2130             // proceeding further.
2131             if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
2132                 l instanceof LocalItem localItem &&
2133                 tree.lhs.type.getTag().isSubRangeOf(INT) &&
2134                 tree.rhs.type.getTag().isSubRangeOf(INT) &&
2135                 tree.rhs.type.constValue() != null) {
2136                 int ival = ((Number) tree.rhs.type.constValue()).intValue();
2137                 if (tree.hasTag(MINUS_ASG)) ival = -ival;
2138                 localItem.incr(ival);
2139                 result = l;
2140                 return;
2141             }
2142             // Otherwise, duplicate expression, load one copy
2143             // and complete binary operation.
2144             l.duplicate();
2145             l.coerce(operator.type.getParameterTypes().head).load();
2146             completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type);
2147         }
2148         result = items.makeAssignItem(l);
2149     }
2150 
2151     public void visitUnary(JCUnary tree) {
2152         OperatorSymbol operator = tree.operator;
2153         if (tree.hasTag(NOT)) {
2154             CondItem od = genCond(tree.arg, false);
2155             result = od.negate();
2156         } else {
2157             Item od = genExpr(tree.arg, operator.type.getParameterTypes().head);
2158             switch (tree.getTag()) {
2159             case POS:
2160                 result = od.load();
2161                 break;
2162             case NEG:
2163                 result = od.load();
2164                 code.emitop0(operator.opcode);
2165                 break;
2166             case COMPL:
2167                 result = od.load();
2168                 emitMinusOne(od.typecode);
2169                 code.emitop0(operator.opcode);
2170                 break;
2171             case PREINC: case PREDEC:
2172                 od.duplicate();
2173                 if (od instanceof LocalItem localItem &&
2174                     (operator.opcode == iadd || operator.opcode == isub)) {
2175                     localItem.incr(tree.hasTag(PREINC) ? 1 : -1);
2176                     result = od;
2177                 } else {
2178                     od.load();
2179                     code.emitop0(one(od.typecode));
2180                     code.emitop0(operator.opcode);
2181                     // Perform narrowing primitive conversion if byte,
2182                     // char, or short.  Fix for 4304655.
2183                     if (od.typecode != INTcode &&
2184                         Code.truncate(od.typecode) == INTcode)
2185                       code.emitop0(int2byte + od.typecode - BYTEcode);
2186                     result = items.makeAssignItem(od);
2187                 }
2188                 break;
2189             case POSTINC: case POSTDEC:
2190                 od.duplicate();
2191                 if (od instanceof LocalItem localItem &&
2192                     (operator.opcode == iadd || operator.opcode == isub)) {
2193                     Item res = od.load();
2194                     localItem.incr(tree.hasTag(POSTINC) ? 1 : -1);
2195                     result = res;
2196                 } else {
2197                     Item res = od.load();
2198                     od.stash(od.typecode);
2199                     code.emitop0(one(od.typecode));
2200                     code.emitop0(operator.opcode);
2201                     // Perform narrowing primitive conversion if byte,
2202                     // char, or short.  Fix for 4304655.
2203                     if (od.typecode != INTcode &&
2204                         Code.truncate(od.typecode) == INTcode)
2205                       code.emitop0(int2byte + od.typecode - BYTEcode);
2206                     od.store();
2207                     result = res;
2208                 }
2209                 break;
2210             case NULLCHK:
2211                 result = od.load();
2212                 code.emitop0(dup);
2213                 genNullCheck(tree);
2214                 break;
2215             default:
2216                 Assert.error();
2217             }
2218         }
2219     }
2220 
2221     /** Generate a null check from the object value at stack top. */
2222     private void genNullCheck(JCTree tree) {
2223         code.statBegin(tree.pos);
2224         callMethod(tree.pos(), syms.objectsType, names.requireNonNull,
2225                    List.of(syms.objectType), true);
2226         code.emitop0(pop);
2227     }
2228 
2229     public void visitBinary(JCBinary tree) {
2230         OperatorSymbol operator = tree.operator;
2231         if (operator.opcode == string_add) {
2232             result = concat.makeConcat(tree);
2233         } else if (tree.hasTag(AND)) {
2234             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2235             if (!lcond.isFalse()) {
2236                 Chain falseJumps = lcond.jumpFalse();
2237                 code.resolve(lcond.trueJumps);
2238                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2239                 result = items.
2240                     makeCondItem(rcond.opcode,
2241                                  rcond.trueJumps,
2242                                  Code.mergeChains(falseJumps,
2243                                                   rcond.falseJumps));
2244             } else {
2245                 result = lcond;
2246             }
2247         } else if (tree.hasTag(OR)) {
2248             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2249             if (!lcond.isTrue()) {
2250                 Chain trueJumps = lcond.jumpTrue();
2251                 code.resolve(lcond.falseJumps);
2252                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2253                 result = items.
2254                     makeCondItem(rcond.opcode,
2255                                  Code.mergeChains(trueJumps, rcond.trueJumps),
2256                                  rcond.falseJumps);
2257             } else {
2258                 result = lcond;
2259             }
2260         } else {
2261             Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head);
2262             od.load();
2263             result = completeBinop(tree.lhs, tree.rhs, operator);
2264         }
2265     }
2266 
2267 
2268         /** Complete generating code for operation, with left operand
2269          *  already on stack.
2270          *  @param lhs       The tree representing the left operand.
2271          *  @param rhs       The tree representing the right operand.
2272          *  @param operator  The operator symbol.
2273          */
2274         Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) {
2275             MethodType optype = (MethodType)operator.type;
2276             int opcode = operator.opcode;
2277             if (opcode >= if_icmpeq && opcode <= if_icmple &&
2278                     rhs.type.constValue() instanceof Number number &&
2279                     number.intValue() == 0) {
2280                 opcode = opcode + (ifeq - if_icmpeq);
2281             } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
2282                        TreeInfo.isNull(rhs)) {
2283                 opcode = opcode + (if_acmp_null - if_acmpeq);
2284             } else {
2285                 // The expected type of the right operand is
2286                 // the second parameter type of the operator, except for
2287                 // shifts with long shiftcount, where we convert the opcode
2288                 // to a short shift and the expected type to int.
2289                 Type rtype = operator.erasure(types).getParameterTypes().tail.head;
2290                 if (opcode >= ishll && opcode <= lushrl) {
2291                     opcode = opcode + (ishl - ishll);
2292                     rtype = syms.intType;
2293                 }
2294                 // Generate code for right operand and load.
2295                 genExpr(rhs, rtype).load();
2296                 // If there are two consecutive opcode instructions,
2297                 // emit the first now.
2298                 if (opcode >= (1 << preShift)) {
2299                     code.emitop0(opcode >> preShift);
2300                     opcode = opcode & 0xFF;
2301                 }
2302             }
2303             if (opcode >= ifeq && opcode <= if_acmpne ||
2304                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
2305                 return items.makeCondItem(opcode);
2306             } else {
2307                 code.emitop0(opcode);
2308                 return items.makeStackItem(optype.restype);
2309             }
2310         }
2311 
2312     public void visitTypeCast(JCTypeCast tree) {
2313         result = genExpr(tree.expr, tree.clazz.type).load();
2314         setTypeAnnotationPositions(tree.pos);
2315         // Additional code is only needed if we cast to a reference type
2316         // which is not statically a supertype of the expression's type.
2317         // For basic types, the coerce(...) in genExpr(...) will do
2318         // the conversion.
2319         if (!tree.clazz.type.isPrimitive() &&
2320            !types.isSameType(tree.expr.type, tree.clazz.type) &&
2321            types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
2322             code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass);
2323         }
2324     }
2325 
2326     public void visitWildcard(JCWildcard tree) {
2327         throw new AssertionError(this.getClass().getName());
2328     }
2329 
2330     public void visitTypeTest(JCInstanceOf tree) {
2331         genExpr(tree.expr, tree.expr.type).load();
2332         setTypeAnnotationPositions(tree.pos);
2333         code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type));
2334         result = items.makeStackItem(syms.booleanType);
2335     }
2336 
2337     public void visitIndexed(JCArrayAccess tree) {
2338         genExpr(tree.indexed, tree.indexed.type).load();
2339         genExpr(tree.index, syms.intType).load();
2340         result = items.makeIndexedItem(tree.type);
2341     }
2342 
2343     public void visitIdent(JCIdent tree) {
2344         Symbol sym = tree.sym;
2345         if (tree.name == names._this || tree.name == names._super) {
2346             Item res = tree.name == names._this
2347                 ? items.makeThisItem()
2348                 : items.makeSuperItem();
2349             if (sym.kind == MTH) {
2350                 // Generate code to address the constructor.
2351                 res.load();
2352                 res = items.makeMemberItem(sym, true);
2353             }
2354             result = res;
2355        } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) {
2356             if (isConstantDynamic(sym)) {
2357                 setTypeAnnotationPositions(tree.pos);
2358             }
2359             result = items.makeDynamicItem(sym);
2360         } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) {
2361             result = items.makeLocalItem((VarSymbol)sym);
2362         } else if ((sym.flags() & STATIC) != 0) {
2363             if (!isAccessSuper(env.enclMethod))
2364                 sym = binaryQualifier(sym, env.enclClass.type);
2365             result = items.makeStaticItem(sym);
2366         } else {
2367             items.makeThisItem().load();
2368             sym = binaryQualifier(sym, env.enclClass.type);
2369             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2370         }
2371     }
2372 
2373     //where
2374     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2375         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2376                              !disableVirtualizedPrivateInvoke;
2377         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2378     }
2379 
2380     public void visitSelect(JCFieldAccess tree) {
2381         Symbol sym = tree.sym;
2382 
2383         if (tree.name == names._class) {
2384             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2385             result = items.makeStackItem(pt);
2386             return;
2387         }
2388 
2389         Symbol ssym = TreeInfo.symbol(tree.selected);
2390 
2391         // Are we selecting via super?
2392         boolean selectSuper =
2393             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2394 
2395         // Are we accessing a member of the superclass in an access method
2396         // resulting from a qualified super?
2397         boolean accessSuper = isAccessSuper(env.enclMethod);
2398 
2399         Item base = (selectSuper)
2400             ? items.makeSuperItem()
2401             : genExpr(tree.selected, tree.selected.type);
2402 
2403         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2404             // We are seeing a variable that is constant but its selecting
2405             // expression is not.
2406             if ((sym.flags() & STATIC) != 0) {
2407                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2408                     base = base.load();
2409                 base.drop();
2410             } else {
2411                 base.load();
2412                 genNullCheck(tree.selected);
2413             }
2414             result = items.
2415                 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue());
2416         } else {
2417             if (isInvokeDynamic(sym)) {
2418                 result = items.makeDynamicItem(sym);
2419                 return;
2420             } else {
2421                 sym = binaryQualifier(sym, tree.selected.type);
2422             }
2423             if ((sym.flags() & STATIC) != 0) {
2424                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2425                     base = base.load();
2426                 base.drop();
2427                 result = items.makeStaticItem(sym);
2428             } else {
2429                 base.load();
2430                 if (sym == syms.lengthVar) {
2431                     code.emitop0(arraylength);
2432                     result = items.makeStackItem(syms.intType);
2433                 } else {
2434                     result = items.
2435                         makeMemberItem(sym,
2436                                        nonVirtualForPrivateAccess(sym) ||
2437                                        selectSuper || accessSuper);
2438                 }
2439             }
2440         }
2441     }
2442 
2443     public boolean isInvokeDynamic(Symbol sym) {
2444         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
2445     }
2446 
2447     public void visitLiteral(JCLiteral tree) {
2448         if (tree.type.hasTag(BOT)) {
2449             code.emitop0(aconst_null);
2450             result = items.makeStackItem(tree.type);
2451         }
2452         else
2453             result = items.makeImmediateItem(tree.type, tree.value);
2454     }
2455 
2456     public void visitLetExpr(LetExpr tree) {
2457         code.resolvePending();
2458 
2459         int limit = code.nextreg;
2460         int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
2461         try {
2462             genStats(tree.defs, env);
2463         } finally {
2464             code.setLetExprStackPos(prevLetExprStart);
2465         }
2466         result = genExpr(tree.expr, tree.expr.type).load();
2467         code.endScopes(limit);
2468     }
2469 
2470     private void generateReferencesToPrunedTree(ClassSymbol classSymbol) {
2471         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
2472         if (prunedInfo != null) {
2473             for (JCTree prunedTree: prunedInfo) {
2474                 prunedTree.accept(classReferenceVisitor);
2475             }
2476         }
2477     }
2478 
2479 /* ************************************************************************
2480  * main method
2481  *************************************************************************/
2482 
2483     /** Generate code for a class definition.
2484      *  @param env   The attribution environment that belongs to the
2485      *               outermost class containing this class definition.
2486      *               We need this for resolving some additional symbols.
2487      *  @param cdef  The tree representing the class definition.
2488      *  @return      True if code is generated with no errors.
2489      */
2490     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
2491         try {
2492             attrEnv = env;
2493             ClassSymbol c = cdef.sym;
2494             this.toplevel = env.toplevel;
2495             this.endPosTable = toplevel.endPositions;
2496             /* method normalizeDefs() can add references to external classes into the constant pool
2497              */
2498             cdef.defs = normalizeDefs(cdef.defs, c);
2499             generateReferencesToPrunedTree(c);
2500             Env<GenContext> localEnv = new Env<>(cdef, new GenContext());
2501             localEnv.toplevel = env.toplevel;
2502             localEnv.enclClass = cdef;
2503 
2504             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2505                 genDef(l.head, localEnv);
2506             }
2507             if (poolWriter.size() > PoolWriter.MAX_ENTRIES) {
2508                 log.error(cdef.pos(), Errors.LimitPool);
2509                 nerrs++;
2510             }
2511             if (nerrs != 0) {
2512                 // if errors, discard code
2513                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2514                     if (l.head.hasTag(METHODDEF))
2515                         ((JCMethodDecl) l.head).sym.code = null;
2516                 }
2517             }
2518             cdef.defs = List.nil(); // discard trees
2519             return nerrs == 0;
2520         } finally {
2521             // note: this method does NOT support recursion.
2522             attrEnv = null;
2523             this.env = null;
2524             toplevel = null;
2525             endPosTable = null;
2526             nerrs = 0;
2527             qualifiedSymbolCache.clear();
2528         }
2529     }
2530 
2531 /* ************************************************************************
2532  * Auxiliary classes
2533  *************************************************************************/
2534 
2535     /** An abstract class for finalizer generation.
2536      */
2537     abstract class GenFinalizer {
2538         /** Generate code to clean up when unwinding. */
2539         abstract void gen();
2540 
2541         /** Generate code to clean up at last. */
2542         abstract void genLast();
2543 
2544         /** Does this finalizer have some nontrivial cleanup to perform? */
2545         boolean hasFinalizer() { return true; }
2546 
2547         /** Should be invoked after the try's body has been visited. */
2548         void afterBody() {}
2549     }
2550 
2551     /** code generation contexts,
2552      *  to be used as type parameter for environments.
2553      */
2554     static class GenContext {
2555 
2556         /** A chain for all unresolved jumps that exit the current environment.
2557          */
2558         Chain exit = null;
2559 
2560         /** A chain for all unresolved jumps that continue in the
2561          *  current environment.
2562          */
2563         Chain cont = null;
2564 
2565         /** A closure that generates the finalizer of the current environment.
2566          *  Only set for Synchronized and Try contexts.
2567          */
2568         GenFinalizer finalize = null;
2569 
2570         /** Is this a switch statement?  If so, allocate registers
2571          * even when the variable declaration is unreachable.
2572          */
2573         boolean isSwitch = false;
2574 
2575         /** A list buffer containing all gaps in the finalizer range,
2576          *  where a catch all exception should not apply.
2577          */
2578         ListBuffer<Integer> gaps = null;
2579 
2580         /** Add given chain to exit chain.
2581          */
2582         void addExit(Chain c)  {
2583             exit = Code.mergeChains(c, exit);
2584         }
2585 
2586         /** Add given chain to cont chain.
2587          */
2588         void addCont(Chain c) {
2589             cont = Code.mergeChains(c, cont);
2590         }
2591     }
2592 
2593 }