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