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