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

Tue, 04 Feb 2020 17:57:00 +0800

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

mercurial