1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.jvm;
  27 
  28 import java.util.HashMap;
  29 import java.util.Map;
  30 import java.util.Set;
  31 
  32 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
  33 import com.sun.tools.javac.tree.TreeInfo.PosKind;
  34 import com.sun.tools.javac.util.*;
  35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  36 import com.sun.tools.javac.util.List;
  37 import com.sun.tools.javac.code.*;
  38 import com.sun.tools.javac.code.Attribute.TypeCompound;
  39 import com.sun.tools.javac.code.Symbol.VarSymbol;
  40 import com.sun.tools.javac.comp.*;
  41 import com.sun.tools.javac.tree.*;
  42 
  43 import com.sun.tools.javac.code.Symbol.*;
  44 import com.sun.tools.javac.code.Type.*;
  45 import com.sun.tools.javac.jvm.Code.*;
  46 import com.sun.tools.javac.jvm.Items.*;
  47 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  48 import com.sun.tools.javac.tree.EndPosTable;
  49 import com.sun.tools.javac.tree.JCTree.*;
  50 
  51 import static com.sun.tools.javac.code.Flags.*;
  52 import static com.sun.tools.javac.code.Kinds.Kind.*;
  53 import static com.sun.tools.javac.code.TypeTag.*;
  54 import static com.sun.tools.javac.jvm.ByteCodes.*;
  55 import static com.sun.tools.javac.jvm.CRTFlags.*;
  56 import static com.sun.tools.javac.main.Option.*;
  57 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  58 
  59 /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
  60  *
  61  *  <p><b>This is NOT part of any supported API.
  62  *  If you write code that depends on this, you do so at your own risk.
  63  *  This code and its internal interfaces are subject to change or
  64  *  deletion without notice.</b>
  65  */
  66 public class Gen extends JCTree.Visitor {

  67     protected static final Context.Key<Gen> genKey = new Context.Key<>();
  68 
  69     private final Log log;
  70     private final Symtab syms;
  71     private final Check chk;
  72     private final Resolve rs;
  73     private final TreeMaker make;
  74     private final Names names;
  75     private final Target target;
  76     private final String accessDollar;
  77     private final Types types;
  78     private final Lower lower;
  79     private final Annotate annotate;
  80     private final StringConcat concat;

  81 
  82     /** Format of stackmap tables to be generated. */
  83     private final Code.StackMapFormat stackMap;
  84 
  85     /** A type that serves as the expected type for all method expressions.
  86      */
  87     private final Type methodType;
  88 
  89     public static Gen instance(Context context) {
  90         Gen instance = context.get(genKey);
  91         if (instance == null)
  92             instance = new Gen(context);
  93         return instance;
  94     }
  95 
  96     /** Constant pool writer, set by genClass.
  97      */
  98     final PoolWriter poolWriter;
  99 
 100     @SuppressWarnings("this-escape")
 101     protected Gen(Context context) {
 102         context.put(genKey, this);
 103 
 104         names = Names.instance(context);
 105         log = Log.instance(context);
 106         syms = Symtab.instance(context);
 107         chk = Check.instance(context);
 108         rs = Resolve.instance(context);
 109         make = TreeMaker.instance(context);
 110         target = Target.instance(context);
 111         types = Types.instance(context);
 112         concat = StringConcat.instance(context);
 113 
 114         methodType = new MethodType(null, null, null, syms.methodClass);
 115         accessDollar = "access" + target.syntheticNameChar();
 116         lower = Lower.instance(context);

 117 
 118         Options options = Options.instance(context);
 119         lineDebugInfo =
 120             options.isUnset(G_CUSTOM) ||
 121             options.isSet(G_CUSTOM, "lines");
 122         varDebugInfo =
 123             options.isUnset(G_CUSTOM)
 124             ? options.isSet(G)
 125             : options.isSet(G_CUSTOM, "vars");
 126         genCrt = options.isSet(XJCOV);
 127         debugCode = options.isSet("debug.code");
 128         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 129         poolWriter = new PoolWriter(types, names);
 130 
 131         // ignore cldc because we cannot have both stackmap formats
 132         this.stackMap = StackMapFormat.JSR202;
 133         annotate = Annotate.instance(context);


 134         qualifiedSymbolCache = new HashMap<>();
 135     }
 136 
 137     /** Switches
 138      */
 139     private final boolean lineDebugInfo;
 140     private final boolean varDebugInfo;
 141     private final boolean genCrt;
 142     private final boolean debugCode;
 143     private boolean disableVirtualizedPrivateInvoke;
 144 
 145     /** Code buffer, set by genMethod.
 146      */
 147     private Code code;
 148 
 149     /** Items structure, set by genMethod.
 150      */
 151     private Items items;
 152 
 153     /** Environment for symbol lookup, set by genClass
 154      */
 155     private Env<AttrContext> attrEnv;
 156 
 157     /** The top level tree.
 158      */
 159     private JCCompilationUnit toplevel;
 160 
 161     /** The number of code-gen errors in this class.
 162      */
 163     private int nerrs = 0;
 164 
 165     /** An object containing mappings of syntax trees to their
 166      *  ending source positions.
 167      */
 168     EndPosTable endPosTable;
 169 
 170     boolean inCondSwitchExpression;
 171     Chain switchExpressionTrueChain;
 172     Chain switchExpressionFalseChain;
 173     List<LocalItem> stackBeforeSwitchExpression;
 174     LocalItem switchResult;
 175     Set<JCMethodInvocation> invocationsWithPatternMatchingCatch = Set.of();
 176     ListBuffer<int[]> patternMatchingInvocationRanges;
 177 


 178     /** Cache the symbol to reflect the qualifying type.
 179      *  key: corresponding type
 180      *  value: qualified symbol
 181      */
 182     Map<Type, Symbol> qualifiedSymbolCache;
 183 
 184     /** Generate code to load an integer constant.
 185      *  @param n     The integer to be loaded.
 186      */
 187     void loadIntConst(int n) {
 188         items.makeImmediateItem(syms.intType, n).load();
 189     }
 190 
 191     /** The opcode that loads a zero constant of a given type code.
 192      *  @param tc   The given type code (@see ByteCode).
 193      */
 194     public static int zero(int tc) {
 195         switch(tc) {
 196         case INTcode: case BYTEcode: case SHORTcode: case CHARcode:
 197             return iconst_0;
 198         case LONGcode:
 199             return lconst_0;
 200         case FLOATcode:
 201             return fconst_0;
 202         case DOUBLEcode:
 203             return dconst_0;
 204         default:
 205             throw new AssertionError("zero");
 206         }
 207     }
 208 
 209     /** The opcode that loads a one constant of a given type code.
 210      *  @param tc   The given type code (@see ByteCode).
 211      */
 212     public static int one(int tc) {
 213         return zero(tc) + 1;
 214     }
 215 
 216     /** Generate code to load -1 of the given type code (either int or long).
 217      *  @param tc   The given type code (@see ByteCode).
 218      */
 219     void emitMinusOne(int tc) {
 220         if (tc == LONGcode) {
 221             items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load();
 222         } else {
 223             code.emitop0(iconst_m1);
 224         }
 225     }
 226 
 227     /** Construct a symbol to reflect the qualifying type that should
 228      *  appear in the byte code as per JLS 13.1.
 229      *
 230      *  For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except
 231      *  for those cases where we need to work around VM bugs).
 232      *
 233      *  For {@literal target <= 1.1}: If qualified variable or method is defined in a
 234      *  non-accessible class, clone it with the qualifier class as owner.
 235      *
 236      *  @param sym    The accessed symbol
 237      *  @param site   The qualifier's type.
 238      */
 239     Symbol binaryQualifier(Symbol sym, Type site) {
 240 
 241         if (site.hasTag(ARRAY)) {
 242             if (sym == syms.lengthVar ||
 243                 sym.owner != syms.arrayClass)
 244                 return sym;
 245             // array clone can be qualified by the array type in later targets
 246             Symbol qualifier;
 247             if ((qualifier = qualifiedSymbolCache.get(site)) == null) {
 248                 qualifier = new ClassSymbol(Flags.PUBLIC, site.tsym.name, site, syms.noSymbol);
 249                 qualifiedSymbolCache.put(site, qualifier);
 250             }
 251             return sym.clone(qualifier);
 252         }
 253 
 254         if (sym.owner == site.tsym ||
 255             (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
 256             return sym;
 257         }
 258 
 259         // leave alone methods inherited from Object
 260         // JLS 13.1.
 261         if (sym.owner == syms.objectType.tsym)
 262             return sym;
 263 
 264         return sym.clone(site.tsym);
 265     }
 266 














 267     /** Insert a reference to given type in the constant pool,
 268      *  checking for an array with too many dimensions;
 269      *  return the reference's index.
 270      *  @param type   The type for which a reference is inserted.
 271      */
 272     int makeRef(DiagnosticPosition pos, Type type) {
 273         return poolWriter.putClass(checkDimension(pos, type));
 274     }
 275 
 276     /** Check if the given type is an array with too many dimensions.
 277      */
 278     private Type checkDimension(DiagnosticPosition pos, Type t) {
 279         checkDimensionInternal(pos, t);
 280         return t;
 281     }
 282 
 283     private void checkDimensionInternal(DiagnosticPosition pos, Type t) {
 284         switch (t.getTag()) {
 285         case METHOD:
 286             checkDimension(pos, t.getReturnType());
 287             for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
 288                 checkDimension(pos, args.head);
 289             break;
 290         case ARRAY:
 291             if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
 292                 log.error(pos, Errors.LimitDimensions);
 293                 nerrs++;
 294             }
 295             break;
 296         default:
 297             break;
 298         }
 299     }
 300 
 301     /** Create a temporary variable.
 302      *  @param type   The variable's type.
 303      */
 304     LocalItem makeTemp(Type type) {
 305         VarSymbol v = new VarSymbol(Flags.SYNTHETIC,
 306                                     names.empty,
 307                                     type,
 308                                     env.enclMethod.sym);
 309         code.newLocal(v);
 310         return items.makeLocalItem(v);
 311     }
 312 
 313     /** Generate code to call a non-private method or constructor.
 314      *  @param pos         Position to be used for error reporting.
 315      *  @param site        The type of which the method is a member.
 316      *  @param name        The method's name.
 317      *  @param argtypes    The method's argument types.
 318      *  @param isStatic    A flag that indicates whether we call a
 319      *                     static or instance method.
 320      */
 321     void callMethod(DiagnosticPosition pos,
 322                     Type site, Name name, List<Type> argtypes,
 323                     boolean isStatic) {
 324         Symbol msym = rs.
 325             resolveInternalMethod(pos, attrEnv, site, name, argtypes, null);
 326         if (isStatic) items.makeStaticItem(msym).invoke();
 327         else items.makeMemberItem(msym, name == names.init).invoke();
 328     }
 329 
 330     /** Is the given method definition an access method
 331      *  resulting from a qualified super? This is signified by an odd
 332      *  access code.
 333      */
 334     private boolean isAccessSuper(JCMethodDecl enclMethod) {
 335         return
 336             (enclMethod.mods.flags & SYNTHETIC) != 0 &&
 337             isOddAccessName(enclMethod.name);
 338     }
 339 
 340     /** Does given name start with "access$" and end in an odd digit?
 341      */
 342     private boolean isOddAccessName(Name name) {
 343         final String string = name.toString();
 344         return
 345             string.startsWith(accessDollar) &&
 346             (string.charAt(string.length() - 1) & 1) != 0;
 347     }
 348 
 349 /* ************************************************************************
 350  * Non-local exits
 351  *************************************************************************/
 352 
 353     /** Generate code to invoke the finalizer associated with given
 354      *  environment.
 355      *  Any calls to finalizers are appended to the environments `cont' chain.
 356      *  Mark beginning of gap in catch all range for finalizer.
 357      */
 358     void genFinalizer(Env<GenContext> env) {
 359         if (code.isAlive() && env.info.finalize != null)
 360             env.info.finalize.gen();
 361     }
 362 
 363     /** Generate code to call all finalizers of structures aborted by
 364      *  a non-local
 365      *  exit.  Return target environment of the non-local exit.
 366      *  @param target      The tree representing the structure that's aborted
 367      *  @param env         The environment current at the non-local exit.
 368      */
 369     Env<GenContext> unwind(JCTree target, Env<GenContext> env) {
 370         Env<GenContext> env1 = env;
 371         while (true) {
 372             genFinalizer(env1);
 373             if (env1.tree == target) break;
 374             env1 = env1.next;
 375         }
 376         return env1;
 377     }
 378 
 379     /** Mark end of gap in catch-all range for finalizer.
 380      *  @param env   the environment which might contain the finalizer
 381      *               (if it does, env.info.gaps != null).
 382      */
 383     void endFinalizerGap(Env<GenContext> env) {
 384         if (env.info.gaps != null && env.info.gaps.length() % 2 == 1)
 385             env.info.gaps.append(code.curCP());
 386     }
 387 
 388     /** Mark end of all gaps in catch-all ranges for finalizers of environments
 389      *  lying between, and including to two environments.
 390      *  @param from    the most deeply nested environment to mark
 391      *  @param to      the least deeply nested environment to mark
 392      */
 393     void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) {
 394         Env<GenContext> last = null;
 395         while (last != to) {
 396             endFinalizerGap(from);
 397             last = from;
 398             from = from.next;
 399         }
 400     }
 401 
 402     /** Do any of the structures aborted by a non-local exit have
 403      *  finalizers that require an empty stack?
 404      *  @param target      The tree representing the structure that's aborted
 405      *  @param env         The environment current at the non-local exit.
 406      */
 407     boolean hasFinally(JCTree target, Env<GenContext> env) {
 408         while (env.tree != target) {
 409             if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
 410                 return true;
 411             env = env.next;
 412         }
 413         return false;
 414     }
 415 
 416 /* ************************************************************************
 417  * Normalizing class-members.
 418  *************************************************************************/
 419 
 420     /** Distribute member initializer code into constructors and {@code <clinit>}
 421      *  method.
 422      *  @param defs         The list of class member declarations.
 423      *  @param c            The enclosing class.
 424      */
 425     List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
 426         ListBuffer<JCStatement> initCode = new ListBuffer<>();
 427         ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
 428         ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
 429         ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
 430         ListBuffer<JCTree> methodDefs = new ListBuffer<>();
 431         // Sort definitions into three listbuffers:
 432         //  - initCode for instance initializers
 433         //  - clinitCode for class initializers
 434         //  - methodDefs for method definitions
 435         for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
 436             JCTree def = l.head;
 437             switch (def.getTag()) {
 438             case BLOCK:
 439                 JCBlock block = (JCBlock)def;
 440                 if ((block.flags & STATIC) != 0)
 441                     clinitCode.append(block);
 442                 else if ((block.flags & SYNTHETIC) == 0)
 443                     initCode.append(block);
 444                 break;
 445             case METHODDEF:
 446                 methodDefs.append(def);
 447                 break;
 448             case VARDEF:
 449                 JCVariableDecl vdef = (JCVariableDecl) def;
 450                 VarSymbol sym = vdef.sym;
 451                 checkDimension(vdef.pos(), sym.type);
 452                 if (vdef.init != null) {
 453                     if ((sym.flags() & STATIC) == 0) {
 454                         // Always initialize instance variables.
 455                         JCStatement init = make.at(vdef.pos()).
 456                             Assignment(sym, vdef.init);
 457                         initCode.append(init);
 458                         endPosTable.replaceTree(vdef, init);
 459                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
 460                     } else if (sym.getConstValue() == null) {
 461                         // Initialize class (static) variables only if
 462                         // they are not compile-time constants.
 463                         JCStatement init = make.at(vdef.pos).
 464                             Assignment(sym, vdef.init);
 465                         clinitCode.append(init);
 466                         endPosTable.replaceTree(vdef, init);
 467                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
 468                     } else {
 469                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
 470                         /* if the init contains a reference to an external class, add it to the
 471                          * constant's pool
 472                          */
 473                         vdef.init.accept(classReferenceVisitor);
 474                     }
 475                 }
 476                 break;
 477             default:
 478                 Assert.error();
 479             }
 480         }
 481         // Insert any instance initializers into all constructors.
 482         if (initCode.length() != 0) {
 483             List<JCStatement> inits = initCode.toList();
 484             initTAs.addAll(c.getInitTypeAttributes());
 485             List<Attribute.TypeCompound> initTAlist = initTAs.toList();
 486             for (JCTree t : methodDefs) {
 487                 normalizeMethod((JCMethodDecl)t, inits, initTAlist);
 488             }
 489         }
 490         // If there are class initializers, create a <clinit> method
 491         // that contains them as its body.
 492         if (clinitCode.length() != 0) {
 493             MethodSymbol clinit = new MethodSymbol(
 494                 STATIC | (c.flags() & STRICTFP),
 495                 names.clinit,
 496                 new MethodType(
 497                     List.nil(), syms.voidType,
 498                     List.nil(), syms.methodClass),
 499                 c);
 500             c.members().enter(clinit);
 501             List<JCStatement> clinitStats = clinitCode.toList();
 502             JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
 503             block.endpos = TreeInfo.endPos(clinitStats.last());
 504             methodDefs.append(make.MethodDef(clinit, block));
 505 
 506             if (!clinitTAs.isEmpty())
 507                 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
 508             if (!c.getClassInitTypeAttributes().isEmpty())
 509                 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes());
 510         }
 511         // Return all method definitions.
 512         return methodDefs.toList();
 513     }
 514 
 515     private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) {
 516         List<TypeCompound> tas = sym.getRawTypeAttributes();
 517         ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<>();
 518         ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>();
 519         for (TypeCompound ta : tas) {
 520             Assert.check(ta.getPosition().type != TargetType.UNKNOWN);
 521             if (ta.getPosition().type == TargetType.FIELD) {
 522                 fieldTAs.add(ta);
 523             } else {
 524                 nonfieldTAs.add(ta);
 525             }
 526         }
 527         sym.setTypeAttributes(fieldTAs.toList());
 528         return nonfieldTAs.toList();
 529     }
 530 
 531     /** Check a constant value and report if it is a string that is
 532      *  too large.
 533      */
 534     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
 535         if (nerrs != 0 || // only complain about a long string once
 536             constValue == null ||
 537             !(constValue instanceof String str) ||
 538             str.length() < PoolWriter.MAX_STRING_LENGTH)
 539             return;
 540         log.error(pos, Errors.LimitString);
 541         nerrs++;
 542     }
 543 
 544     /** Insert instance initializer code into initial constructor.
 545      *  @param md        The tree potentially representing a
 546      *                   constructor's definition.
 547      *  @param initCode  The list of instance initializer statements.
 548      *  @param initTAs  Type annotations from the initializer expression.
 549      */
 550     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
 551         if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
 552             // We are seeing a constructor that does not call another
 553             // constructor of the same class.
 554             List<JCStatement> stats = md.body.stats;
 555             ListBuffer<JCStatement> newstats = new ListBuffer<>();
 556 
 557             if (stats.nonEmpty()) {
 558                 // Copy initializers of synthetic variables generated in
 559                 // the translation of inner classes.
 560                 while (TreeInfo.isSyntheticInit(stats.head)) {
 561                     newstats.append(stats.head);
 562                     stats = stats.tail;
 563                 }
 564                 // Copy superclass constructor call
 565                 newstats.append(stats.head);
 566                 stats = stats.tail;
 567                 // Copy remaining synthetic initializers.
 568                 while (stats.nonEmpty() &&
 569                        TreeInfo.isSyntheticInit(stats.head)) {
 570                     newstats.append(stats.head);
 571                     stats = stats.tail;
 572                 }
 573                 // Now insert the initializer code.
 574                 newstats.appendList(initCode);
 575                 // And copy all remaining statements.
 576                 while (stats.nonEmpty()) {
 577                     newstats.append(stats.head);
 578                     stats = stats.tail;
 579                 }
 580             }
 581             md.body.stats = newstats.toList();
 582             if (md.body.endpos == Position.NOPOS)
 583                 md.body.endpos = TreeInfo.endPos(md.body.stats.last());
 584 
 585             md.sym.appendUniqueTypeAttributes(initTAs);
 586         }
 587     }
 588 
 589 /* ************************************************************************
 590  * Traversal methods
 591  *************************************************************************/
 592 
 593     /** Visitor argument: The current environment.
 594      */
 595     Env<GenContext> env;
 596 
 597     /** Visitor argument: The expected type (prototype).
 598      */
 599     Type pt;
 600 
 601     /** Visitor result: The item representing the computed value.
 602      */
 603     Item result;
 604 
 605     /** Visitor method: generate code for a definition, catching and reporting
 606      *  any completion failures.
 607      *  @param tree    The definition to be visited.
 608      *  @param env     The environment current at the definition.
 609      */
 610     public void genDef(JCTree tree, Env<GenContext> env) {
 611         Env<GenContext> prevEnv = this.env;
 612         try {
 613             this.env = env;
 614             tree.accept(this);
 615         } catch (CompletionFailure ex) {
 616             chk.completionError(tree.pos(), ex);
 617         } finally {
 618             this.env = prevEnv;
 619         }
 620     }
 621 
 622     /** Derived visitor method: check whether CharacterRangeTable
 623      *  should be emitted, if so, put a new entry into CRTable
 624      *  and call method to generate bytecode.
 625      *  If not, just call method to generate bytecode.
 626      *  @see    #genStat(JCTree, Env)
 627      *
 628      *  @param  tree     The tree to be visited.
 629      *  @param  env      The environment to use.
 630      *  @param  crtFlags The CharacterRangeTable flags
 631      *                   indicating type of the entry.
 632      */
 633     public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) {
 634         if (!genCrt) {
 635             genStat(tree, env);
 636             return;
 637         }
 638         int startpc = code.curCP();
 639         genStat(tree, env);
 640         if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK;
 641         code.crt.put(tree, crtFlags, startpc, code.curCP());
 642     }
 643 
 644     /** Derived visitor method: generate code for a statement.
 645      */
 646     public void genStat(JCTree tree, Env<GenContext> env) {
 647         if (code.isAlive()) {
 648             code.statBegin(tree.pos);
 649             genDef(tree, env);
 650         } else if (env.info.isSwitch && tree.hasTag(VARDEF)) {
 651             // variables whose declarations are in a switch
 652             // can be used even if the decl is unreachable.
 653             code.newLocal(((JCVariableDecl) tree).sym);
 654         }
 655     }
 656 
 657     /** Derived visitor method: check whether CharacterRangeTable
 658      *  should be emitted, if so, put a new entry into CRTable
 659      *  and call method to generate bytecode.
 660      *  If not, just call method to generate bytecode.
 661      *  @see    #genStats(List, Env)
 662      *
 663      *  @param  trees    The list of trees to be visited.
 664      *  @param  env      The environment to use.
 665      *  @param  crtFlags The CharacterRangeTable flags
 666      *                   indicating type of the entry.
 667      */
 668     public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) {
 669         if (!genCrt) {
 670             genStats(trees, env);
 671             return;
 672         }
 673         if (trees.length() == 1) {        // mark one statement with the flags
 674             genStat(trees.head, env, crtFlags | CRT_STATEMENT);
 675         } else {
 676             int startpc = code.curCP();
 677             genStats(trees, env);
 678             code.crt.put(trees, crtFlags, startpc, code.curCP());
 679         }
 680     }
 681 
 682     /** Derived visitor method: generate code for a list of statements.
 683      */
 684     public void genStats(List<? extends JCTree> trees, Env<GenContext> env) {
 685         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
 686             genStat(l.head, env, CRT_STATEMENT);
 687     }
 688 
 689     /** Derived visitor method: check whether CharacterRangeTable
 690      *  should be emitted, if so, put a new entry into CRTable
 691      *  and call method to generate bytecode.
 692      *  If not, just call method to generate bytecode.
 693      *  @see    #genCond(JCTree,boolean)
 694      *
 695      *  @param  tree     The tree to be visited.
 696      *  @param  crtFlags The CharacterRangeTable flags
 697      *                   indicating type of the entry.
 698      */
 699     public CondItem genCond(JCTree tree, int crtFlags) {
 700         if (!genCrt) return genCond(tree, false);
 701         int startpc = code.curCP();
 702         CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0);
 703         code.crt.put(tree, crtFlags, startpc, code.curCP());
 704         return item;
 705     }
 706 
 707     /** Derived visitor method: generate code for a boolean
 708      *  expression in a control-flow context.
 709      *  @param _tree         The expression to be visited.
 710      *  @param markBranches The flag to indicate that the condition is
 711      *                      a flow controller so produced conditions
 712      *                      should contain a proper tree to generate
 713      *                      CharacterRangeTable branches for them.
 714      */
 715     public CondItem genCond(JCTree _tree, boolean markBranches) {
 716         JCTree inner_tree = TreeInfo.skipParens(_tree);
 717         if (inner_tree.hasTag(CONDEXPR)) {
 718             JCConditional tree = (JCConditional)inner_tree;
 719             CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER);
 720             if (cond.isTrue()) {
 721                 code.resolve(cond.trueJumps);
 722                 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET);
 723                 if (markBranches) result.tree = tree.truepart;
 724                 return result;
 725             }
 726             if (cond.isFalse()) {
 727                 code.resolve(cond.falseJumps);
 728                 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET);
 729                 if (markBranches) result.tree = tree.falsepart;
 730                 return result;
 731             }
 732             Chain secondJumps = cond.jumpFalse();
 733             code.resolve(cond.trueJumps);
 734             CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET);
 735             if (markBranches) first.tree = tree.truepart;
 736             Chain falseJumps = first.jumpFalse();
 737             code.resolve(first.trueJumps);
 738             Chain trueJumps = code.branch(goto_);
 739             code.resolve(secondJumps);
 740             CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET);
 741             CondItem result = items.makeCondItem(second.opcode,
 742                                       Code.mergeChains(trueJumps, second.trueJumps),
 743                                       Code.mergeChains(falseJumps, second.falseJumps));
 744             if (markBranches) result.tree = tree.falsepart;
 745             return result;
 746         } else if (inner_tree.hasTag(SWITCH_EXPRESSION)) {
 747             code.resolvePending();
 748 
 749             boolean prevInCondSwitchExpression = inCondSwitchExpression;
 750             Chain prevSwitchExpressionTrueChain = switchExpressionTrueChain;
 751             Chain prevSwitchExpressionFalseChain = switchExpressionFalseChain;
 752             try {
 753                 inCondSwitchExpression = true;
 754                 switchExpressionTrueChain = null;
 755                 switchExpressionFalseChain = null;
 756                 try {
 757                     doHandleSwitchExpression((JCSwitchExpression) inner_tree);
 758                 } catch (CompletionFailure ex) {
 759                     chk.completionError(_tree.pos(), ex);
 760                     code.state.stacksize = 1;
 761                 }
 762                 CondItem result = items.makeCondItem(goto_,
 763                                                      switchExpressionTrueChain,
 764                                                      switchExpressionFalseChain);
 765                 if (markBranches) result.tree = _tree;
 766                 return result;
 767             } finally {
 768                 inCondSwitchExpression = prevInCondSwitchExpression;
 769                 switchExpressionTrueChain = prevSwitchExpressionTrueChain;
 770                 switchExpressionFalseChain = prevSwitchExpressionFalseChain;
 771             }
 772         } else if (inner_tree.hasTag(LETEXPR) && ((LetExpr) inner_tree).needsCond) {
 773             code.resolvePending();
 774 
 775             LetExpr tree = (LetExpr) inner_tree;
 776             int limit = code.nextreg;
 777             int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
 778             try {
 779                 genStats(tree.defs, env);
 780             } finally {
 781                 code.setLetExprStackPos(prevLetExprStart);
 782             }
 783             CondItem result = genCond(tree.expr, markBranches);
 784             code.endScopes(limit);
 785             return result;
 786         } else {
 787             CondItem result = genExpr(_tree, syms.booleanType).mkCond();
 788             if (markBranches) result.tree = _tree;
 789             return result;
 790         }
 791     }
 792 
 793     public Code getCode() {
 794         return code;
 795     }
 796 
 797     public Items getItems() {
 798         return items;
 799     }
 800 
 801     public Env<AttrContext> getAttrEnv() {
 802         return attrEnv;
 803     }
 804 
 805     /** Visitor class for expressions which might be constant expressions.
 806      *  This class is a subset of TreeScanner. Intended to visit trees pruned by
 807      *  Lower as long as constant expressions looking for references to any
 808      *  ClassSymbol. Any such reference will be added to the constant pool so
 809      *  automated tools can detect class dependencies better.
 810      */
 811     class ClassReferenceVisitor extends JCTree.Visitor {
 812 
 813         @Override
 814         public void visitTree(JCTree tree) {}
 815 
 816         @Override
 817         public void visitBinary(JCBinary tree) {
 818             tree.lhs.accept(this);
 819             tree.rhs.accept(this);
 820         }
 821 
 822         @Override
 823         public void visitSelect(JCFieldAccess tree) {
 824             if (tree.selected.type.hasTag(CLASS)) {
 825                 makeRef(tree.selected.pos(), tree.selected.type);
 826             }
 827         }
 828 
 829         @Override
 830         public void visitIdent(JCIdent tree) {
 831             if (tree.sym.owner instanceof ClassSymbol classSymbol) {
 832                 poolWriter.putClass(classSymbol);
 833             }
 834         }
 835 
 836         @Override
 837         public void visitConditional(JCConditional tree) {
 838             tree.cond.accept(this);
 839             tree.truepart.accept(this);
 840             tree.falsepart.accept(this);
 841         }
 842 
 843         @Override
 844         public void visitUnary(JCUnary tree) {
 845             tree.arg.accept(this);
 846         }
 847 
 848         @Override
 849         public void visitParens(JCParens tree) {
 850             tree.expr.accept(this);
 851         }
 852 
 853         @Override
 854         public void visitTypeCast(JCTypeCast tree) {
 855             tree.expr.accept(this);
 856         }
 857     }
 858 
 859     private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor();
 860 
 861     /** Visitor method: generate code for an expression, catching and reporting
 862      *  any completion failures.
 863      *  @param tree    The expression to be visited.
 864      *  @param pt      The expression's expected type (proto-type).
 865      */
 866     public Item genExpr(JCTree tree, Type pt) {
 867         if (!code.isAlive()) {
 868             return items.makeStackItem(pt);
 869         }
 870 
 871         Type prevPt = this.pt;
 872         try {
 873             if (tree.type.constValue() != null) {
 874                 // Short circuit any expressions which are constants
 875                 tree.accept(classReferenceVisitor);
 876                 checkStringConstant(tree.pos(), tree.type.constValue());
 877                 Symbol sym = TreeInfo.symbol(tree);
 878                 if (sym != null && isConstantDynamic(sym)) {
 879                     result = items.makeDynamicItem(sym);
 880                 } else {
 881                     result = items.makeImmediateItem(tree.type, tree.type.constValue());
 882                 }
 883             } else {
 884                 this.pt = pt;
 885                 tree.accept(this);
 886             }
 887             return result.coerce(pt);
 888         } catch (CompletionFailure ex) {
 889             chk.completionError(tree.pos(), ex);
 890             code.state.stacksize = 1;
 891             return items.makeStackItem(pt);
 892         } finally {
 893             this.pt = prevPt;
 894         }
 895     }
 896 
 897     public boolean isConstantDynamic(Symbol sym) {
 898         return sym.kind == VAR &&
 899                 sym instanceof DynamicVarSymbol dynamicVarSymbol &&
 900                 dynamicVarSymbol.isDynamic();
 901     }
 902 
 903     /** Derived visitor method: generate code for a list of method arguments.
 904      *  @param trees    The argument expressions to be visited.
 905      *  @param pts      The expression's expected types (i.e. the formal parameter
 906      *                  types of the invoked method).
 907      */
 908     public void genArgs(List<JCExpression> trees, List<Type> pts) {
 909         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
 910             genExpr(l.head, pts.head).load();
 911             pts = pts.tail;
 912         }
 913         // require lists be of same length
 914         Assert.check(pts.isEmpty());
 915     }
 916 
 917 /* ************************************************************************
 918  * Visitor methods for statements and definitions
 919  *************************************************************************/
 920 
 921     /** Thrown when the byte code size exceeds limit.
 922      */
 923     public static class CodeSizeOverflow extends RuntimeException {
 924         private static final long serialVersionUID = 0;
 925         public CodeSizeOverflow() {}
 926     }
 927 
 928     public void visitMethodDef(JCMethodDecl tree) {
 929         // Create a new local environment that points pack at method
 930         // definition.
 931         Env<GenContext> localEnv = env.dup(tree);
 932         localEnv.enclMethod = tree;
 933         // The expected type of every return statement in this method
 934         // is the method's return type.
 935         this.pt = tree.sym.erasure(types).getReturnType();
 936 
 937         checkDimension(tree.pos(), tree.sym.erasure(types));
 938         genMethod(tree, localEnv, false);
 939     }
 940 //where
 941         /** Generate code for a method.
 942          *  @param tree     The tree representing the method definition.
 943          *  @param env      The environment current for the method body.
 944          *  @param fatcode  A flag that indicates whether all jumps are
 945          *                  within 32K.  We first invoke this method under
 946          *                  the assumption that fatcode == false, i.e. all
 947          *                  jumps are within 32K.  If this fails, fatcode
 948          *                  is set to true and we try again.
 949          */
 950         void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
 951             MethodSymbol meth = tree.sym;
 952             int extras = 0;
 953             // Count up extra parameters
 954             if (meth.isConstructor()) {
 955                 extras++;
 956                 if (meth.enclClass().isInner() &&
 957                     !meth.enclClass().isStatic()) {
 958                     extras++;
 959                 }
 960             } else if ((tree.mods.flags & STATIC) == 0) {
 961                 extras++;
 962             }
 963             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
 964             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
 965                 ClassFile.MAX_PARAMETERS) {
 966                 log.error(tree.pos(), Errors.LimitParameters);
 967                 nerrs++;
 968             }
 969 
 970             else if (tree.body != null) {
 971                 // Create a new code structure and initialize it.
 972                 int startpcCrt = initCode(tree, env, fatcode);
 973 
 974                 try {
 975                     genStat(tree.body, env);
 976                 } catch (CodeSizeOverflow e) {
 977                     // Failed due to code limit, try again with jsr/ret
 978                     startpcCrt = initCode(tree, env, fatcode);
 979                     genStat(tree.body, env);
 980                 }
 981 
 982                 if (code.state.stacksize != 0) {
 983                     log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
 984                     throw new AssertionError();
 985                 }
 986 
 987                 // If last statement could complete normally, insert a
 988                 // return at the end.
 989                 if (code.isAlive()) {
 990                     code.statBegin(TreeInfo.endPos(tree.body));
 991                     if (env.enclMethod == null ||
 992                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
 993                         code.emitop0(return_);



 994                     } else {
 995                         // sometime dead code seems alive (4415991);
 996                         // generate a small loop instead
 997                         int startpc = code.entryPoint();
 998                         CondItem c = items.makeCondItem(goto_);
 999                         code.resolve(c.jumpTrue(), startpc);
1000                     }
1001                 }
1002                 if (genCrt)
1003                     code.crt.put(tree.body,
1004                                  CRT_BLOCK,
1005                                  startpcCrt,
1006                                  code.curCP());
1007 
1008                 code.endScopes(0);
1009 
1010                 // If we exceeded limits, panic
1011                 if (code.checkLimits(tree.pos(), log)) {
1012                     nerrs++;
1013                     return;
1014                 }
1015 
1016                 // If we generated short code but got a long jump, do it again
1017                 // with fatCode = true.
1018                 if (!fatcode && code.fatcode) genMethod(tree, env, true);
1019 
1020                 // Clean up
1021                 if(stackMap == StackMapFormat.JSR202) {
1022                     code.lastFrame = null;
1023                     code.frameBeforeLast = null;
1024                 }
1025 
1026                 // Compress exception table
1027                 code.compressCatchTable();
1028 
1029                 // Fill in type annotation positions for exception parameters
1030                 code.fillExceptionParameterPositions();
1031             }
1032         }
1033 
1034         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1035             MethodSymbol meth = tree.sym;
1036 
1037             // Create a new code structure.
1038             meth.code = code = new Code(meth,
1039                                         fatcode,
1040                                         lineDebugInfo ? toplevel.lineMap : null,
1041                                         varDebugInfo,
1042                                         stackMap,
1043                                         debugCode,
1044                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1045                                                : null,
1046                                         syms,
1047                                         types,
1048                                         poolWriter);

