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