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