1049             items = new Items(poolWriter, code, syms, types);
1050             if (code.debugCode) {
1051                 System.err.println(meth + " for body " + tree);
1052             }
1053 
1054             // If method is not static, create a new local variable address
1055             // for `this'.
1056             if ((tree.mods.flags & STATIC) == 0) {
1057                 Type selfType = meth.owner.type;
1058                 if (meth.isConstructor() && selfType != syms.objectType)
1059                     selfType = UninitializedType.uninitializedThis(selfType);
1060                 code.setDefined(
1061                         code.newLocal(
1062                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1063             }
1064 
1065             // Mark all parameters as defined from the beginning of
1066             // the method.
1067             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1068                 checkDimension(l.head.pos(), l.head.sym.type);
1069                 code.setDefined(code.newLocal(l.head.sym));
1070             }
1071 
1072             // Get ready to generate code for method body.
1073             int startpcCrt = genCrt ? code.curCP() : 0;
1074             code.entryPoint();
1075 
1076             // Suppress initial stackmap
1077             code.pendingStackMap = false;
1078 
1079             return startpcCrt;
1080         }
1081 
1082     public void visitVarDef(JCVariableDecl tree) {
1083         VarSymbol v = tree.sym;
1084         if (tree.init != null) {
1085             checkStringConstant(tree.init.pos(), v.getConstValue());
1086             if (v.getConstValue() == null || varDebugInfo) {
1087                 Assert.check(code.isStatementStart());
1088                 code.newLocal(v);
1089                 genExpr(tree.init, v.erasure(types)).load();
1090                 items.makeLocalItem(v).store();
1091                 Assert.check(code.isStatementStart());
1092             }
1093         } else {
1094             code.newLocal(v);
1095         }
1096         checkDimension(tree.pos(), v.type);




1097     }
1098 
1099     public void visitSkip(JCSkip tree) {
1100     }
1101 
1102     public void visitBlock(JCBlock tree) {
1103         if (tree.patternMatchingCatch != null) {
1104             Set<JCMethodInvocation> prevInvocationsWithPatternMatchingCatch = invocationsWithPatternMatchingCatch;
1105             ListBuffer<int[]> prevRanges = patternMatchingInvocationRanges;
1106             State startState = code.state.dup();
1107             try {
1108                 invocationsWithPatternMatchingCatch = tree.patternMatchingCatch.calls2Handle();
1109                 patternMatchingInvocationRanges = new ListBuffer<>();
1110                 doVisitBlock(tree);
1111             } finally {
1112                 Chain skipCatch = code.branch(goto_);
1113                 JCCatch handler = tree.patternMatchingCatch.handler();
1114                 code.entryPoint(startState, handler.param.sym.type);
1115                 genPatternMatchingCatch(handler, env, patternMatchingInvocationRanges.toList());
1116                 code.resolve(skipCatch);
1117                 invocationsWithPatternMatchingCatch = prevInvocationsWithPatternMatchingCatch;
1118                 patternMatchingInvocationRanges = prevRanges;
1119             }
1120         } else {
1121             doVisitBlock(tree);
1122         }
1123     }
1124 
1125     private void doVisitBlock(JCBlock tree) {
1126         int limit = code.nextreg;
1127         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1128         genStats(tree.stats, localEnv);
1129         // End the scope of all block-local variables in variable info.
1130         if (!env.tree.hasTag(METHODDEF)) {
1131             code.statBegin(tree.endpos);
1132             code.endScopes(limit);
1133             code.pendingStatPos = Position.NOPOS;
1134         }
1135     }
1136 
1137     public void visitDoLoop(JCDoWhileLoop tree) {
1138         genLoop(tree, tree.body, tree.cond, List.nil(), false);
1139     }
1140 
1141     public void visitWhileLoop(JCWhileLoop tree) {
1142         genLoop(tree, tree.body, tree.cond, List.nil(), true);
1143     }
1144 































