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

Tue, 16 Jun 2009 10:46:37 +0100

author
mcimadamore
date
Tue, 16 Jun 2009 10:46:37 +0100
changeset 299
22872b24d38c
parent 267
e2722bd43f3a
child 308
03944ee4fac4
permissions
-rw-r--r--

6638712: Inference with wildcard types causes selection of inapplicable method
Summary: Added global sanity check in order to make sure that return type inference does not violate bounds constraints
Reviewed-by: jjg

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

mercurial