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