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