1145     public void visitForLoop(JCForLoop tree) {
1146         int limit = code.nextreg;
1147         genStats(tree.init, env);
1148         genLoop(tree, tree.body, tree.cond, tree.step, true);
1149         code.endScopes(limit);
1150     }
1151     //where
1152         /** Generate code for a loop.
1153          *  @param loop       The tree representing the loop.
1154          *  @param body       The loop's body.
1155          *  @param cond       The loop's controlling condition.
1156          *  @param step       "Step" statements to be inserted at end of
1157          *                    each iteration.
1158          *  @param testFirst  True if the loop test belongs before the body.
1159          */
1160         private void genLoop(JCStatement loop,
1161                              JCStatement body,
1162                              JCExpression cond,
1163                              List<JCExpressionStatement> step,
1164                              boolean testFirst) {
1165             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1166             int startpc = code.entryPoint();
1167             if (testFirst) { //while or for loop
1168                 CondItem c;
1169                 if (cond != null) {
1170                     code.statBegin(cond.pos);
1171                     Assert.check(code.isStatementStart());
1172                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1173                 } else {
1174                     c = items.makeCondItem(goto_);
1175                 }
1176                 Chain loopDone = c.jumpFalse();
1177                 code.resolve(c.trueJumps);
1178                 Assert.check(code.isStatementStart());
1179                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1180                 code.resolve(loopEnv.info.cont);
1181                 genStats(step, loopEnv);
1182                 code.resolve(code.branch(goto_), startpc);
1183                 code.resolve(loopDone);
1184             } else {
1185                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1186                 code.resolve(loopEnv.info.cont);
1187                 genStats(step, loopEnv);
1188                 if (code.isAlive()) {
1189                     CondItem c;
1190                     if (cond != null) {
1191                         code.statBegin(cond.pos);
1192                         Assert.check(code.isStatementStart());
1193                         c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1194                     } else {
1195                         c = items.makeCondItem(goto_);
1196                     }
1197                     code.resolve(c.jumpTrue(), startpc);
1198                     Assert.check(code.isStatementStart());
1199                     code.resolve(c.falseJumps);
1200                 }
1201             }
1202             Chain exit = loopEnv.info.exit;
1203             if (exit != null) {
1204                 code.resolve(exit);
1205                 exit.state.defined.excludeFrom(code.nextreg);
1206             }
1207         }
1208 
1209     public void visitForeachLoop(JCEnhancedForLoop tree) {
1210         throw new AssertionError(); // should have been removed by Lower.
1211     }
1212 
1213     public void visitLabelled(JCLabeledStatement tree) {
1214         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1215         genStat(tree.body, localEnv, CRT_STATEMENT);
1216         Chain exit = localEnv.info.exit;
1217         if (exit != null) {
1218             code.resolve(exit);
1219             exit.state.defined.excludeFrom(code.nextreg);
1220         }
1221     }
1222 
1223     public void visitSwitch(JCSwitch tree) {
1224         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1225     }
1226 
1227     @Override
1228     public void visitSwitchExpression(JCSwitchExpression tree) {
1229         code.resolvePending();
1230         boolean prevInCondSwitchExpression = inCondSwitchExpression;
1231         try {
1232             inCondSwitchExpression = false;
1233             doHandleSwitchExpression(tree);
1234         } finally {
1235             inCondSwitchExpression = prevInCondSwitchExpression;
1236         }
1237         result = items.makeStackItem(pt);
1238     }
1239 
1240     private void doHandleSwitchExpression(JCSwitchExpression tree) {
1241         List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1242         LocalItem prevSwitchResult = switchResult;
1243         int limit = code.nextreg;
1244         try {
1245             stackBeforeSwitchExpression = List.nil();
1246             switchResult = null;
1247             if (hasTry(tree)) {
1248                 //if the switch expression contains try-catch, the catch handlers need to have
1249                 //an empty stack. So stash whole stack to local variables, and restore it before
1250                 //breaks:
1251                 while (code.state.stacksize > 0) {
1252                     Type type = code.state.peek();
1253                     Name varName = names.fromString(target.syntheticNameChar() +
1254                                                     "stack" +
1255                                                     target.syntheticNameChar() +
1256                                                     tree.pos +
1257                                                     target.syntheticNameChar() +
1258                                                     code.state.stacksize);
1259                     VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type,
1260                                                   this.env.enclMethod.sym);
1261                     LocalItem item = items.new LocalItem(type, code.newLocal(var));
1262                     stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item);
1263                     item.store();
1264                 }
1265                 switchResult = makeTemp(tree.type);
1266             }
1267             int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
1268             try {
1269                 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1270             } finally {
1271                 code.setLetExprStackPos(prevLetExprStart);
1272             }
1273         } finally {
1274             stackBeforeSwitchExpression = prevStackBeforeSwitchExpression;
1275             switchResult = prevSwitchResult;
1276             code.endScopes(limit);
1277         }
1278     }
1279     //where:
1280         private boolean hasTry(JCSwitchExpression tree) {
1281             class HasTryScanner extends TreeScanner {
1282                 private boolean hasTry;
1283 
1284                 @Override
1285                 public void visitTry(JCTry tree) {
1286                     hasTry = true;
1287                 }
1288 
1289                 @Override
1290                 public void visitSynchronized(JCSynchronized tree) {
1291                     hasTry = true;
1292                 }
1293 
1294                 @Override
1295                 public void visitClassDef(JCClassDecl tree) {
1296                 }
1297 
1298                 @Override
1299                 public void visitLambda(JCLambda tree) {
1300                 }
1301             };
1302 
1303             HasTryScanner hasTryScanner = new HasTryScanner();
1304 
1305             hasTryScanner.scan(tree);
1306             return hasTryScanner.hasTry;
1307         }
1308 
1309     private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1310                               boolean patternSwitch) {
1311         int limit = code.nextreg;
1312         Assert.check(!selector.type.hasTag(CLASS));
1313         int switchStart = patternSwitch ? code.entryPoint() : -1;
1314         int startpcCrt = genCrt ? code.curCP() : 0;
1315         Assert.check(code.isStatementStart());
1316         Item sel = genExpr(selector, syms.intType);
1317         if (cases.isEmpty()) {
1318             // We are seeing:  switch <sel> {}
1319             sel.load().drop();
1320             if (genCrt)
1321                 code.crt.put(TreeInfo.skipParens(selector),
1322                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1323         } else {
1324             // We are seeing a nonempty switch.
1325             sel.load();
1326             if (genCrt)
1327                 code.crt.put(TreeInfo.skipParens(selector),
1328                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1329             Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1330             switchEnv.info.isSwitch = true;
1331 
1332             // Compute number of labels and minimum and maximum label values.
1333             // For each case, store its label in an array.
1334             int lo = Integer.MAX_VALUE;  // minimum label.
1335             int hi = Integer.MIN_VALUE;  // maximum label.
1336             int nlabels = 0;               // number of labels.
1337 
1338             int[] labels = new int[cases.length()];  // the label array.
1339             int defaultIndex = -1;     // the index of the default clause.
1340 
1341             List<JCCase> l = cases;
1342             for (int i = 0; i < labels.length; i++) {
1343                 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1344                     Assert.check(l.head.labels.size() == 1);
1345                     int val = ((Number) constLabel.expr.type.constValue()).intValue();
1346                     labels[i] = val;
1347                     if (val < lo) lo = val;
1348                     if (hi < val) hi = val;
1349                     nlabels++;
1350                 } else {
1351                     Assert.check(defaultIndex == -1);
1352                     defaultIndex = i;
1353                 }
1354                 l = l.tail;
1355             }
1356 
1357             // Determine whether to issue a tableswitch or a lookupswitch
1358             // instruction.
1359             long table_space_cost = 4 + ((long) hi - lo + 1); // words
1360             long table_time_cost = 3; // comparisons
1361             long lookup_space_cost = 3 + 2 * (long) nlabels;
1362             long lookup_time_cost = nlabels;
1363             int opcode =
1364                 nlabels > 0 &&
1365                 table_space_cost + 3 * table_time_cost <=
1366                 lookup_space_cost + 3 * lookup_time_cost
1367                 ?
1368                 tableswitch : lookupswitch;
1369 
1370             int startpc = code.curCP();    // the position of the selector operation
1371             code.emitop0(opcode);
1372             code.align(4);
1373             int tableBase = code.curCP();  // the start of the jump table
1374             int[] offsets = null;          // a table of offsets for a lookupswitch
1375             code.emit4(-1);                // leave space for default offset
1376             if (opcode == tableswitch) {
1377                 code.emit4(lo);            // minimum label
1378                 code.emit4(hi);            // maximum label
1379                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
1380                     code.emit4(-1);
1381                 }
1382             } else {
1383                 code.emit4(nlabels);    // number of labels
1384                 for (int i = 0; i < nlabels; i++) {
1385                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
1386                 }
1387                 offsets = new int[labels.length];
1388             }
1389             Code.State stateSwitch = code.state.dup();
1390             code.markDead();
1391 
1392             // For each case do:
1393             l = cases;
1394             for (int i = 0; i < labels.length; i++) {
1395                 JCCase c = l.head;
1396                 l = l.tail;
1397 
1398                 int pc = code.entryPoint(stateSwitch);
1399                 // Insert offset directly into code or else into the
1400                 // offsets table.
1401                 if (i != defaultIndex) {
1402                     if (opcode == tableswitch) {
1403                         code.put4(
1404                             tableBase + 4 * (labels[i] - lo + 3),
1405                             pc - startpc);
1406                     } else {
1407                         offsets[i] = pc - startpc;
1408                     }
1409                 } else {
1410                     code.put4(tableBase, pc - startpc);
1411                 }
1412 
1413                 // Generate code for the statements in this case.
1414                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1415             }
1416 
1417             if (switchEnv.info.cont != null) {
1418                 Assert.check(patternSwitch);
1419                 code.resolve(switchEnv.info.cont, switchStart);
1420             }
1421 
1422             // Resolve all breaks.
1423             Chain exit = switchEnv.info.exit;
1424             if  (exit != null) {
1425                 code.resolve(exit);
1426                 exit.state.defined.excludeFrom(limit);
1427             }
1428 
1429             // If we have not set the default offset, we do so now.
1430             if (code.get4(tableBase) == -1) {
1431                 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc);
1432             }
1433 
1434             if (opcode == tableswitch) {
1435                 // Let any unfilled slots point to the default case.
1436                 int defaultOffset = code.get4(tableBase);
1437                 for (long i = lo; i <= hi; i++) {
1438                     int t = (int)(tableBase + 4 * (i - lo + 3));
1439                     if (code.get4(t) == -1)
1440                         code.put4(t, defaultOffset);
1441                 }
1442             } else {
1443                 // Sort non-default offsets and copy into lookup table.
1444                 if (defaultIndex >= 0)
1445                     for (int i = defaultIndex; i < labels.length - 1; i++) {
1446                         labels[i] = labels[i+1];
1447                         offsets[i] = offsets[i+1];
1448                     }
1449                 if (nlabels > 0)
1450                     qsort2(labels, offsets, 0, nlabels - 1);
1451                 for (int i = 0; i < nlabels; i++) {
1452                     int caseidx = tableBase + 8 * (i + 1);
1453                     code.put4(caseidx, labels[i]);
1454                     code.put4(caseidx + 4, offsets[i]);
1455                 }
1456             }
1457         }
1458         code.endScopes(limit);
1459     }
1460 //where
1461         /** Sort (int) arrays of keys and values
1462          */
1463        static void qsort2(int[] keys, int[] values, int lo, int hi) {
1464             int i = lo;
1465             int j = hi;
1466             int pivot = keys[(i+j)/2];
1467             do {
1468                 while (keys[i] < pivot) i++;
1469                 while (pivot < keys[j]) j--;
1470                 if (i <= j) {
1471                     int temp1 = keys[i];
1472                     keys[i] = keys[j];
1473                     keys[j] = temp1;
1474                     int temp2 = values[i];
1475                     values[i] = values[j];
1476                     values[j] = temp2;
1477                     i++;
1478                     j--;
1479                 }
1480             } while (i <= j);
1481             if (lo < j) qsort2(keys, values, lo, j);
1482             if (i < hi) qsort2(keys, values, i, hi);
1483         }
1484 
1485     public void visitSynchronized(JCSynchronized tree) {
1486         int limit = code.nextreg;
1487         // Generate code to evaluate lock and save in temporary variable.
1488         final LocalItem lockVar = makeTemp(syms.objectType);
1489         Assert.check(code.isStatementStart());
1490         genExpr(tree.lock, tree.lock.type).load().duplicate();
1491         lockVar.store();
1492 
1493         // Generate code to enter monitor.
1494         code.emitop0(monitorenter);
1495         code.state.lock(lockVar.reg);
1496 
1497         // Generate code for a try statement with given body, no catch clauses
1498         // in a new environment with the "exit-monitor" operation as finalizer.
1499         final Env<GenContext> syncEnv = env.dup(tree, new GenContext());
1500         syncEnv.info.finalize = new GenFinalizer() {
1501             void gen() {
1502                 genLast();
1503                 Assert.check(syncEnv.info.gaps.length() % 2 == 0);
1504                 syncEnv.info.gaps.append(code.curCP());
1505             }
1506             void genLast() {
1507                 if (code.isAlive()) {
1508                     lockVar.load();
1509                     code.emitop0(monitorexit);
1510                     code.state.unlock(lockVar.reg);
1511                 }
1512             }
1513         };
1514         syncEnv.info.gaps = new ListBuffer<>();
1515         genTry(tree.body, List.nil(), syncEnv);
1516         code.endScopes(limit);
1517     }
1518 
1519     public void visitTry(final JCTry tree) {
1520         // Generate code for a try statement with given body and catch clauses,
1521         // in a new environment which calls the finally block if there is one.
1522         final Env<GenContext> tryEnv = env.dup(tree, new GenContext());
1523         final Env<GenContext> oldEnv = env;
1524         tryEnv.info.finalize = new GenFinalizer() {
1525             void gen() {
1526                 Assert.check(tryEnv.info.gaps.length() % 2 == 0);
1527                 tryEnv.info.gaps.append(code.curCP());
1528                 genLast();
1529             }
1530             void genLast() {
1531                 if (tree.finalizer != null)
1532                     genStat(tree.finalizer, oldEnv, CRT_BLOCK);
1533             }
1534             boolean hasFinalizer() {
1535                 return tree.finalizer != null;
1536             }
1537 
1538             @Override
1539             void afterBody() {
1540                 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1541                     //for body-only finally, remove the GenFinalizer after try body
1542                     //so that the finally is not generated to catch bodies:
1543                     tryEnv.info.finalize = null;
1544                 }
1545             }
1546 
1547         };
1548         tryEnv.info.gaps = new ListBuffer<>();
1549         genTry(tree.body, tree.catchers, tryEnv);
1550     }
1551     //where
1552         /** Generate code for a try or synchronized statement
1553          *  @param body      The body of the try or synchronized statement.
1554          *  @param catchers  The list of catch clauses.
1555          *  @param env       The current environment of the body.
1556          */
1557         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1558             int limit = code.nextreg;
1559             int startpc = code.curCP();
1560             Code.State stateTry = code.state.dup();
1561             genStat(body, env, CRT_BLOCK);
1562             int endpc = code.curCP();
1563             List<Integer> gaps = env.info.gaps.toList();
1564             code.statBegin(TreeInfo.endPos(body));
1565             genFinalizer(env);
1566             code.statBegin(TreeInfo.endPos(env.tree));
1567             Chain exitChain;
1568             boolean actualTry = env.tree.hasTag(TRY);
1569             if (startpc == endpc && actualTry) {
1570                 exitChain = code.branch(dontgoto);
1571             } else {
1572                 exitChain = code.branch(goto_);
1573             }
1574             endFinalizerGap(env);
1575             env.info.finalize.afterBody();
1576             boolean hasFinalizer =
1577                 env.info.finalize != null &&
1578                 env.info.finalize.hasFinalizer();
1579             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1580                 // start off with exception on stack
1581                 code.entryPoint(stateTry, l.head.param.sym.type);
1582                 genCatch(l.head, env, startpc, endpc, gaps);
1583                 genFinalizer(env);
1584                 if (hasFinalizer || l.tail.nonEmpty()) {
1585                     code.statBegin(TreeInfo.endPos(env.tree));
1586                     exitChain = Code.mergeChains(exitChain,
1587                                                  code.branch(goto_));
1588                 }
1589                 endFinalizerGap(env);
1590             }
1591             if (hasFinalizer && (startpc != endpc || !actualTry)) {
1592                 // Create a new register segment to avoid allocating
1593                 // the same variables in finalizers and other statements.
1594                 code.newRegSegment();
1595 
1596                 // Add a catch-all clause.
1597 
1598                 // start off with exception on stack
1599                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1600 
1601                 // Register all exception ranges for catch all clause.
1602                 // The range of the catch all clause is from the beginning
1603                 // of the try or synchronized block until the present
1604                 // code pointer excluding all gaps in the current
1605                 // environment's GenContext.
1606                 int startseg = startpc;
1607                 while (env.info.gaps.nonEmpty()) {
1608                     int endseg = env.info.gaps.next().intValue();
1609                     registerCatch(body.pos(), startseg, endseg,
1610                                   catchallpc, 0);
1611                     startseg = env.info.gaps.next().intValue();
1612                 }
1613                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1614                 code.markStatBegin();
1615 
1616                 Item excVar = makeTemp(syms.throwableType);
1617                 excVar.store();
1618                 genFinalizer(env);
1619                 code.resolvePending();
1620                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1621                 code.markStatBegin();
1622 
1623                 excVar.load();
1624                 registerCatch(body.pos(), startseg,
1625                               env.info.gaps.next().intValue(),
1626                               catchallpc, 0);
1627                 code.emitop0(athrow);
1628                 code.markDead();
1629 
1630                 // If there are jsr's to this finalizer, ...
1631                 if (env.info.cont != null) {
1632                     // Resolve all jsr's.
1633                     code.resolve(env.info.cont);
1634 
1635                     // Mark statement line number
1636                     code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1637                     code.markStatBegin();
1638 
1639                     // Save return address.
1640                     LocalItem retVar = makeTemp(syms.throwableType);
1641                     retVar.store();
1642 
1643                     // Generate finalizer code.
1644                     env.info.finalize.genLast();
1645 
1646                     // Return.
1647                     code.emitop1w(ret, retVar.reg);
1648                     code.markDead();
1649                 }
1650             }
1651             // Resolve all breaks.
1652             code.resolve(exitChain);
1653 
1654             code.endScopes(limit);
1655         }
1656 
1657         /** Generate code for a catch clause.
1658          *  @param tree     The catch clause.
1659          *  @param env      The environment current in the enclosing try.
1660          *  @param startpc  Start pc of try-block.
1661          *  @param endpc    End pc of try-block.
1662          */
1663         void genCatch(JCCatch tree,
1664                       Env<GenContext> env,
1665                       int startpc, int endpc,
1666                       List<Integer> gaps) {
1667             if (startpc != endpc) {
1668                 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs
1669                         = catchTypesWithAnnotations(tree);
1670                 while (gaps.nonEmpty()) {
1671                     for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1672                         JCExpression subCatch = subCatch1.snd;
1673                         int catchType = makeRef(tree.pos(), subCatch.type);
1674                         int end = gaps.head.intValue();
1675                         registerCatch(tree.pos(),
1676                                       startpc,  end, code.curCP(),
1677                                       catchType);
1678                         for (Attribute.TypeCompound tc :  subCatch1.fst) {
1679                                 tc.position.setCatchInfo(catchType, startpc);
1680                         }
1681                     }
1682                     gaps = gaps.tail;
1683                     startpc = gaps.head.intValue();
1684                     gaps = gaps.tail;
1685                 }
1686                 if (startpc < endpc) {
1687                     for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1688                         JCExpression subCatch = subCatch1.snd;
1689                         int catchType = makeRef(tree.pos(), subCatch.type);
1690                         registerCatch(tree.pos(),
1691                                       startpc, endpc, code.curCP(),
1692                                       catchType);
1693                         for (Attribute.TypeCompound tc :  subCatch1.fst) {
1694                             tc.position.setCatchInfo(catchType, startpc);
1695                         }
1696                     }
1697                 }
1698                 genCatchBlock(tree, env);
1699             }
1700         }
1701         void genPatternMatchingCatch(JCCatch tree,
1702                                      Env<GenContext> env,
1703                                      List<int[]> ranges) {
1704             for (int[] range : ranges) {
1705                 JCExpression subCatch = tree.param.vartype;
1706                 int catchType = makeRef(tree.pos(), subCatch.type);
1707                 registerCatch(tree.pos(),
1708                               range[0], range[1], code.curCP(),
1709                               catchType);
1710             }
1711             genCatchBlock(tree, env);
1712         }
1713         void genCatchBlock(JCCatch tree, Env<GenContext> env) {
1714             VarSymbol exparam = tree.param.sym;
1715             code.statBegin(tree.pos);
1716             code.markStatBegin();
1717             int limit = code.nextreg;
1718             code.newLocal(exparam);
1719             items.makeLocalItem(exparam).store();
1720             code.statBegin(TreeInfo.firstStatPos(tree.body));
1721             genStat(tree.body, env, CRT_BLOCK);
1722             code.endScopes(limit);
1723             code.statBegin(TreeInfo.endPos(tree.body));
1724         }
1725         // where
1726         List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) {
1727             return TreeInfo.isMultiCatch(tree) ?
1728                     catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) :
1729                     List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype));
1730         }
1731         // where
1732         List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) {
1733             List<JCExpression> alts = tree.alternatives;
1734             List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head));
1735             alts = alts.tail;
1736 
1737             while(alts != null && alts.head != null) {
1738                 JCExpression alt = alts.head;
1739                 if (alt instanceof JCAnnotatedType annotatedType) {
1740                     res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt));
1741                 } else {
1742                     res = res.prepend(new Pair<>(List.nil(), alt));
1743                 }
1744                 alts = alts.tail;
1745             }
1746             return res.reverse();
1747         }
1748 
1749         /** Register a catch clause in the "Exceptions" code-attribute.
1750          */
1751         void registerCatch(DiagnosticPosition pos,
1752                            int startpc, int endpc,
1753                            int handler_pc, int catch_type) {
1754             char startpc1 = (char)startpc;
1755             char endpc1 = (char)endpc;
1756             char handler_pc1 = (char)handler_pc;
1757             if (startpc1 == startpc &&
1758                 endpc1 == endpc &&
1759                 handler_pc1 == handler_pc) {
1760                 code.addCatch(startpc1, endpc1, handler_pc1,
1761                               (char)catch_type);
1762             } else {
1763                 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1764                 nerrs++;
1765             }
1766         }
1767 
1768     public void visitIf(JCIf tree) {
1769         int limit = code.nextreg;
1770         Chain thenExit = null;
1771         Assert.check(code.isStatementStart());
1772         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1773                              CRT_FLOW_CONTROLLER);
1774         Chain elseChain = c.jumpFalse();
1775         Assert.check(code.isStatementStart());
1776         if (!c.isFalse()) {
1777             code.resolve(c.trueJumps);
1778             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1779             thenExit = code.branch(goto_);
1780         }
1781         if (elseChain != null) {
1782             code.resolve(elseChain);
1783             if (tree.elsepart != null) {
1784                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1785             }
1786         }
1787         code.resolve(thenExit);
1788         code.endScopes(limit);
1789         Assert.check(code.isStatementStart());
1790     }
1791 
1792     public void visitExec(JCExpressionStatement tree) {
1793         // Optimize x++ to ++x and x-- to --x.
1794         JCExpression e = tree.expr;
1795         switch (e.getTag()) {
1796             case POSTINC:
1797                 ((JCUnary) e).setTag(PREINC);
1798                 break;
1799             case POSTDEC:
1800                 ((JCUnary) e).setTag(PREDEC);
1801                 break;
1802         }
1803         Assert.check(code.isStatementStart());
1804         genExpr(tree.expr, tree.expr.type).drop();
1805         Assert.check(code.isStatementStart());
1806     }
1807 
1808     public void visitBreak(JCBreak tree) {
1809         Assert.check(code.isStatementStart());
1810         final Env<GenContext> targetEnv = unwindBreak(tree.target);
1811         targetEnv.info.addExit(code.branch(goto_));
1812         endFinalizerGaps(env, targetEnv);
1813     }
1814 
1815     public void visitYield(JCYield tree) {
1816         Assert.check(code.isStatementStart());
1817         final Env<GenContext> targetEnv;
1818         if (inCondSwitchExpression) {
1819             CondItem value = genCond(tree.value, CRT_FLOW_TARGET);
1820             Chain falseJumps = value.jumpFalse();
1821 
1822             code.resolve(value.trueJumps);
1823             Env<GenContext> localEnv = unwindBreak(tree.target);
1824             reloadStackBeforeSwitchExpr();
1825             Chain trueJumps = code.branch(goto_);
1826 
1827             endFinalizerGaps(env, localEnv);
1828 
1829             code.resolve(falseJumps);
1830             targetEnv = unwindBreak(tree.target);
1831             reloadStackBeforeSwitchExpr();
1832             falseJumps = code.branch(goto_);
1833 
1834             if (switchExpressionTrueChain == null) {
1835                 switchExpressionTrueChain = trueJumps;
1836             } else {
1837                 switchExpressionTrueChain =
1838                         Code.mergeChains(switchExpressionTrueChain, trueJumps);
1839             }
1840             if (switchExpressionFalseChain == null) {
1841                 switchExpressionFalseChain = falseJumps;
1842             } else {
1843                 switchExpressionFalseChain =
1844                         Code.mergeChains(switchExpressionFalseChain, falseJumps);
1845             }
1846         } else {
1847             genExpr(tree.value, pt).load();
1848             if (switchResult != null)
1849                 switchResult.store();
1850 
1851             targetEnv = unwindBreak(tree.target);
1852 
1853             if (code.isAlive()) {
1854                 reloadStackBeforeSwitchExpr();
1855                 if (switchResult != null)
1856                     switchResult.load();
1857 
1858                 code.state.forceStackTop(tree.target.type);
1859                 targetEnv.info.addExit(code.branch(goto_));
1860                 code.markDead();
1861             }
1862         }
1863         endFinalizerGaps(env, targetEnv);
1864     }
1865     //where:
1866         /** As side-effect, might mark code as dead disabling any further emission.
1867          */
1868         private Env<GenContext> unwindBreak(JCTree target) {
1869             int tmpPos = code.pendingStatPos;
1870             Env<GenContext> targetEnv = unwind(target, env);
1871             code.pendingStatPos = tmpPos;
1872             return targetEnv;
1873         }
1874 
1875         private void reloadStackBeforeSwitchExpr() {
1876             for (LocalItem li : stackBeforeSwitchExpression)
1877                 li.load();
1878         }
1879 
1880     public void visitContinue(JCContinue tree) {
1881         int tmpPos = code.pendingStatPos;
1882         Env<GenContext> targetEnv = unwind(tree.target, env);
1883         code.pendingStatPos = tmpPos;
1884         Assert.check(code.isStatementStart());
1885         targetEnv.info.addCont(code.branch(goto_));
1886         endFinalizerGaps(env, targetEnv);
1887     }
1888 
1889     public void visitReturn(JCReturn tree) {
1890         int limit = code.nextreg;
1891         final Env<GenContext> targetEnv;
1892 
1893         /* Save and then restore the location of the return in case a finally
1894          * is expanded (with unwind()) in the middle of our bytecodes.
1895          */
1896         int tmpPos = code.pendingStatPos;
1897         if (tree.expr != null) {
1898             Assert.check(code.isStatementStart());
1899             Item r = genExpr(tree.expr, pt).load();
1900             if (hasFinally(env.enclMethod, env)) {
1901                 r = makeTemp(pt);
1902                 r.store();
1903             }
1904             targetEnv = unwind(env.enclMethod, env);
1905             code.pendingStatPos = tmpPos;
1906             r.load();
1907             code.emitop0(ireturn + Code.truncate(Code.typecode(pt)));
1908         } else {
1909             targetEnv = unwind(env.enclMethod, env);
1910             code.pendingStatPos = tmpPos;
1911             code.emitop0(return_);
1912         }
1913         endFinalizerGaps(env, targetEnv);
1914         code.endScopes(limit);
1915     }
1916 
1917     public void visitThrow(JCThrow tree) {
1918         Assert.check(code.isStatementStart());
1919         genExpr(tree.expr, tree.expr.type).load();
1920         code.emitop0(athrow);
1921         Assert.check(code.isStatementStart());
1922     }
1923 
1924 /* ************************************************************************
1925  * Visitor methods for expressions
1926  *************************************************************************/
1927 
1928     public void visitApply(JCMethodInvocation tree) {
1929         setTypeAnnotationPositions(tree.pos);
1930         // Generate code for method.
1931         Item m = genExpr(tree.meth, methodType);
1932         // Generate code for all arguments, where the expected types are
1933         // the parameters of the method's external type (that is, any implicit
1934         // outer instance of a super(...) call appears as first parameter).
1935         MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
1936         genArgs(tree.args,
1937                 msym.externalType(types).getParameterTypes());
1938         if (!msym.isDynamic()) {
1939             code.statBegin(tree.pos);
1940         }
1941         if (invocationsWithPatternMatchingCatch.contains(tree)) {
1942             int start = code.curCP();
1943             result = m.invoke();
1944             patternMatchingInvocationRanges.add(new int[] {start, code.curCP()});
1945         } else {
1946             result = m.invoke();
1947         }
1948     }
1949 
1950     public void visitConditional(JCConditional tree) {
1951         Chain thenExit = null;
1952         code.statBegin(tree.cond.pos);
1953         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
1954         Chain elseChain = c.jumpFalse();
1955         if (!c.isFalse()) {
1956             code.resolve(c.trueJumps);
1957             int startpc = genCrt ? code.curCP() : 0;
1958             code.statBegin(tree.truepart.pos);
1959             genExpr(tree.truepart, pt).load();
1960             code.state.forceStackTop(tree.type);
1961             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
1962                                      startpc, code.curCP());
1963             thenExit = code.branch(goto_);
1964         }
1965         if (elseChain != null) {
1966             code.resolve(elseChain);
1967             int startpc = genCrt ? code.curCP() : 0;
1968             code.statBegin(tree.falsepart.pos);
1969             genExpr(tree.falsepart, pt).load();
1970             code.state.forceStackTop(tree.type);
1971             if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET,
1972                                      startpc, code.curCP());
1973         }
1974         code.resolve(thenExit);
1975         result = items.makeStackItem(pt);
1976     }
1977 
1978     private void setTypeAnnotationPositions(int treePos) {
1979         MethodSymbol meth = code.meth;
1980         boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR
1981                 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT;
1982 
1983         for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) {
1984             if (ta.hasUnknownPosition())
1985                 ta.tryFixPosition();
1986 
1987             if (ta.position.matchesPos(treePos))
1988                 ta.position.updatePosOffset(code.cp);
1989         }
1990 
1991         if (!initOrClinit)
1992             return;
1993 
1994         for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) {
1995             if (ta.hasUnknownPosition())
1996                 ta.tryFixPosition();
1997 
1998             if (ta.position.matchesPos(treePos))
1999                 ta.position.updatePosOffset(code.cp);
2000         }
2001 
2002         ClassSymbol clazz = meth.enclClass();
2003         for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
2004             if (!s.getKind().isField())
2005                 continue;
2006 
2007             for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
2008                 if (ta.hasUnknownPosition())
2009                     ta.tryFixPosition();
2010 
2011                 if (ta.position.matchesPos(treePos))
2012                     ta.position.updatePosOffset(code.cp);
2013             }
2014         }
2015     }
2016 
2017     public void visitNewClass(JCNewClass tree) {
2018         // Enclosing instances or anonymous classes should have been eliminated
2019         // by now.
2020         Assert.check(tree.encl == null && tree.def == null);
2021         setTypeAnnotationPositions(tree.pos);
2022 
2023         code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass);
2024         code.emitop0(dup);
2025 
2026         // Generate code for all arguments, where the expected types are
2027         // the parameters of the constructor's external type (that is,
2028         // any implicit outer instance appears as first parameter).
2029         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
2030 
2031         items.makeMemberItem(tree.constructor, true).invoke();
2032         result = items.makeStackItem(tree.type);
2033     }
2034 
2035     public void visitNewArray(JCNewArray tree) {
2036         setTypeAnnotationPositions(tree.pos);
2037 
2038         if (tree.elems != null) {
2039             Type elemtype = types.elemtype(tree.type);
2040             loadIntConst(tree.elems.length());
2041             Item arr = makeNewArray(tree.pos(), tree.type, 1);
2042             int i = 0;
2043             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {
2044                 arr.duplicate();
2045                 loadIntConst(i);
2046                 i++;
2047                 genExpr(l.head, elemtype).load();
2048                 items.makeIndexedItem(elemtype).store();
2049             }
2050             result = arr;
2051         } else {
2052             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2053                 genExpr(l.head, syms.intType).load();
2054             }
2055             result = makeNewArray(tree.pos(), tree.type, tree.dims.length());
2056         }
2057     }
2058 //where
2059         /** Generate code to create an array with given element type and number
2060          *  of dimensions.
2061          */
2062         Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) {
2063             Type elemtype = types.elemtype(type);
2064             if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) {
2065                 log.error(pos, Errors.LimitDimensions);
2066                 nerrs++;
2067             }
2068             int elemcode = Code.arraycode(elemtype);
2069             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2070                 code.emitAnewarray(makeRef(pos, elemtype), type);
2071             } else if (elemcode == 1) {
2072                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2073             } else {
2074                 code.emitNewarray(elemcode, type);
2075             }
2076             return items.makeStackItem(type);
2077         }
2078 
2079     public void visitParens(JCParens tree) {
2080         result = genExpr(tree.expr, tree.expr.type);
2081     }
2082 
2083     public void visitAssign(JCAssign tree) {
2084         Item l = genExpr(tree.lhs, tree.lhs.type);
2085         genExpr(tree.rhs, tree.lhs.type).load();
2086         if (tree.rhs.type.hasTag(BOT)) {
2087             /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2088                for "regarding a reference as having some other type in a manner that can be proved
2089                correct at compile time."
2090             */
2091             code.state.forceStackTop(tree.lhs.type);
2092         }
2093         result = items.makeAssignItem(l);
2094     }
2095 
2096     public void visitAssignop(JCAssignOp tree) {
2097         OperatorSymbol operator = tree.operator;
2098         Item l;
2099         if (operator.opcode == string_add) {
2100             l = concat.makeConcat(tree);
2101         } else {
2102             // Generate code for first expression
2103             l = genExpr(tree.lhs, tree.lhs.type);
2104 
2105             // If we have an increment of -32768 to +32767 of a local
2106             // int variable we can use an incr instruction instead of
2107             // proceeding further.
2108             if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
2109                 l instanceof LocalItem localItem &&
2110                 tree.lhs.type.getTag().isSubRangeOf(INT) &&
2111                 tree.rhs.type.getTag().isSubRangeOf(INT) &&
2112                 tree.rhs.type.constValue() != null) {
2113                 int ival = ((Number) tree.rhs.type.constValue()).intValue();
2114                 if (tree.hasTag(MINUS_ASG)) ival = -ival;
2115                 localItem.incr(ival);
2116                 result = l;
2117                 return;
2118             }
2119             // Otherwise, duplicate expression, load one copy
2120             // and complete binary operation.
2121             l.duplicate();
2122             l.coerce(operator.type.getParameterTypes().head).load();
2123             completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type);
2124         }
2125         result = items.makeAssignItem(l);
2126     }
2127 
2128     public void visitUnary(JCUnary tree) {
2129         OperatorSymbol operator = tree.operator;
2130         if (tree.hasTag(NOT)) {
2131             CondItem od = genCond(tree.arg, false);
2132             result = od.negate();
2133         } else {
2134             Item od = genExpr(tree.arg, operator.type.getParameterTypes().head);
2135             switch (tree.getTag()) {
2136             case POS:
2137                 result = od.load();
2138                 break;
2139             case NEG:
2140                 result = od.load();
2141                 code.emitop0(operator.opcode);
2142                 break;
2143             case COMPL:
2144                 result = od.load();
2145                 emitMinusOne(od.typecode);
2146                 code.emitop0(operator.opcode);
2147                 break;
2148             case PREINC: case PREDEC:
2149                 od.duplicate();
2150                 if (od instanceof LocalItem localItem &&
2151                     (operator.opcode == iadd || operator.opcode == isub)) {
2152                     localItem.incr(tree.hasTag(PREINC) ? 1 : -1);
2153                     result = od;
2154                 } else {
2155                     od.load();
2156                     code.emitop0(one(od.typecode));
2157                     code.emitop0(operator.opcode);
2158                     // Perform narrowing primitive conversion if byte,
2159                     // char, or short.  Fix for 4304655.
2160                     if (od.typecode != INTcode &&
2161                         Code.truncate(od.typecode) == INTcode)
2162                       code.emitop0(int2byte + od.typecode - BYTEcode);
2163                     result = items.makeAssignItem(od);
2164                 }
2165                 break;
2166             case POSTINC: case POSTDEC:
2167                 od.duplicate();
2168                 if (od instanceof LocalItem localItem &&
2169                     (operator.opcode == iadd || operator.opcode == isub)) {
2170                     Item res = od.load();
2171                     localItem.incr(tree.hasTag(POSTINC) ? 1 : -1);
2172                     result = res;
2173                 } else {
2174                     Item res = od.load();
2175                     od.stash(od.typecode);
2176                     code.emitop0(one(od.typecode));
2177                     code.emitop0(operator.opcode);
2178                     // Perform narrowing primitive conversion if byte,
2179                     // char, or short.  Fix for 4304655.
2180                     if (od.typecode != INTcode &&
2181                         Code.truncate(od.typecode) == INTcode)
2182                       code.emitop0(int2byte + od.typecode - BYTEcode);
2183                     od.store();
2184                     result = res;
2185                 }
2186                 break;
2187             case NULLCHK:
2188                 result = od.load();
2189                 code.emitop0(dup);
2190                 genNullCheck(tree);
2191                 break;
2192             default:
2193                 Assert.error();
2194             }
2195         }
2196     }
2197 
2198     /** Generate a null check from the object value at stack top. */
2199     private void genNullCheck(JCTree tree) {
2200         code.statBegin(tree.pos);
2201         callMethod(tree.pos(), syms.objectsType, names.requireNonNull,
2202                    List.of(syms.objectType), true);
2203         code.emitop0(pop);
2204     }
2205 
2206     public void visitBinary(JCBinary tree) {
2207         OperatorSymbol operator = tree.operator;
2208         if (operator.opcode == string_add) {
2209             result = concat.makeConcat(tree);
2210         } else if (tree.hasTag(AND)) {
2211             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2212             if (!lcond.isFalse()) {
2213                 Chain falseJumps = lcond.jumpFalse();
2214                 code.resolve(lcond.trueJumps);
2215                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2216                 result = items.
2217                     makeCondItem(rcond.opcode,
2218                                  rcond.trueJumps,
2219                                  Code.mergeChains(falseJumps,
2220                                                   rcond.falseJumps));
2221             } else {
2222                 result = lcond;
2223             }
2224         } else if (tree.hasTag(OR)) {
2225             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2226             if (!lcond.isTrue()) {
2227                 Chain trueJumps = lcond.jumpTrue();
2228                 code.resolve(lcond.falseJumps);
2229                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2230                 result = items.
2231                     makeCondItem(rcond.opcode,
2232                                  Code.mergeChains(trueJumps, rcond.trueJumps),
2233                                  rcond.falseJumps);
2234             } else {
2235                 result = lcond;
2236             }
2237         } else {
2238             Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head);
2239             od.load();
2240             result = completeBinop(tree.lhs, tree.rhs, operator);
2241         }
2242     }
2243 
2244 
2245         /** Complete generating code for operation, with left operand
2246          *  already on stack.
2247          *  @param lhs       The tree representing the left operand.
2248          *  @param rhs       The tree representing the right operand.
2249          *  @param operator  The operator symbol.
2250          */
2251         Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) {
2252             MethodType optype = (MethodType)operator.type;
2253             int opcode = operator.opcode;
2254             if (opcode >= if_icmpeq && opcode <= if_icmple &&
2255                     rhs.type.constValue() instanceof Number number &&
2256                     number.intValue() == 0) {
2257                 opcode = opcode + (ifeq - if_icmpeq);
2258             } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
2259                        TreeInfo.isNull(rhs)) {
2260                 opcode = opcode + (if_acmp_null - if_acmpeq);
2261             } else {
2262                 // The expected type of the right operand is
2263                 // the second parameter type of the operator, except for
2264                 // shifts with long shiftcount, where we convert the opcode
2265                 // to a short shift and the expected type to int.
2266                 Type rtype = operator.erasure(types).getParameterTypes().tail.head;
2267                 if (opcode >= ishll && opcode <= lushrl) {
2268                     opcode = opcode + (ishl - ishll);
2269                     rtype = syms.intType;
2270                 }
2271                 // Generate code for right operand and load.
2272                 genExpr(rhs, rtype).load();
2273                 // If there are two consecutive opcode instructions,
2274                 // emit the first now.
2275                 if (opcode >= (1 << preShift)) {
2276                     code.emitop0(opcode >> preShift);
2277                     opcode = opcode & 0xFF;
2278                 }
2279             }
2280             if (opcode >= ifeq && opcode <= if_acmpne ||
2281                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
2282                 return items.makeCondItem(opcode);
2283             } else {
2284                 code.emitop0(opcode);
2285                 return items.makeStackItem(optype.restype);
2286             }
2287         }
2288 
2289     public void visitTypeCast(JCTypeCast tree) {
2290         result = genExpr(tree.expr, tree.clazz.type).load();
2291         setTypeAnnotationPositions(tree.pos);
2292         // Additional code is only needed if we cast to a reference type
2293         // which is not statically a supertype of the expression's type.
2294         // For basic types, the coerce(...) in genExpr(...) will do
2295         // the conversion.

2296         if (!tree.clazz.type.isPrimitive() &&
2297            !types.isSameType(tree.expr.type, tree.clazz.type) &&
2298            types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
2299             code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass);







2300         }
2301     }
2302 
2303     public void visitWildcard(JCWildcard tree) {
2304         throw new AssertionError(this.getClass().getName());
2305     }
2306 
2307     public void visitTypeTest(JCInstanceOf tree) {
2308         genExpr(tree.expr, tree.expr.type).load();
2309         setTypeAnnotationPositions(tree.pos);
2310         code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type));
2311         result = items.makeStackItem(syms.booleanType);
2312     }
2313 
2314     public void visitIndexed(JCArrayAccess tree) {
2315         genExpr(tree.indexed, tree.indexed.type).load();
2316         genExpr(tree.index, syms.intType).load();
2317         result = items.makeIndexedItem(tree.type);
2318     }
2319 
2320     public void visitIdent(JCIdent tree) {
2321         Symbol sym = tree.sym;
2322         if (tree.name == names._this || tree.name == names._super) {
2323             Item res = tree.name == names._this
2324                 ? items.makeThisItem()
2325                 : items.makeSuperItem();
2326             if (sym.kind == MTH) {
2327                 // Generate code to address the constructor.
2328                 res.load();
2329                 res = items.makeMemberItem(sym, true);
2330             }
2331             result = res;
2332        } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) {
2333             if (isConstantDynamic(sym)) {
2334                 setTypeAnnotationPositions(tree.pos);
2335             }
2336             result = items.makeDynamicItem(sym);
2337         } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) {
2338             result = items.makeLocalItem((VarSymbol)sym);
2339         } else if ((sym.flags() & STATIC) != 0) {
2340             if (!isAccessSuper(env.enclMethod))
2341                 sym = binaryQualifier(sym, env.enclClass.type);
2342             result = items.makeStaticItem(sym);
2343         } else {
2344             items.makeThisItem().load();
2345             sym = binaryQualifier(sym, env.enclClass.type);
2346             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2347         }
2348     }
2349 
2350     //where
2351     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2352         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2353                              !disableVirtualizedPrivateInvoke;
2354         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2355     }
2356 
2357     public void visitSelect(JCFieldAccess tree) {
2358         Symbol sym = tree.sym;
2359 
2360         if (tree.name == names._class) {
2361             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2362             result = items.makeStackItem(pt);
2363             return;
2364        }
2365 
2366         Symbol ssym = TreeInfo.symbol(tree.selected);
2367 
2368         // Are we selecting via super?
2369         boolean selectSuper =
2370             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2371 
2372         // Are we accessing a member of the superclass in an access method
2373         // resulting from a qualified super?
2374         boolean accessSuper = isAccessSuper(env.enclMethod);
2375 
2376         Item base = (selectSuper)
2377             ? items.makeSuperItem()
2378             : genExpr(tree.selected, tree.selected.type);
2379 
2380         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2381             // We are seeing a variable that is constant but its selecting
2382             // expression is not.
2383             if ((sym.flags() & STATIC) != 0) {
2384                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2385                     base = base.load();
2386                 base.drop();
2387             } else {
2388                 base.load();
2389                 genNullCheck(tree.selected);
2390             }
2391             result = items.
2392                 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue());
2393         } else {
2394             if (isInvokeDynamic(sym)) {
2395                 result = items.makeDynamicItem(sym);
2396                 return;
2397             } else {
2398                 sym = binaryQualifier(sym, tree.selected.type);
2399             }
2400             if ((sym.flags() & STATIC) != 0) {
2401                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2402                     base = base.load();
2403                 base.drop();
2404                 result = items.makeStaticItem(sym);
2405             } else {
2406                 base.load();
2407                 if (sym == syms.lengthVar) {
2408                     code.emitop0(arraylength);
2409                     result = items.makeStackItem(syms.intType);
2410                 } else {
2411                     result = items.
2412                         makeMemberItem(sym,
2413                                        nonVirtualForPrivateAccess(sym) ||
2414                                        selectSuper || accessSuper);
2415                 }
2416             }
2417         }
2418     }
2419 












