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

Fri, 18 Jun 2010 15:12:04 -0700

author
jrose
date
Fri, 18 Jun 2010 15:12:04 -0700
changeset 573
005bec70ca27
parent 554
9d9f26857129
parent 571
f0e3ec1f9d9f
child 591
d1d7595fa824
permissions
-rw-r--r--

Merge

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

mercurial