src/share/classes/com/sun/tools/javac/jvm/Gen.java

Thu, 24 May 2018 16:48:51 +0800

author
aoqi
date
Thu, 24 May 2018 16:48:51 +0800
changeset 3295
859dc787b52b
parent 3000
4044eb07194d
parent 2893
ca5783d9a597
child 3446
e468915bad3a
permissions
-rw-r--r--

Merge

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

mercurial