2420     public boolean isInvokeDynamic(Symbol sym) {
2421         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
2422     }
2423 
2424     public void visitLiteral(JCLiteral tree) {
2425         if (tree.type.hasTag(BOT)) {
2426             code.emitop0(aconst_null);
2427             result = items.makeStackItem(tree.type);
2428         }
2429         else
2430             result = items.makeImmediateItem(tree.type, tree.value);
2431     }
2432 
2433     public void visitLetExpr(LetExpr tree) {
2434         code.resolvePending();
2435 
2436         int limit = code.nextreg;
2437         int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
2438         try {
2439             genStats(tree.defs, env);
2440         } finally {
2441             code.setLetExprStackPos(prevLetExprStart);
2442         }
2443         result = genExpr(tree.expr, tree.expr.type).load();
2444         code.endScopes(limit);
2445     }
2446 
2447     private void generateReferencesToPrunedTree(ClassSymbol classSymbol) {
2448         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
2449         if (prunedInfo != null) {
2450             for (JCTree prunedTree: prunedInfo) {
2451                 prunedTree.accept(classReferenceVisitor);
2452             }
2453         }
2454     }
2455 
2456 /* ************************************************************************
2457  * main method
2458  *************************************************************************/
2459 
2460     /** Generate code for a class definition.
2461      *  @param env   The attribution environment that belongs to the
2462      *               outermost class containing this class definition.
2463      *               We need this for resolving some additional symbols.
2464      *  @param cdef  The tree representing the class definition.
2465      *  @return      True if code is generated with no errors.
2466      */
2467     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
2468         try {
2469             attrEnv = env;
2470             ClassSymbol c = cdef.sym;
2471             this.toplevel = env.toplevel;
2472             this.endPosTable = toplevel.endPositions;
2473             /* method normalizeDefs() can add references to external classes into the constant pool
2474              */
2475             cdef.defs = normalizeDefs(cdef.defs, c);

2476             generateReferencesToPrunedTree(c);
2477             Env<GenContext> localEnv = new Env<>(cdef, new GenContext());
2478             localEnv.toplevel = env.toplevel;
2479             localEnv.enclClass = cdef;
2480 
2481             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2482                 genDef(l.head, localEnv);
2483             }
2484             if (poolWriter.size() > PoolWriter.MAX_ENTRIES) {
2485                 log.error(cdef.pos(), Errors.LimitPool);
2486                 nerrs++;
2487             }
2488             if (nerrs != 0) {
2489                 // if errors, discard code
2490                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2491                     if (l.head.hasTag(METHODDEF))
2492                         ((JCMethodDecl) l.head).sym.code = null;
2493                 }
2494             }
2495             cdef.defs = List.nil(); // discard trees
2496             return nerrs == 0;
2497         } finally {
2498             // note: this method does NOT support recursion.
2499             attrEnv = null;
2500             this.env = null;
2501             toplevel = null;
2502             endPosTable = null;
2503             nerrs = 0;
2504             qualifiedSymbolCache.clear();
2505         }
2506     }
2507 
2508 /* ************************************************************************
2509  * Auxiliary classes
2510  *************************************************************************/
2511 
2512     /** An abstract class for finalizer generation.
2513      */
2514     abstract class GenFinalizer {
2515         /** Generate code to clean up when unwinding. */
2516         abstract void gen();
2517 
2518         /** Generate code to clean up at last. */
2519         abstract void genLast();
2520 
2521         /** Does this finalizer have some nontrivial cleanup to perform? */
2522         boolean hasFinalizer() { return true; }
2523 
2524         /** Should be invoked after the try's body has been visited. */
2525         void afterBody() {}
2526     }
2527 
2528     /** code generation contexts,
2529      *  to be used as type parameter for environments.
2530      */
2531     static class GenContext {
2532 
2533         /** A chain for all unresolved jumps that exit the current environment.
2534          */
2535         Chain exit = null;
2536 
2537         /** A chain for all unresolved jumps that continue in the
2538          *  current environment.
2539          */
2540         Chain cont = null;
2541 
2542         /** A closure that generates the finalizer of the current environment.
2543          *  Only set for Synchronized and Try contexts.
2544          */
2545         GenFinalizer finalize = null;
2546 
2547         /** Is this a switch statement?  If so, allocate registers
2548          * even when the variable declaration is unreachable.
2549          */
2550         boolean isSwitch = false;
2551 
2552         /** A list buffer containing all gaps in the finalizer range,
2553          *  where a catch all exception should not apply.
2554          */
2555         ListBuffer<Integer> gaps = null;
2556 
2557         /** Add given chain to exit chain.
2558          */
2559         void addExit(Chain c)  {
2560             exit = Code.mergeChains(c, exit);
2561         }
2562 
2563         /** Add given chain to cont chain.
2564          */
2565         void addCont(Chain c) {
2566             cont = Code.mergeChains(c, cont);
2567         }
2568     }
2569 
2570 }
--- EOF ---