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

Mon, 14 Nov 2011 15:11:10 -0800

author
ksrini
date
Mon, 14 Nov 2011 15:11:10 -0800
changeset 1138
7375d4979bd3
parent 1127
ca49d50318dc
child 1157
3809292620c9
permissions
-rw-r--r--

7106166: (javac) re-factor EndPos parser
Reviewed-by: jjg

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

mercurial