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