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

Thu, 12 Oct 2017 19:50:01 +0800

author
aoqi
date
Thu, 12 Oct 2017 19:50:01 +0800
changeset 2702
9ca8d8713094
parent 2657
d42678403377
parent 2525
2eb010b6cb22
child 2893
ca5783d9a597
permissions
-rw-r--r--

merge

     1 /*
     2  * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.jvm;
    28 import java.util.*;
    30 import com.sun.tools.javac.util.*;
    31 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    32 import com.sun.tools.javac.util.List;
    33 import com.sun.tools.javac.code.*;
    34 import com.sun.tools.javac.code.Attribute.TypeCompound;
    35 import com.sun.tools.javac.code.Symbol.VarSymbol;
    36 import com.sun.tools.javac.comp.*;
    37 import com.sun.tools.javac.tree.*;
    39 import com.sun.tools.javac.code.Symbol.*;
    40 import com.sun.tools.javac.code.Type.*;
    41 import com.sun.tools.javac.jvm.Code.*;
    42 import com.sun.tools.javac.jvm.Items.*;
    43 import com.sun.tools.javac.tree.EndPosTable;
    44 import com.sun.tools.javac.tree.JCTree.*;
    46 import static com.sun.tools.javac.code.Flags.*;
    47 import static com.sun.tools.javac.code.Kinds.*;
    48 import static com.sun.tools.javac.code.TypeTag.*;
    49 import static com.sun.tools.javac.jvm.ByteCodes.*;
    50 import static com.sun.tools.javac.jvm.CRTFlags.*;
    51 import static com.sun.tools.javac.main.Option.*;
    52 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    54 /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
    55  *
    56  *  <p><b>This is NOT part of any supported API.
    57  *  If you write code that depends on this, you do so at your own risk.
    58  *  This code and its internal interfaces are subject to change or
    59  *  deletion without notice.</b>
    60  */
    61 public class Gen extends JCTree.Visitor {
    62     protected static final Context.Key<Gen> genKey =
    63         new Context.Key<Gen>();
    65     private final Log log;
    66     private final Symtab syms;
    67     private final Check chk;
    68     private final Resolve rs;
    69     private final TreeMaker make;
    70     private final Names names;
    71     private final Target target;
    72     private final Type stringBufferType;
    73     private final Map<Type,Symbol> stringBufferAppend;
    74     private Name accessDollar;
    75     private final Types types;
    76     private final Lower lower;
    77     private final Flow flow;
    79     /** Switch: GJ mode?
    80      */
    81     private final boolean allowGenerics;
    83     /** Set when Miranda method stubs are to be generated. */
    84     private final boolean generateIproxies;
    86     /** Format of stackmap tables to be generated. */
    87     private final Code.StackMapFormat stackMap;
    89     /** A type that serves as the expected type for all method expressions.
    90      */
    91     private final Type methodType;
    93     public static Gen instance(Context context) {
    94         Gen instance = context.get(genKey);
    95         if (instance == null)
    96             instance = new Gen(context);
    97         return instance;
    98     }
   100     /** Constant pool, reset by genClass.
   101      */
   102     private Pool pool;
   104     /** LVTRanges info.
   105      */
   106     private LVTRanges lvtRanges;
   108     private final boolean typeAnnoAsserts;
   110     protected Gen(Context context) {
   111         context.put(genKey, this);
   113         names = Names.instance(context);
   114         log = Log.instance(context);
   115         syms = Symtab.instance(context);
   116         chk = Check.instance(context);
   117         rs = Resolve.instance(context);
   118         make = TreeMaker.instance(context);
   119         target = Target.instance(context);
   120         types = Types.instance(context);
   121         methodType = new MethodType(null, null, null, syms.methodClass);
   122         allowGenerics = Source.instance(context).allowGenerics();
   123         stringBufferType = target.useStringBuilder()
   124             ? syms.stringBuilderType
   125             : syms.stringBufferType;
   126         stringBufferAppend = new HashMap<Type,Symbol>();
   127         accessDollar = names.
   128             fromString("access" + target.syntheticNameChar());
   129         flow = Flow.instance(context);
   130         lower = Lower.instance(context);
   132         Options options = Options.instance(context);
   133         lineDebugInfo =
   134             options.isUnset(G_CUSTOM) ||
   135             options.isSet(G_CUSTOM, "lines");
   136         varDebugInfo =
   137             options.isUnset(G_CUSTOM)
   138             ? options.isSet(G)
   139             : options.isSet(G_CUSTOM, "vars");
   140         if (varDebugInfo) {
   141             lvtRanges = LVTRanges.instance(context);
   142         }
   143         genCrt = options.isSet(XJCOV);
   144         debugCode = options.isSet("debugcode");
   145         allowInvokedynamic = target.hasInvokedynamic() || options.isSet("invokedynamic");
   146         pool = new Pool(types);
   147         typeAnnoAsserts = options.isSet("TypeAnnotationAsserts");
   149         generateIproxies =
   150             target.requiresIproxy() ||
   151             options.isSet("miranda");
   153         if (target.generateStackMapTable()) {
   154             // ignore cldc because we cannot have both stackmap formats
   155             this.stackMap = StackMapFormat.JSR202;
   156         } else {
   157             if (target.generateCLDCStackmap()) {
   158                 this.stackMap = StackMapFormat.CLDC;
   159             } else {
   160                 this.stackMap = StackMapFormat.NONE;
   161             }
   162         }
   164         // by default, avoid jsr's for simple finalizers
   165         int setjsrlimit = 50;
   166         String jsrlimitString = options.get("jsrlimit");
   167         if (jsrlimitString != null) {
   168             try {
   169                 setjsrlimit = Integer.parseInt(jsrlimitString);
   170             } catch (NumberFormatException ex) {
   171                 // ignore ill-formed numbers for jsrlimit
   172             }
   173         }
   174         this.jsrlimit = setjsrlimit;
   175         this.useJsrLocally = false; // reset in visitTry
   176     }
   178     /** Switches
   179      */
   180     private final boolean lineDebugInfo;
   181     private final boolean varDebugInfo;
   182     private final boolean genCrt;
   183     private final boolean debugCode;
   184     private final boolean allowInvokedynamic;
   186     /** Default limit of (approximate) size of finalizer to inline.
   187      *  Zero means always use jsr.  100 or greater means never use
   188      *  jsr.
   189      */
   190     private final int jsrlimit;
   192     /** True if jsr is used.
   193      */
   194     private boolean useJsrLocally;
   196     /** Code buffer, set by genMethod.
   197      */
   198     private Code code;
   200     /** Items structure, set by genMethod.
   201      */
   202     private Items items;
   204     /** Environment for symbol lookup, set by genClass
   205      */
   206     private Env<AttrContext> attrEnv;
   208     /** The top level tree.
   209      */
   210     private JCCompilationUnit toplevel;
   212     /** The number of code-gen errors in this class.
   213      */
   214     private int nerrs = 0;
   216     /** An object containing mappings of syntax trees to their
   217      *  ending source positions.
   218      */
   219     EndPosTable endPosTable;
   221     /** Generate code to load an integer constant.
   222      *  @param n     The integer to be loaded.
   223      */
   224     void loadIntConst(int n) {
   225         items.makeImmediateItem(syms.intType, n).load();
   226     }
   228     /** The opcode that loads a zero constant of a given type code.
   229      *  @param tc   The given type code (@see ByteCode).
   230      */
   231     public static int zero(int tc) {
   232         switch(tc) {
   233         case INTcode: case BYTEcode: case SHORTcode: case CHARcode:
   234             return iconst_0;
   235         case LONGcode:
   236             return lconst_0;
   237         case FLOATcode:
   238             return fconst_0;
   239         case DOUBLEcode:
   240             return dconst_0;
   241         default:
   242             throw new AssertionError("zero");
   243         }
   244     }
   246     /** The opcode that loads a one constant of a given type code.
   247      *  @param tc   The given type code (@see ByteCode).
   248      */
   249     public static int one(int tc) {
   250         return zero(tc) + 1;
   251     }
   253     /** Generate code to load -1 of the given type code (either int or long).
   254      *  @param tc   The given type code (@see ByteCode).
   255      */
   256     void emitMinusOne(int tc) {
   257         if (tc == LONGcode) {
   258             items.makeImmediateItem(syms.longType, new Long(-1)).load();
   259         } else {
   260             code.emitop0(iconst_m1);
   261         }
   262     }
   264     /** Construct a symbol to reflect the qualifying type that should
   265      *  appear in the byte code as per JLS 13.1.
   266      *
   267      *  For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except
   268      *  for those cases where we need to work around VM bugs).
   269      *
   270      *  For {@literal target <= 1.1}: If qualified variable or method is defined in a
   271      *  non-accessible class, clone it with the qualifier class as owner.
   272      *
   273      *  @param sym    The accessed symbol
   274      *  @param site   The qualifier's type.
   275      */
   276     Symbol binaryQualifier(Symbol sym, Type site) {
   278         if (site.hasTag(ARRAY)) {
   279             if (sym == syms.lengthVar ||
   280                 sym.owner != syms.arrayClass)
   281                 return sym;
   282             // array clone can be qualified by the array type in later targets
   283             Symbol qualifier = target.arrayBinaryCompatibility()
   284                 ? new ClassSymbol(Flags.PUBLIC, site.tsym.name,
   285                                   site, syms.noSymbol)
   286                 : syms.objectType.tsym;
   287             return sym.clone(qualifier);
   288         }
   290         if (sym.owner == site.tsym ||
   291             (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
   292             return sym;
   293         }
   294         if (!target.obeyBinaryCompatibility())
   295             return rs.isAccessible(attrEnv, (TypeSymbol)sym.owner)
   296                 ? sym
   297                 : sym.clone(site.tsym);
   299         if (!target.interfaceFieldsBinaryCompatibility()) {
   300             if ((sym.owner.flags() & INTERFACE) != 0 && sym.kind == VAR)
   301                 return sym;
   302         }
   304         // leave alone methods inherited from Object
   305         // JLS 13.1.
   306         if (sym.owner == syms.objectType.tsym)
   307             return sym;
   309         if (!target.interfaceObjectOverridesBinaryCompatibility()) {
   310             if ((sym.owner.flags() & INTERFACE) != 0 &&
   311                 syms.objectType.tsym.members().lookup(sym.name).scope != null)
   312                 return sym;
   313         }
   315         return sym.clone(site.tsym);
   316     }
   318     /** Insert a reference to given type in the constant pool,
   319      *  checking for an array with too many dimensions;
   320      *  return the reference's index.
   321      *  @param type   The type for which a reference is inserted.
   322      */
   323     int makeRef(DiagnosticPosition pos, Type type) {
   324         checkDimension(pos, type);
   325         if (type.isAnnotated()) {
   326             // Treat annotated types separately - we don't want
   327             // to collapse all of them - at least for annotated
   328             // exceptions.
   329             // TODO: review this.
   330             return pool.put((Object)type);
   331         } else {
   332             return pool.put(type.hasTag(CLASS) ? (Object)type.tsym : (Object)type);
   333         }
   334     }
   336     /** Check if the given type is an array with too many dimensions.
   337      */
   338     private void checkDimension(DiagnosticPosition pos, Type t) {
   339         switch (t.getTag()) {
   340         case METHOD:
   341             checkDimension(pos, t.getReturnType());
   342             for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
   343                 checkDimension(pos, args.head);
   344             break;
   345         case ARRAY:
   346             if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
   347                 log.error(pos, "limit.dimensions");
   348                 nerrs++;
   349             }
   350             break;
   351         default:
   352             break;
   353         }
   354     }
   356     /** Create a tempory variable.
   357      *  @param type   The variable's type.
   358      */
   359     LocalItem makeTemp(Type type) {
   360         VarSymbol v = new VarSymbol(Flags.SYNTHETIC,
   361                                     names.empty,
   362                                     type,
   363                                     env.enclMethod.sym);
   364         code.newLocal(v);
   365         return items.makeLocalItem(v);
   366     }
   368     /** Generate code to call a non-private method or constructor.
   369      *  @param pos         Position to be used for error reporting.
   370      *  @param site        The type of which the method is a member.
   371      *  @param name        The method's name.
   372      *  @param argtypes    The method's argument types.
   373      *  @param isStatic    A flag that indicates whether we call a
   374      *                     static or instance method.
   375      */
   376     void callMethod(DiagnosticPosition pos,
   377                     Type site, Name name, List<Type> argtypes,
   378                     boolean isStatic) {
   379         Symbol msym = rs.
   380             resolveInternalMethod(pos, attrEnv, site, name, argtypes, null);
   381         if (isStatic) items.makeStaticItem(msym).invoke();
   382         else items.makeMemberItem(msym, name == names.init).invoke();
   383     }
   385     /** Is the given method definition an access method
   386      *  resulting from a qualified super? This is signified by an odd
   387      *  access code.
   388      */
   389     private boolean isAccessSuper(JCMethodDecl enclMethod) {
   390         return
   391             (enclMethod.mods.flags & SYNTHETIC) != 0 &&
   392             isOddAccessName(enclMethod.name);
   393     }
   395     /** Does given name start with "access$" and end in an odd digit?
   396      */
   397     private boolean isOddAccessName(Name name) {
   398         return
   399             name.startsWith(accessDollar) &&
   400             (name.getByteAt(name.getByteLength() - 1) & 1) == 1;
   401     }
   403 /* ************************************************************************
   404  * Non-local exits
   405  *************************************************************************/
   407     /** Generate code to invoke the finalizer associated with given
   408      *  environment.
   409      *  Any calls to finalizers are appended to the environments `cont' chain.
   410      *  Mark beginning of gap in catch all range for finalizer.
   411      */
   412     void genFinalizer(Env<GenContext> env) {
   413         if (code.isAlive() && env.info.finalize != null)
   414             env.info.finalize.gen();
   415     }
   417     /** Generate code to call all finalizers of structures aborted by
   418      *  a non-local
   419      *  exit.  Return target environment of the non-local exit.
   420      *  @param target      The tree representing the structure that's aborted
   421      *  @param env         The environment current at the non-local exit.
   422      */
   423     Env<GenContext> unwind(JCTree target, Env<GenContext> env) {
   424         Env<GenContext> env1 = env;
   425         while (true) {
   426             genFinalizer(env1);
   427             if (env1.tree == target) break;
   428             env1 = env1.next;
   429         }
   430         return env1;
   431     }
   433     /** Mark end of gap in catch-all range for finalizer.
   434      *  @param env   the environment which might contain the finalizer
   435      *               (if it does, env.info.gaps != null).
   436      */
   437     void endFinalizerGap(Env<GenContext> env) {
   438         if (env.info.gaps != null && env.info.gaps.length() % 2 == 1)
   439             env.info.gaps.append(code.curCP());
   440     }
   442     /** Mark end of all gaps in catch-all ranges for finalizers of environments
   443      *  lying between, and including to two environments.
   444      *  @param from    the most deeply nested environment to mark
   445      *  @param to      the least deeply nested environment to mark
   446      */
   447     void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) {
   448         Env<GenContext> last = null;
   449         while (last != to) {
   450             endFinalizerGap(from);
   451             last = from;
   452             from = from.next;
   453         }
   454     }
   456     /** Do any of the structures aborted by a non-local exit have
   457      *  finalizers that require an empty stack?
   458      *  @param target      The tree representing the structure that's aborted
   459      *  @param env         The environment current at the non-local exit.
   460      */
   461     boolean hasFinally(JCTree target, Env<GenContext> env) {
   462         while (env.tree != target) {
   463             if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
   464                 return true;
   465             env = env.next;
   466         }
   467         return false;
   468     }
   470 /* ************************************************************************
   471  * Normalizing class-members.
   472  *************************************************************************/
   474     /** Distribute member initializer code into constructors and {@code <clinit>}
   475      *  method.
   476      *  @param defs         The list of class member declarations.
   477      *  @param c            The enclosing class.
   478      */
   479     List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
   480         ListBuffer<JCStatement> initCode = new ListBuffer<JCStatement>();
   481         ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<Attribute.TypeCompound>();
   482         ListBuffer<JCStatement> clinitCode = new ListBuffer<JCStatement>();
   483         ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<Attribute.TypeCompound>();
   484         ListBuffer<JCTree> methodDefs = new ListBuffer<JCTree>();
   485         // Sort definitions into three listbuffers:
   486         //  - initCode for instance initializers
   487         //  - clinitCode for class initializers
   488         //  - methodDefs for method definitions
   489         for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
   490             JCTree def = l.head;
   491             switch (def.getTag()) {
   492             case BLOCK:
   493                 JCBlock block = (JCBlock)def;
   494                 if ((block.flags & STATIC) != 0)
   495                     clinitCode.append(block);
   496                 else
   497                     initCode.append(block);
   498                 break;
   499             case METHODDEF:
   500                 methodDefs.append(def);
   501                 break;
   502             case VARDEF:
   503                 JCVariableDecl vdef = (JCVariableDecl) def;
   504                 VarSymbol sym = vdef.sym;
   505                 checkDimension(vdef.pos(), sym.type);
   506                 if (vdef.init != null) {
   507                     if ((sym.flags() & STATIC) == 0) {
   508                         // Always initialize instance variables.
   509                         JCStatement init = make.at(vdef.pos()).
   510                             Assignment(sym, vdef.init);
   511                         initCode.append(init);
   512                         endPosTable.replaceTree(vdef, init);
   513                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
   514                     } else if (sym.getConstValue() == null) {
   515                         // Initialize class (static) variables only if
   516                         // they are not compile-time constants.
   517                         JCStatement init = make.at(vdef.pos).
   518                             Assignment(sym, vdef.init);
   519                         clinitCode.append(init);
   520                         endPosTable.replaceTree(vdef, init);
   521                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
   522                     } else {
   523                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
   524                     }
   525                 }
   526                 break;
   527             default:
   528                 Assert.error();
   529             }
   530         }
   531         // Insert any instance initializers into all constructors.
   532         if (initCode.length() != 0) {
   533             List<JCStatement> inits = initCode.toList();
   534             initTAs.addAll(c.getInitTypeAttributes());
   535             List<Attribute.TypeCompound> initTAlist = initTAs.toList();
   536             for (JCTree t : methodDefs) {
   537                 normalizeMethod((JCMethodDecl)t, inits, initTAlist);
   538             }
   539         }
   540         // If there are class initializers, create a <clinit> method
   541         // that contains them as its body.
   542         if (clinitCode.length() != 0) {
   543             MethodSymbol clinit = new MethodSymbol(
   544                 STATIC | (c.flags() & STRICTFP),
   545                 names.clinit,
   546                 new MethodType(
   547                     List.<Type>nil(), syms.voidType,
   548                     List.<Type>nil(), syms.methodClass),
   549                 c);
   550             c.members().enter(clinit);
   551             List<JCStatement> clinitStats = clinitCode.toList();
   552             JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
   553             block.endpos = TreeInfo.endPos(clinitStats.last());
   554             methodDefs.append(make.MethodDef(clinit, block));
   556             if (!clinitTAs.isEmpty())
   557                 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
   558             if (!c.getClassInitTypeAttributes().isEmpty())
   559                 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes());
   560         }
   561         // Return all method definitions.
   562         return methodDefs.toList();
   563     }
   565     private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) {
   566         List<TypeCompound> tas = sym.getRawTypeAttributes();
   567         ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<Attribute.TypeCompound>();
   568         ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<Attribute.TypeCompound>();
   569         for (TypeCompound ta : tas) {
   570             if (ta.getPosition().type == TargetType.FIELD) {
   571                 fieldTAs.add(ta);
   572             } else {
   573                 if (typeAnnoAsserts) {
   574                     Assert.error("Type annotation does not have a valid positior");
   575                 }
   577                 nonfieldTAs.add(ta);
   578             }
   579         }
   580         sym.setTypeAttributes(fieldTAs.toList());
   581         return nonfieldTAs.toList();
   582     }
   584     /** Check a constant value and report if it is a string that is
   585      *  too large.
   586      */
   587     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
   588         if (nerrs != 0 || // only complain about a long string once
   589             constValue == null ||
   590             !(constValue instanceof String) ||
   591             ((String)constValue).length() < Pool.MAX_STRING_LENGTH)
   592             return;
   593         log.error(pos, "limit.string");
   594         nerrs++;
   595     }
   597     /** Insert instance initializer code into initial constructor.
   598      *  @param md        The tree potentially representing a
   599      *                   constructor's definition.
   600      *  @param initCode  The list of instance initializer statements.
   601      *  @param initTAs  Type annotations from the initializer expression.
   602      */
   603     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
   604         if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
   605             // We are seeing a constructor that does not call another
   606             // constructor of the same class.
   607             List<JCStatement> stats = md.body.stats;
   608             ListBuffer<JCStatement> newstats = new ListBuffer<JCStatement>();
   610             if (stats.nonEmpty()) {
   611                 // Copy initializers of synthetic variables generated in
   612                 // the translation of inner classes.
   613                 while (TreeInfo.isSyntheticInit(stats.head)) {
   614                     newstats.append(stats.head);
   615                     stats = stats.tail;
   616                 }
   617                 // Copy superclass constructor call
   618                 newstats.append(stats.head);
   619                 stats = stats.tail;
   620                 // Copy remaining synthetic initializers.
   621                 while (stats.nonEmpty() &&
   622                        TreeInfo.isSyntheticInit(stats.head)) {
   623                     newstats.append(stats.head);
   624                     stats = stats.tail;
   625                 }
   626                 // Now insert the initializer code.
   627                 newstats.appendList(initCode);
   628                 // And copy all remaining statements.
   629                 while (stats.nonEmpty()) {
   630                     newstats.append(stats.head);
   631                     stats = stats.tail;
   632                 }
   633             }
   634             md.body.stats = newstats.toList();
   635             if (md.body.endpos == Position.NOPOS)
   636                 md.body.endpos = TreeInfo.endPos(md.body.stats.last());
   638             md.sym.appendUniqueTypeAttributes(initTAs);
   639         }
   640     }
   642 /* ********************************************************************
   643  * Adding miranda methods
   644  *********************************************************************/
   646     /** Add abstract methods for all methods defined in one of
   647      *  the interfaces of a given class,
   648      *  provided they are not already implemented in the class.
   649      *
   650      *  @param c      The class whose interfaces are searched for methods
   651      *                for which Miranda methods should be added.
   652      */
   653     void implementInterfaceMethods(ClassSymbol c) {
   654         implementInterfaceMethods(c, c);
   655     }
   657     /** Add abstract methods for all methods defined in one of
   658      *  the interfaces of a given class,
   659      *  provided they are not already implemented in the class.
   660      *
   661      *  @param c      The class whose interfaces are searched for methods
   662      *                for which Miranda methods should be added.
   663      *  @param site   The class in which a definition may be needed.
   664      */
   665     void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
   666         for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
   667             ClassSymbol i = (ClassSymbol)l.head.tsym;
   668             for (Scope.Entry e = i.members().elems;
   669                  e != null;
   670                  e = e.sibling)
   671             {
   672                 if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
   673                 {
   674                     MethodSymbol absMeth = (MethodSymbol)e.sym;
   675                     MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
   676                     if (implMeth == null)
   677                         addAbstractMethod(site, absMeth);
   678                     else if ((implMeth.flags() & IPROXY) != 0)
   679                         adjustAbstractMethod(site, implMeth, absMeth);
   680                 }
   681             }
   682             implementInterfaceMethods(i, site);
   683         }
   684     }
   686     /** Add an abstract methods to a class
   687      *  which implicitly implements a method defined in some interface
   688      *  implemented by the class. These methods are called "Miranda methods".
   689      *  Enter the newly created method into its enclosing class scope.
   690      *  Note that it is not entered into the class tree, as the emitter
   691      *  doesn't need to see it there to emit an abstract method.
   692      *
   693      *  @param c      The class to which the Miranda method is added.
   694      *  @param m      The interface method symbol for which a Miranda method
   695      *                is added.
   696      */
   697     private void addAbstractMethod(ClassSymbol c,
   698                                    MethodSymbol m) {
   699         MethodSymbol absMeth = new MethodSymbol(
   700             m.flags() | IPROXY | SYNTHETIC, m.name,
   701             m.type, // was c.type.memberType(m), but now only !generics supported
   702             c);
   703         c.members().enter(absMeth); // add to symbol table
   704     }
   706     private void adjustAbstractMethod(ClassSymbol c,
   707                                       MethodSymbol pm,
   708                                       MethodSymbol im) {
   709         MethodType pmt = (MethodType)pm.type;
   710         Type imt = types.memberType(c.type, im);
   711         pmt.thrown = chk.intersect(pmt.getThrownTypes(), imt.getThrownTypes());
   712     }
   714 /* ************************************************************************
   715  * Traversal methods
   716  *************************************************************************/
   718     /** Visitor argument: The current environment.
   719      */
   720     Env<GenContext> env;
   722     /** Visitor argument: The expected type (prototype).
   723      */
   724     Type pt;
   726     /** Visitor result: The item representing the computed value.
   727      */
   728     Item result;
   730     /** Visitor method: generate code for a definition, catching and reporting
   731      *  any completion failures.
   732      *  @param tree    The definition to be visited.
   733      *  @param env     The environment current at the definition.
   734      */
   735     public void genDef(JCTree tree, Env<GenContext> env) {
   736         Env<GenContext> prevEnv = this.env;
   737         try {
   738             this.env = env;
   739             tree.accept(this);
   740         } catch (CompletionFailure ex) {
   741             chk.completionError(tree.pos(), ex);
   742         } finally {
   743             this.env = prevEnv;
   744         }
   745     }
   747     /** Derived visitor method: check whether CharacterRangeTable
   748      *  should be emitted, if so, put a new entry into CRTable
   749      *  and call method to generate bytecode.
   750      *  If not, just call method to generate bytecode.
   751      *  @see    #genStat(JCTree, Env)
   752      *
   753      *  @param  tree     The tree to be visited.
   754      *  @param  env      The environment to use.
   755      *  @param  crtFlags The CharacterRangeTable flags
   756      *                   indicating type of the entry.
   757      */
   758     public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) {
   759         if (!genCrt) {
   760             genStat(tree, env);
   761             return;
   762         }
   763         int startpc = code.curCP();
   764         genStat(tree, env);
   765         if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK;
   766         code.crt.put(tree, crtFlags, startpc, code.curCP());
   767     }
   769     /** Derived visitor method: generate code for a statement.
   770      */
   771     public void genStat(JCTree tree, Env<GenContext> env) {
   772         if (code.isAlive()) {
   773             code.statBegin(tree.pos);
   774             genDef(tree, env);
   775         } else if (env.info.isSwitch && tree.hasTag(VARDEF)) {
   776             // variables whose declarations are in a switch
   777             // can be used even if the decl is unreachable.
   778             code.newLocal(((JCVariableDecl) tree).sym);
   779         }
   780     }
   782     /** Derived visitor method: check whether CharacterRangeTable
   783      *  should be emitted, if so, put a new entry into CRTable
   784      *  and call method to generate bytecode.
   785      *  If not, just call method to generate bytecode.
   786      *  @see    #genStats(List, Env)
   787      *
   788      *  @param  trees    The list of trees to be visited.
   789      *  @param  env      The environment to use.
   790      *  @param  crtFlags The CharacterRangeTable flags
   791      *                   indicating type of the entry.
   792      */
   793     public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) {
   794         if (!genCrt) {
   795             genStats(trees, env);
   796             return;
   797         }
   798         if (trees.length() == 1) {        // mark one statement with the flags
   799             genStat(trees.head, env, crtFlags | CRT_STATEMENT);
   800         } else {
   801             int startpc = code.curCP();
   802             genStats(trees, env);
   803             code.crt.put(trees, crtFlags, startpc, code.curCP());
   804         }
   805     }
   807     /** Derived visitor method: generate code for a list of statements.
   808      */
   809     public void genStats(List<? extends JCTree> trees, Env<GenContext> env) {
   810         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   811             genStat(l.head, env, CRT_STATEMENT);
   812     }
   814     /** Derived visitor method: check whether CharacterRangeTable
   815      *  should be emitted, if so, put a new entry into CRTable
   816      *  and call method to generate bytecode.
   817      *  If not, just call method to generate bytecode.
   818      *  @see    #genCond(JCTree,boolean)
   819      *
   820      *  @param  tree     The tree to be visited.
   821      *  @param  crtFlags The CharacterRangeTable flags
   822      *                   indicating type of the entry.
   823      */
   824     public CondItem genCond(JCTree tree, int crtFlags) {
   825         if (!genCrt) return genCond(tree, false);
   826         int startpc = code.curCP();
   827         CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0);
   828         code.crt.put(tree, crtFlags, startpc, code.curCP());
   829         return item;
   830     }
   832     /** Derived visitor method: generate code for a boolean
   833      *  expression in a control-flow context.
   834      *  @param _tree         The expression to be visited.
   835      *  @param markBranches The flag to indicate that the condition is
   836      *                      a flow controller so produced conditions
   837      *                      should contain a proper tree to generate
   838      *                      CharacterRangeTable branches for them.
   839      */
   840     public CondItem genCond(JCTree _tree, boolean markBranches) {
   841         JCTree inner_tree = TreeInfo.skipParens(_tree);
   842         if (inner_tree.hasTag(CONDEXPR)) {
   843             JCConditional tree = (JCConditional)inner_tree;
   844             CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER);
   845             if (cond.isTrue()) {
   846                 code.resolve(cond.trueJumps);
   847                 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET);
   848                 if (markBranches) result.tree = tree.truepart;
   849                 return result;
   850             }
   851             if (cond.isFalse()) {
   852                 code.resolve(cond.falseJumps);
   853                 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET);
   854                 if (markBranches) result.tree = tree.falsepart;
   855                 return result;
   856             }
   857             Chain secondJumps = cond.jumpFalse();
   858             code.resolve(cond.trueJumps);
   859             CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET);
   860             if (markBranches) first.tree = tree.truepart;
   861             Chain falseJumps = first.jumpFalse();
   862             code.resolve(first.trueJumps);
   863             Chain trueJumps = code.branch(goto_);
   864             code.resolve(secondJumps);
   865             CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET);
   866             CondItem result = items.makeCondItem(second.opcode,
   867                                       Code.mergeChains(trueJumps, second.trueJumps),
   868                                       Code.mergeChains(falseJumps, second.falseJumps));
   869             if (markBranches) result.tree = tree.falsepart;
   870             return result;
   871         } else {
   872             CondItem result = genExpr(_tree, syms.booleanType).mkCond();
   873             if (markBranches) result.tree = _tree;
   874             return result;
   875         }
   876     }
   878     /** Visitor class for expressions which might be constant expressions.
   879      *  This class is a subset of TreeScanner. Intended to visit trees pruned by
   880      *  Lower as long as constant expressions looking for references to any
   881      *  ClassSymbol. Any such reference will be added to the constant pool so
   882      *  automated tools can detect class dependencies better.
   883      */
   884     class ClassReferenceVisitor extends JCTree.Visitor {
   886         @Override
   887         public void visitTree(JCTree tree) {}
   889         @Override
   890         public void visitBinary(JCBinary tree) {
   891             tree.lhs.accept(this);
   892             tree.rhs.accept(this);
   893         }
   895         @Override
   896         public void visitSelect(JCFieldAccess tree) {
   897             if (tree.selected.type.hasTag(CLASS)) {
   898                 makeRef(tree.selected.pos(), tree.selected.type);
   899             }
   900         }
   902         @Override
   903         public void visitIdent(JCIdent tree) {
   904             if (tree.sym.owner instanceof ClassSymbol) {
   905                 pool.put(tree.sym.owner);
   906             }
   907         }
   909         @Override
   910         public void visitConditional(JCConditional tree) {
   911             tree.cond.accept(this);
   912             tree.truepart.accept(this);
   913             tree.falsepart.accept(this);
   914         }
   916         @Override
   917         public void visitUnary(JCUnary tree) {
   918             tree.arg.accept(this);
   919         }
   921         @Override
   922         public void visitParens(JCParens tree) {
   923             tree.expr.accept(this);
   924         }
   926         @Override
   927         public void visitTypeCast(JCTypeCast tree) {
   928             tree.expr.accept(this);
   929         }
   930     }
   932     private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor();
   934     /** Visitor method: generate code for an expression, catching and reporting
   935      *  any completion failures.
   936      *  @param tree    The expression to be visited.
   937      *  @param pt      The expression's expected type (proto-type).
   938      */
   939     public Item genExpr(JCTree tree, Type pt) {
   940         Type prevPt = this.pt;
   941         try {
   942             if (tree.type.constValue() != null) {
   943                 // Short circuit any expressions which are constants
   944                 tree.accept(classReferenceVisitor);
   945                 checkStringConstant(tree.pos(), tree.type.constValue());
   946                 result = items.makeImmediateItem(tree.type, tree.type.constValue());
   947             } else {
   948                 this.pt = pt;
   949                 tree.accept(this);
   950             }
   951             return result.coerce(pt);
   952         } catch (CompletionFailure ex) {
   953             chk.completionError(tree.pos(), ex);
   954             code.state.stacksize = 1;
   955             return items.makeStackItem(pt);
   956         } finally {
   957             this.pt = prevPt;
   958         }
   959     }
   961     /** Derived visitor method: generate code for a list of method arguments.
   962      *  @param trees    The argument expressions to be visited.
   963      *  @param pts      The expression's expected types (i.e. the formal parameter
   964      *                  types of the invoked method).
   965      */
   966     public void genArgs(List<JCExpression> trees, List<Type> pts) {
   967         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
   968             genExpr(l.head, pts.head).load();
   969             pts = pts.tail;
   970         }
   971         // require lists be of same length
   972         Assert.check(pts.isEmpty());
   973     }
   975 /* ************************************************************************
   976  * Visitor methods for statements and definitions
   977  *************************************************************************/
   979     /** Thrown when the byte code size exceeds limit.
   980      */
   981     public static class CodeSizeOverflow extends RuntimeException {
   982         private static final long serialVersionUID = 0;
   983         public CodeSizeOverflow() {}
   984     }
   986     public void visitMethodDef(JCMethodDecl tree) {
   987         // Create a new local environment that points pack at method
   988         // definition.
   989         Env<GenContext> localEnv = env.dup(tree);
   990         localEnv.enclMethod = tree;
   991         // The expected type of every return statement in this method
   992         // is the method's return type.
   993         this.pt = tree.sym.erasure(types).getReturnType();
   995         checkDimension(tree.pos(), tree.sym.erasure(types));
   996         genMethod(tree, localEnv, false);
   997     }
   998 //where
   999         /** Generate code for a method.
  1000          *  @param tree     The tree representing the method definition.
  1001          *  @param env      The environment current for the method body.
  1002          *  @param fatcode  A flag that indicates whether all jumps are
  1003          *                  within 32K.  We first invoke this method under
  1004          *                  the assumption that fatcode == false, i.e. all
  1005          *                  jumps are within 32K.  If this fails, fatcode
  1006          *                  is set to true and we try again.
  1007          */
  1008         void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
  1009             MethodSymbol meth = tree.sym;
  1010             int extras = 0;
  1011             // Count up extra parameters
  1012             if (meth.isConstructor()) {
  1013                 extras++;
  1014                 if (meth.enclClass().isInner() &&
  1015                     !meth.enclClass().isStatic()) {
  1016                     extras++;
  1018             } else if ((tree.mods.flags & STATIC) == 0) {
  1019                 extras++;
  1021             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
  1022             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
  1023                 ClassFile.MAX_PARAMETERS) {
  1024                 log.error(tree.pos(), "limit.parameters");
  1025                 nerrs++;
  1028             else if (tree.body != null) {
  1029                 // Create a new code structure and initialize it.
  1030                 int startpcCrt = initCode(tree, env, fatcode);
  1032                 try {
  1033                     genStat(tree.body, env);
  1034                 } catch (CodeSizeOverflow e) {
  1035                     // Failed due to code limit, try again with jsr/ret
  1036                     startpcCrt = initCode(tree, env, fatcode);
  1037                     genStat(tree.body, env);
  1040                 if (code.state.stacksize != 0) {
  1041                     log.error(tree.body.pos(), "stack.sim.error", tree);
  1042                     throw new AssertionError();
  1045                 // If last statement could complete normally, insert a
  1046                 // return at the end.
  1047                 if (code.isAlive()) {
  1048                     code.statBegin(TreeInfo.endPos(tree.body));
  1049                     if (env.enclMethod == null ||
  1050                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
  1051                         code.emitop0(return_);
  1052                     } else {
  1053                         // sometime dead code seems alive (4415991);
  1054                         // generate a small loop instead
  1055                         int startpc = code.entryPoint();
  1056                         CondItem c = items.makeCondItem(goto_);
  1057                         code.resolve(c.jumpTrue(), startpc);
  1060                 if (genCrt)
  1061                     code.crt.put(tree.body,
  1062                                  CRT_BLOCK,
  1063                                  startpcCrt,
  1064                                  code.curCP());
  1066                 code.endScopes(0);
  1068                 // If we exceeded limits, panic
  1069                 if (code.checkLimits(tree.pos(), log)) {
  1070                     nerrs++;
  1071                     return;
  1074                 // If we generated short code but got a long jump, do it again
  1075                 // with fatCode = true.
  1076                 if (!fatcode && code.fatcode) genMethod(tree, env, true);
  1078                 // Clean up
  1079                 if(stackMap == StackMapFormat.JSR202) {
  1080                     code.lastFrame = null;
  1081                     code.frameBeforeLast = null;
  1084                 // Compress exception table
  1085                 code.compressCatchTable();
  1087                 // Fill in type annotation positions for exception parameters
  1088                 code.fillExceptionParameterPositions();
  1092         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
  1093             MethodSymbol meth = tree.sym;
  1095             // Create a new code structure.
  1096             meth.code = code = new Code(meth,
  1097                                         fatcode,
  1098                                         lineDebugInfo ? toplevel.lineMap : null,
  1099                                         varDebugInfo,
  1100                                         stackMap,
  1101                                         debugCode,
  1102                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
  1103                                                : null,
  1104                                         syms,
  1105                                         types,
  1106                                         pool,
  1107                                         varDebugInfo ? lvtRanges : null);
  1108             items = new Items(pool, code, syms, types);
  1109             if (code.debugCode) {
  1110                 System.err.println(meth + " for body " + tree);
  1113             // If method is not static, create a new local variable address
  1114             // for `this'.
  1115             if ((tree.mods.flags & STATIC) == 0) {
  1116                 Type selfType = meth.owner.type;
  1117                 if (meth.isConstructor() && selfType != syms.objectType)
  1118                     selfType = UninitializedType.uninitializedThis(selfType);
  1119                 code.setDefined(
  1120                         code.newLocal(
  1121                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
  1124             // Mark all parameters as defined from the beginning of
  1125             // the method.
  1126             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
  1127                 checkDimension(l.head.pos(), l.head.sym.type);
  1128                 code.setDefined(code.newLocal(l.head.sym));
  1131             // Get ready to generate code for method body.
  1132             int startpcCrt = genCrt ? code.curCP() : 0;
  1133             code.entryPoint();
  1135             // Suppress initial stackmap
  1136             code.pendingStackMap = false;
  1138             return startpcCrt;
  1141     public void visitVarDef(JCVariableDecl tree) {
  1142         VarSymbol v = tree.sym;
  1143         code.newLocal(v);
  1144         if (tree.init != null) {
  1145             checkStringConstant(tree.init.pos(), v.getConstValue());
  1146             if (v.getConstValue() == null || varDebugInfo) {
  1147                 genExpr(tree.init, v.erasure(types)).load();
  1148                 items.makeLocalItem(v).store();
  1151         checkDimension(tree.pos(), v.type);
  1154     public void visitSkip(JCSkip tree) {
  1157     public void visitBlock(JCBlock tree) {
  1158         int limit = code.nextreg;
  1159         Env<GenContext> localEnv = env.dup(tree, new GenContext());
  1160         genStats(tree.stats, localEnv);
  1161         // End the scope of all block-local variables in variable info.
  1162         if (!env.tree.hasTag(METHODDEF)) {
  1163             code.statBegin(tree.endpos);
  1164             code.endScopes(limit);
  1165             code.pendingStatPos = Position.NOPOS;
  1169     public void visitDoLoop(JCDoWhileLoop tree) {
  1170         genLoop(tree, tree.body, tree.cond, List.<JCExpressionStatement>nil(), false);
  1173     public void visitWhileLoop(JCWhileLoop tree) {
  1174         genLoop(tree, tree.body, tree.cond, List.<JCExpressionStatement>nil(), true);
  1177     public void visitForLoop(JCForLoop tree) {
  1178         int limit = code.nextreg;
  1179         genStats(tree.init, env);
  1180         genLoop(tree, tree.body, tree.cond, tree.step, true);
  1181         code.endScopes(limit);
  1183     //where
  1184         /** Generate code for a loop.
  1185          *  @param loop       The tree representing the loop.
  1186          *  @param body       The loop's body.
  1187          *  @param cond       The loop's controling condition.
  1188          *  @param step       "Step" statements to be inserted at end of
  1189          *                    each iteration.
  1190          *  @param testFirst  True if the loop test belongs before the body.
  1191          */
  1192         private void genLoop(JCStatement loop,
  1193                              JCStatement body,
  1194                              JCExpression cond,
  1195                              List<JCExpressionStatement> step,
  1196                              boolean testFirst) {
  1197             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
  1198             int startpc = code.entryPoint();
  1199             if (testFirst) { //while or for loop
  1200                 CondItem c;
  1201                 if (cond != null) {
  1202                     code.statBegin(cond.pos);
  1203                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
  1204                 } else {
  1205                     c = items.makeCondItem(goto_);
  1207                 Chain loopDone = c.jumpFalse();
  1208                 code.resolve(c.trueJumps);
  1209                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
  1210                 if (varDebugInfo) {
  1211                     checkLoopLocalVarRangeEnding(loop, body,
  1212                             LoopLocalVarRangeEndingPoint.BEFORE_STEPS);
  1214                 code.resolve(loopEnv.info.cont);
  1215                 genStats(step, loopEnv);
  1216                 if (varDebugInfo) {
  1217                     checkLoopLocalVarRangeEnding(loop, body,
  1218                             LoopLocalVarRangeEndingPoint.AFTER_STEPS);
  1220                 code.resolve(code.branch(goto_), startpc);
  1221                 code.resolve(loopDone);
  1222             } else {
  1223                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
  1224                 if (varDebugInfo) {
  1225                     checkLoopLocalVarRangeEnding(loop, body,
  1226                             LoopLocalVarRangeEndingPoint.BEFORE_STEPS);
  1228                 code.resolve(loopEnv.info.cont);
  1229                 genStats(step, loopEnv);
  1230                 if (varDebugInfo) {
  1231                     checkLoopLocalVarRangeEnding(loop, body,
  1232                             LoopLocalVarRangeEndingPoint.AFTER_STEPS);
  1234                 CondItem c;
  1235                 if (cond != null) {
  1236                     code.statBegin(cond.pos);
  1237                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
  1238                 } else {
  1239                     c = items.makeCondItem(goto_);
  1241                 code.resolve(c.jumpTrue(), startpc);
  1242                 code.resolve(c.falseJumps);
  1244             code.resolve(loopEnv.info.exit);
  1245             if (loopEnv.info.exit != null) {
  1246                 loopEnv.info.exit.state.defined.excludeFrom(code.nextreg);
  1250         private enum LoopLocalVarRangeEndingPoint {
  1251             BEFORE_STEPS,
  1252             AFTER_STEPS,
  1255         /**
  1256          *  Checks whether we have reached an alive range ending point for local
  1257          *  variables after a loop.
  1259          *  Local variables alive range ending point for loops varies depending
  1260          *  on the loop type. The range can be closed before or after the code
  1261          *  for the steps sentences has been generated.
  1263          *  - While loops has no steps so in that case the range is closed just
  1264          *  after the body of the loop.
  1266          *  - For-like loops may have steps so as long as the steps sentences
  1267          *  can possibly contain non-synthetic local variables, the alive range
  1268          *  for local variables must be closed after the steps in this case.
  1269         */
  1270         private void checkLoopLocalVarRangeEnding(JCTree loop, JCTree body,
  1271                 LoopLocalVarRangeEndingPoint endingPoint) {
  1272             if (varDebugInfo && lvtRanges.containsKey(code.meth, body)) {
  1273                 switch (endingPoint) {
  1274                     case BEFORE_STEPS:
  1275                         if (!loop.hasTag(FORLOOP)) {
  1276                             code.closeAliveRanges(body);
  1278                         break;
  1279                     case AFTER_STEPS:
  1280                         if (loop.hasTag(FORLOOP)) {
  1281                             code.closeAliveRanges(body);
  1283                         break;
  1288     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1289         throw new AssertionError(); // should have been removed by Lower.
  1292     public void visitLabelled(JCLabeledStatement tree) {
  1293         Env<GenContext> localEnv = env.dup(tree, new GenContext());
  1294         genStat(tree.body, localEnv, CRT_STATEMENT);
  1295         code.resolve(localEnv.info.exit);
  1298     public void visitSwitch(JCSwitch tree) {
  1299         int limit = code.nextreg;
  1300         Assert.check(!tree.selector.type.hasTag(CLASS));
  1301         int startpcCrt = genCrt ? code.curCP() : 0;
  1302         Item sel = genExpr(tree.selector, syms.intType);
  1303         List<JCCase> cases = tree.cases;
  1304         if (cases.isEmpty()) {
  1305             // We are seeing:  switch <sel> {}
  1306             sel.load().drop();
  1307             if (genCrt)
  1308                 code.crt.put(TreeInfo.skipParens(tree.selector),
  1309                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
  1310         } else {
  1311             // We are seeing a nonempty switch.
  1312             sel.load();
  1313             if (genCrt)
  1314                 code.crt.put(TreeInfo.skipParens(tree.selector),
  1315                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
  1316             Env<GenContext> switchEnv = env.dup(tree, new GenContext());
  1317             switchEnv.info.isSwitch = true;
  1319             // Compute number of labels and minimum and maximum label values.
  1320             // For each case, store its label in an array.
  1321             int lo = Integer.MAX_VALUE;  // minimum label.
  1322             int hi = Integer.MIN_VALUE;  // maximum label.
  1323             int nlabels = 0;               // number of labels.
  1325             int[] labels = new int[cases.length()];  // the label array.
  1326             int defaultIndex = -1;     // the index of the default clause.
  1328             List<JCCase> l = cases;
  1329             for (int i = 0; i < labels.length; i++) {
  1330                 if (l.head.pat != null) {
  1331                     int val = ((Number)l.head.pat.type.constValue()).intValue();
  1332                     labels[i] = val;
  1333                     if (val < lo) lo = val;
  1334                     if (hi < val) hi = val;
  1335                     nlabels++;
  1336                 } else {
  1337                     Assert.check(defaultIndex == -1);
  1338                     defaultIndex = i;
  1340                 l = l.tail;
  1343             // Determine whether to issue a tableswitch or a lookupswitch
  1344             // instruction.
  1345             long table_space_cost = 4 + ((long) hi - lo + 1); // words
  1346             long table_time_cost = 3; // comparisons
  1347             long lookup_space_cost = 3 + 2 * (long) nlabels;
  1348             long lookup_time_cost = nlabels;
  1349             int opcode =
  1350                 nlabels > 0 &&
  1351                 table_space_cost + 3 * table_time_cost <=
  1352                 lookup_space_cost + 3 * lookup_time_cost
  1354                 tableswitch : lookupswitch;
  1356             int startpc = code.curCP();    // the position of the selector operation
  1357             code.emitop0(opcode);
  1358             code.align(4);
  1359             int tableBase = code.curCP();  // the start of the jump table
  1360             int[] offsets = null;          // a table of offsets for a lookupswitch
  1361             code.emit4(-1);                // leave space for default offset
  1362             if (opcode == tableswitch) {
  1363                 code.emit4(lo);            // minimum label
  1364                 code.emit4(hi);            // maximum label
  1365                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
  1366                     code.emit4(-1);
  1368             } else {
  1369                 code.emit4(nlabels);    // number of labels
  1370                 for (int i = 0; i < nlabels; i++) {
  1371                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
  1373                 offsets = new int[labels.length];
  1375             Code.State stateSwitch = code.state.dup();
  1376             code.markDead();
  1378             // For each case do:
  1379             l = cases;
  1380             for (int i = 0; i < labels.length; i++) {
  1381                 JCCase c = l.head;
  1382                 l = l.tail;
  1384                 int pc = code.entryPoint(stateSwitch);
  1385                 // Insert offset directly into code or else into the
  1386                 // offsets table.
  1387                 if (i != defaultIndex) {
  1388                     if (opcode == tableswitch) {
  1389                         code.put4(
  1390                             tableBase + 4 * (labels[i] - lo + 3),
  1391                             pc - startpc);
  1392                     } else {
  1393                         offsets[i] = pc - startpc;
  1395                 } else {
  1396                     code.put4(tableBase, pc - startpc);
  1399                 // Generate code for the statements in this case.
  1400                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
  1401                 if (varDebugInfo && lvtRanges.containsKey(code.meth, c.stats.last())) {
  1402                     code.closeAliveRanges(c.stats.last());
  1406             // Resolve all breaks.
  1407             code.resolve(switchEnv.info.exit);
  1409             // If we have not set the default offset, we do so now.
  1410             if (code.get4(tableBase) == -1) {
  1411                 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc);
  1414             if (opcode == tableswitch) {
  1415                 // Let any unfilled slots point to the default case.
  1416                 int defaultOffset = code.get4(tableBase);
  1417                 for (long i = lo; i <= hi; i++) {
  1418                     int t = (int)(tableBase + 4 * (i - lo + 3));
  1419                     if (code.get4(t) == -1)
  1420                         code.put4(t, defaultOffset);
  1422             } else {
  1423                 // Sort non-default offsets and copy into lookup table.
  1424                 if (defaultIndex >= 0)
  1425                     for (int i = defaultIndex; i < labels.length - 1; i++) {
  1426                         labels[i] = labels[i+1];
  1427                         offsets[i] = offsets[i+1];
  1429                 if (nlabels > 0)
  1430                     qsort2(labels, offsets, 0, nlabels - 1);
  1431                 for (int i = 0; i < nlabels; i++) {
  1432                     int caseidx = tableBase + 8 * (i + 1);
  1433                     code.put4(caseidx, labels[i]);
  1434                     code.put4(caseidx + 4, offsets[i]);
  1438         code.endScopes(limit);
  1440 //where
  1441         /** Sort (int) arrays of keys and values
  1442          */
  1443        static void qsort2(int[] keys, int[] values, int lo, int hi) {
  1444             int i = lo;
  1445             int j = hi;
  1446             int pivot = keys[(i+j)/2];
  1447             do {
  1448                 while (keys[i] < pivot) i++;
  1449                 while (pivot < keys[j]) j--;
  1450                 if (i <= j) {
  1451                     int temp1 = keys[i];
  1452                     keys[i] = keys[j];
  1453                     keys[j] = temp1;
  1454                     int temp2 = values[i];
  1455                     values[i] = values[j];
  1456                     values[j] = temp2;
  1457                     i++;
  1458                     j--;
  1460             } while (i <= j);
  1461             if (lo < j) qsort2(keys, values, lo, j);
  1462             if (i < hi) qsort2(keys, values, i, hi);
  1465     public void visitSynchronized(JCSynchronized tree) {
  1466         int limit = code.nextreg;
  1467         // Generate code to evaluate lock and save in temporary variable.
  1468         final LocalItem lockVar = makeTemp(syms.objectType);
  1469         genExpr(tree.lock, tree.lock.type).load().duplicate();
  1470         lockVar.store();
  1472         // Generate code to enter monitor.
  1473         code.emitop0(monitorenter);
  1474         code.state.lock(lockVar.reg);
  1476         // Generate code for a try statement with given body, no catch clauses
  1477         // in a new environment with the "exit-monitor" operation as finalizer.
  1478         final Env<GenContext> syncEnv = env.dup(tree, new GenContext());
  1479         syncEnv.info.finalize = new GenFinalizer() {
  1480             void gen() {
  1481                 genLast();
  1482                 Assert.check(syncEnv.info.gaps.length() % 2 == 0);
  1483                 syncEnv.info.gaps.append(code.curCP());
  1485             void genLast() {
  1486                 if (code.isAlive()) {
  1487                     lockVar.load();
  1488                     code.emitop0(monitorexit);
  1489                     code.state.unlock(lockVar.reg);
  1492         };
  1493         syncEnv.info.gaps = new ListBuffer<Integer>();
  1494         genTry(tree.body, List.<JCCatch>nil(), syncEnv);
  1495         code.endScopes(limit);
  1498     public void visitTry(final JCTry tree) {
  1499         // Generate code for a try statement with given body and catch clauses,
  1500         // in a new environment which calls the finally block if there is one.
  1501         final Env<GenContext> tryEnv = env.dup(tree, new GenContext());
  1502         final Env<GenContext> oldEnv = env;
  1503         if (!useJsrLocally) {
  1504             useJsrLocally =
  1505                 (stackMap == StackMapFormat.NONE) &&
  1506                 (jsrlimit <= 0 ||
  1507                 jsrlimit < 100 &&
  1508                 estimateCodeComplexity(tree.finalizer)>jsrlimit);
  1510         tryEnv.info.finalize = new GenFinalizer() {
  1511             void gen() {
  1512                 if (useJsrLocally) {
  1513                     if (tree.finalizer != null) {
  1514                         Code.State jsrState = code.state.dup();
  1515                         jsrState.push(Code.jsrReturnValue);
  1516                         tryEnv.info.cont =
  1517                             new Chain(code.emitJump(jsr),
  1518                                       tryEnv.info.cont,
  1519                                       jsrState);
  1521                     Assert.check(tryEnv.info.gaps.length() % 2 == 0);
  1522                     tryEnv.info.gaps.append(code.curCP());
  1523                 } else {
  1524                     Assert.check(tryEnv.info.gaps.length() % 2 == 0);
  1525                     tryEnv.info.gaps.append(code.curCP());
  1526                     genLast();
  1529             void genLast() {
  1530                 if (tree.finalizer != null)
  1531                     genStat(tree.finalizer, oldEnv, CRT_BLOCK);
  1533             boolean hasFinalizer() {
  1534                 return tree.finalizer != null;
  1536         };
  1537         tryEnv.info.gaps = new ListBuffer<Integer>();
  1538         genTry(tree.body, tree.catchers, tryEnv);
  1540     //where
  1541         /** Generate code for a try or synchronized statement
  1542          *  @param body      The body of the try or synchronized statement.
  1543          *  @param catchers  The lis of catch clauses.
  1544          *  @param env       the environment current for the body.
  1545          */
  1546         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
  1547             int limit = code.nextreg;
  1548             int startpc = code.curCP();
  1549             Code.State stateTry = code.state.dup();
  1550             genStat(body, env, CRT_BLOCK);
  1551             int endpc = code.curCP();
  1552             boolean hasFinalizer =
  1553                 env.info.finalize != null &&
  1554                 env.info.finalize.hasFinalizer();
  1555             List<Integer> gaps = env.info.gaps.toList();
  1556             code.statBegin(TreeInfo.endPos(body));
  1557             genFinalizer(env);
  1558             code.statBegin(TreeInfo.endPos(env.tree));
  1559             Chain exitChain = code.branch(goto_);
  1560             if (varDebugInfo && lvtRanges.containsKey(code.meth, body)) {
  1561                 code.closeAliveRanges(body);
  1563             endFinalizerGap(env);
  1564             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
  1565                 // start off with exception on stack
  1566                 code.entryPoint(stateTry, l.head.param.sym.type);
  1567                 genCatch(l.head, env, startpc, endpc, gaps);
  1568                 genFinalizer(env);
  1569                 if (hasFinalizer || l.tail.nonEmpty()) {
  1570                     code.statBegin(TreeInfo.endPos(env.tree));
  1571                     exitChain = Code.mergeChains(exitChain,
  1572                                                  code.branch(goto_));
  1574                 endFinalizerGap(env);
  1576             if (hasFinalizer) {
  1577                 // Create a new register segement to avoid allocating
  1578                 // the same variables in finalizers and other statements.
  1579                 code.newRegSegment();
  1581                 // Add a catch-all clause.
  1583                 // start off with exception on stack
  1584                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
  1586                 // Register all exception ranges for catch all clause.
  1587                 // The range of the catch all clause is from the beginning
  1588                 // of the try or synchronized block until the present
  1589                 // code pointer excluding all gaps in the current
  1590                 // environment's GenContext.
  1591                 int startseg = startpc;
  1592                 while (env.info.gaps.nonEmpty()) {
  1593                     int endseg = env.info.gaps.next().intValue();
  1594                     registerCatch(body.pos(), startseg, endseg,
  1595                                   catchallpc, 0);
  1596                     startseg = env.info.gaps.next().intValue();
  1598                 code.statBegin(TreeInfo.finalizerPos(env.tree));
  1599                 code.markStatBegin();
  1601                 Item excVar = makeTemp(syms.throwableType);
  1602                 excVar.store();
  1603                 genFinalizer(env);
  1604                 excVar.load();
  1605                 registerCatch(body.pos(), startseg,
  1606                               env.info.gaps.next().intValue(),
  1607                               catchallpc, 0);
  1608                 code.emitop0(athrow);
  1609                 code.markDead();
  1611                 // If there are jsr's to this finalizer, ...
  1612                 if (env.info.cont != null) {
  1613                     // Resolve all jsr's.
  1614                     code.resolve(env.info.cont);
  1616                     // Mark statement line number
  1617                     code.statBegin(TreeInfo.finalizerPos(env.tree));
  1618                     code.markStatBegin();
  1620                     // Save return address.
  1621                     LocalItem retVar = makeTemp(syms.throwableType);
  1622                     retVar.store();
  1624                     // Generate finalizer code.
  1625                     env.info.finalize.genLast();
  1627                     // Return.
  1628                     code.emitop1w(ret, retVar.reg);
  1629                     code.markDead();
  1632             // Resolve all breaks.
  1633             code.resolve(exitChain);
  1635             code.endScopes(limit);
  1638         /** Generate code for a catch clause.
  1639          *  @param tree     The catch clause.
  1640          *  @param env      The environment current in the enclosing try.
  1641          *  @param startpc  Start pc of try-block.
  1642          *  @param endpc    End pc of try-block.
  1643          */
  1644         void genCatch(JCCatch tree,
  1645                       Env<GenContext> env,
  1646                       int startpc, int endpc,
  1647                       List<Integer> gaps) {
  1648             if (startpc != endpc) {
  1649                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ?
  1650                         ((JCTypeUnion)tree.param.vartype).alternatives :
  1651                         List.of(tree.param.vartype);
  1652                 while (gaps.nonEmpty()) {
  1653                     for (JCExpression subCatch : subClauses) {
  1654                         int catchType = makeRef(tree.pos(), subCatch.type);
  1655                         int end = gaps.head.intValue();
  1656                         registerCatch(tree.pos(),
  1657                                       startpc,  end, code.curCP(),
  1658                                       catchType);
  1659                         if (subCatch.type.isAnnotated()) {
  1660                             for (Attribute.TypeCompound tc :
  1661                                      subCatch.type.getAnnotationMirrors()) {
  1662                                 tc.position.type_index = catchType;
  1666                     gaps = gaps.tail;
  1667                     startpc = gaps.head.intValue();
  1668                     gaps = gaps.tail;
  1670                 if (startpc < endpc) {
  1671                     for (JCExpression subCatch : subClauses) {
  1672                         int catchType = makeRef(tree.pos(), subCatch.type);
  1673                         registerCatch(tree.pos(),
  1674                                       startpc, endpc, code.curCP(),
  1675                                       catchType);
  1676                         if (subCatch.type.isAnnotated()) {
  1677                             for (Attribute.TypeCompound tc :
  1678                                      subCatch.type.getAnnotationMirrors()) {
  1679                                 tc.position.type_index = catchType;
  1684                 VarSymbol exparam = tree.param.sym;
  1685                 code.statBegin(tree.pos);
  1686                 code.markStatBegin();
  1687                 int limit = code.nextreg;
  1688                 int exlocal = code.newLocal(exparam);
  1689                 items.makeLocalItem(exparam).store();
  1690                 code.statBegin(TreeInfo.firstStatPos(tree.body));
  1691                 genStat(tree.body, env, CRT_BLOCK);
  1692                 code.endScopes(limit);
  1693                 code.statBegin(TreeInfo.endPos(tree.body));
  1697         /** Register a catch clause in the "Exceptions" code-attribute.
  1698          */
  1699         void registerCatch(DiagnosticPosition pos,
  1700                            int startpc, int endpc,
  1701                            int handler_pc, int catch_type) {
  1702             char startpc1 = (char)startpc;
  1703             char endpc1 = (char)endpc;
  1704             char handler_pc1 = (char)handler_pc;
  1705             if (startpc1 == startpc &&
  1706                 endpc1 == endpc &&
  1707                 handler_pc1 == handler_pc) {
  1708                 code.addCatch(startpc1, endpc1, handler_pc1,
  1709                               (char)catch_type);
  1710             } else {
  1711                 if (!useJsrLocally && !target.generateStackMapTable()) {
  1712                     useJsrLocally = true;
  1713                     throw new CodeSizeOverflow();
  1714                 } else {
  1715                     log.error(pos, "limit.code.too.large.for.try.stmt");
  1716                     nerrs++;
  1721     /** Very roughly estimate the number of instructions needed for
  1722      *  the given tree.
  1723      */
  1724     int estimateCodeComplexity(JCTree tree) {
  1725         if (tree == null) return 0;
  1726         class ComplexityScanner extends TreeScanner {
  1727             int complexity = 0;
  1728             public void scan(JCTree tree) {
  1729                 if (complexity > jsrlimit) return;
  1730                 super.scan(tree);
  1732             public void visitClassDef(JCClassDecl tree) {}
  1733             public void visitDoLoop(JCDoWhileLoop tree)
  1734                 { super.visitDoLoop(tree); complexity++; }
  1735             public void visitWhileLoop(JCWhileLoop tree)
  1736                 { super.visitWhileLoop(tree); complexity++; }
  1737             public void visitForLoop(JCForLoop tree)
  1738                 { super.visitForLoop(tree); complexity++; }
  1739             public void visitSwitch(JCSwitch tree)
  1740                 { super.visitSwitch(tree); complexity+=5; }
  1741             public void visitCase(JCCase tree)
  1742                 { super.visitCase(tree); complexity++; }
  1743             public void visitSynchronized(JCSynchronized tree)
  1744                 { super.visitSynchronized(tree); complexity+=6; }
  1745             public void visitTry(JCTry tree)
  1746                 { super.visitTry(tree);
  1747                   if (tree.finalizer != null) complexity+=6; }
  1748             public void visitCatch(JCCatch tree)
  1749                 { super.visitCatch(tree); complexity+=2; }
  1750             public void visitConditional(JCConditional tree)
  1751                 { super.visitConditional(tree); complexity+=2; }
  1752             public void visitIf(JCIf tree)
  1753                 { super.visitIf(tree); complexity+=2; }
  1754             // note: for break, continue, and return we don't take unwind() into account.
  1755             public void visitBreak(JCBreak tree)
  1756                 { super.visitBreak(tree); complexity+=1; }
  1757             public void visitContinue(JCContinue tree)
  1758                 { super.visitContinue(tree); complexity+=1; }
  1759             public void visitReturn(JCReturn tree)
  1760                 { super.visitReturn(tree); complexity+=1; }
  1761             public void visitThrow(JCThrow tree)
  1762                 { super.visitThrow(tree); complexity+=1; }
  1763             public void visitAssert(JCAssert tree)
  1764                 { super.visitAssert(tree); complexity+=5; }
  1765             public void visitApply(JCMethodInvocation tree)
  1766                 { super.visitApply(tree); complexity+=2; }
  1767             public void visitNewClass(JCNewClass tree)
  1768                 { scan(tree.encl); scan(tree.args); complexity+=2; }
  1769             public void visitNewArray(JCNewArray tree)
  1770                 { super.visitNewArray(tree); complexity+=5; }
  1771             public void visitAssign(JCAssign tree)
  1772                 { super.visitAssign(tree); complexity+=1; }
  1773             public void visitAssignop(JCAssignOp tree)
  1774                 { super.visitAssignop(tree); complexity+=2; }
  1775             public void visitUnary(JCUnary tree)
  1776                 { complexity+=1;
  1777                   if (tree.type.constValue() == null) super.visitUnary(tree); }
  1778             public void visitBinary(JCBinary tree)
  1779                 { complexity+=1;
  1780                   if (tree.type.constValue() == null) super.visitBinary(tree); }
  1781             public void visitTypeTest(JCInstanceOf tree)
  1782                 { super.visitTypeTest(tree); complexity+=1; }
  1783             public void visitIndexed(JCArrayAccess tree)
  1784                 { super.visitIndexed(tree); complexity+=1; }
  1785             public void visitSelect(JCFieldAccess tree)
  1786                 { super.visitSelect(tree);
  1787                   if (tree.sym.kind == VAR) complexity+=1; }
  1788             public void visitIdent(JCIdent tree) {
  1789                 if (tree.sym.kind == VAR) {
  1790                     complexity+=1;
  1791                     if (tree.type.constValue() == null &&
  1792                         tree.sym.owner.kind == TYP)
  1793                         complexity+=1;
  1796             public void visitLiteral(JCLiteral tree)
  1797                 { complexity+=1; }
  1798             public void visitTree(JCTree tree) {}
  1799             public void visitWildcard(JCWildcard tree) {
  1800                 throw new AssertionError(this.getClass().getName());
  1803         ComplexityScanner scanner = new ComplexityScanner();
  1804         tree.accept(scanner);
  1805         return scanner.complexity;
  1808     public void visitIf(JCIf tree) {
  1809         int limit = code.nextreg;
  1810         Chain thenExit = null;
  1811         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
  1812                              CRT_FLOW_CONTROLLER);
  1813         Chain elseChain = c.jumpFalse();
  1814         if (!c.isFalse()) {
  1815             code.resolve(c.trueJumps);
  1816             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
  1817             thenExit = code.branch(goto_);
  1818             if (varDebugInfo && lvtRanges.containsKey(code.meth, tree.thenpart)) {
  1819                 code.closeAliveRanges(tree.thenpart, code.cp);
  1822         if (elseChain != null) {
  1823             code.resolve(elseChain);
  1824             if (tree.elsepart != null) {
  1825                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
  1826                 if (varDebugInfo && lvtRanges.containsKey(code.meth, tree.elsepart)) {
  1827                     code.closeAliveRanges(tree.elsepart);
  1831         code.resolve(thenExit);
  1832         code.endScopes(limit);
  1835     public void visitExec(JCExpressionStatement tree) {
  1836         // Optimize x++ to ++x and x-- to --x.
  1837         JCExpression e = tree.expr;
  1838         switch (e.getTag()) {
  1839             case POSTINC:
  1840                 ((JCUnary) e).setTag(PREINC);
  1841                 break;
  1842             case POSTDEC:
  1843                 ((JCUnary) e).setTag(PREDEC);
  1844                 break;
  1846         genExpr(tree.expr, tree.expr.type).drop();
  1849     public void visitBreak(JCBreak tree) {
  1850         Env<GenContext> targetEnv = unwind(tree.target, env);
  1851         Assert.check(code.state.stacksize == 0);
  1852         targetEnv.info.addExit(code.branch(goto_));
  1853         endFinalizerGaps(env, targetEnv);
  1856     public void visitContinue(JCContinue tree) {
  1857         Env<GenContext> targetEnv = unwind(tree.target, env);
  1858         Assert.check(code.state.stacksize == 0);
  1859         targetEnv.info.addCont(code.branch(goto_));
  1860         endFinalizerGaps(env, targetEnv);
  1863     public void visitReturn(JCReturn tree) {
  1864         int limit = code.nextreg;
  1865         final Env<GenContext> targetEnv;
  1866         if (tree.expr != null) {
  1867             Item r = genExpr(tree.expr, pt).load();
  1868             if (hasFinally(env.enclMethod, env)) {
  1869                 r = makeTemp(pt);
  1870                 r.store();
  1872             targetEnv = unwind(env.enclMethod, env);
  1873             r.load();
  1874             code.emitop0(ireturn + Code.truncate(Code.typecode(pt)));
  1875         } else {
  1876             /*  If we have a statement like:
  1878              *  return;
  1880              *  we need to store the code.pendingStatPos value before generating
  1881              *  the finalizer.
  1882              */
  1883             int tmpPos = code.pendingStatPos;
  1884             targetEnv = unwind(env.enclMethod, env);
  1885             code.pendingStatPos = tmpPos;
  1886             code.emitop0(return_);
  1888         endFinalizerGaps(env, targetEnv);
  1889         code.endScopes(limit);
  1892     public void visitThrow(JCThrow tree) {
  1893         genExpr(tree.expr, tree.expr.type).load();
  1894         code.emitop0(athrow);
  1897 /* ************************************************************************
  1898  * Visitor methods for expressions
  1899  *************************************************************************/
  1901     public void visitApply(JCMethodInvocation tree) {
  1902         setTypeAnnotationPositions(tree.pos);
  1903         // Generate code for method.
  1904         Item m = genExpr(tree.meth, methodType);
  1905         // Generate code for all arguments, where the expected types are
  1906         // the parameters of the method's external type (that is, any implicit
  1907         // outer instance of a super(...) call appears as first parameter).
  1908         MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
  1909         genArgs(tree.args,
  1910                 msym.externalType(types).getParameterTypes());
  1911         if (!msym.isDynamic()) {
  1912             code.statBegin(tree.pos);
  1914         result = m.invoke();
  1917     public void visitConditional(JCConditional tree) {
  1918         Chain thenExit = null;
  1919         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
  1920         Chain elseChain = c.jumpFalse();
  1921         if (!c.isFalse()) {
  1922             code.resolve(c.trueJumps);
  1923             int startpc = genCrt ? code.curCP() : 0;
  1924             genExpr(tree.truepart, pt).load();
  1925             code.state.forceStackTop(tree.type);
  1926             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
  1927                                      startpc, code.curCP());
  1928             thenExit = code.branch(goto_);
  1930         if (elseChain != null) {
  1931             code.resolve(elseChain);
  1932             int startpc = genCrt ? code.curCP() : 0;
  1933             genExpr(tree.falsepart, pt).load();
  1934             code.state.forceStackTop(tree.type);
  1935             if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET,
  1936                                      startpc, code.curCP());
  1938         code.resolve(thenExit);
  1939         result = items.makeStackItem(pt);
  1942     private void setTypeAnnotationPositions(int treePos) {
  1943         MethodSymbol meth = code.meth;
  1944         boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR
  1945                 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT;
  1947         for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) {
  1948             if (ta.hasUnknownPosition())
  1949                 ta.tryFixPosition();
  1951             if (ta.position.matchesPos(treePos))
  1952                 ta.position.updatePosOffset(code.cp);
  1955         if (!initOrClinit)
  1956             return;
  1958         for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) {
  1959             if (ta.hasUnknownPosition())
  1960                 ta.tryFixPosition();
  1962             if (ta.position.matchesPos(treePos))
  1963                 ta.position.updatePosOffset(code.cp);
  1966         ClassSymbol clazz = meth.enclClass();
  1967         for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
  1968             if (!s.getKind().isField())
  1969                 continue;
  1971             for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
  1972                 if (ta.hasUnknownPosition())
  1973                     ta.tryFixPosition();
  1975                 if (ta.position.matchesPos(treePos))
  1976                     ta.position.updatePosOffset(code.cp);
  1981     public void visitNewClass(JCNewClass tree) {
  1982         // Enclosing instances or anonymous classes should have been eliminated
  1983         // by now.
  1984         Assert.check(tree.encl == null && tree.def == null);
  1985         setTypeAnnotationPositions(tree.pos);
  1987         code.emitop2(new_, makeRef(tree.pos(), tree.type));
  1988         code.emitop0(dup);
  1990         // Generate code for all arguments, where the expected types are
  1991         // the parameters of the constructor's external type (that is,
  1992         // any implicit outer instance appears as first parameter).
  1993         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
  1995         items.makeMemberItem(tree.constructor, true).invoke();
  1996         result = items.makeStackItem(tree.type);
  1999     public void visitNewArray(JCNewArray tree) {
  2000         setTypeAnnotationPositions(tree.pos);
  2002         if (tree.elems != null) {
  2003             Type elemtype = types.elemtype(tree.type);
  2004             loadIntConst(tree.elems.length());
  2005             Item arr = makeNewArray(tree.pos(), tree.type, 1);
  2006             int i = 0;
  2007             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {
  2008                 arr.duplicate();
  2009                 loadIntConst(i);
  2010                 i++;
  2011                 genExpr(l.head, elemtype).load();
  2012                 items.makeIndexedItem(elemtype).store();
  2014             result = arr;
  2015         } else {
  2016             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2017                 genExpr(l.head, syms.intType).load();
  2019             result = makeNewArray(tree.pos(), tree.type, tree.dims.length());
  2022 //where
  2023         /** Generate code to create an array with given element type and number
  2024          *  of dimensions.
  2025          */
  2026         Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) {
  2027             Type elemtype = types.elemtype(type);
  2028             if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) {
  2029                 log.error(pos, "limit.dimensions");
  2030                 nerrs++;
  2032             int elemcode = Code.arraycode(elemtype);
  2033             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
  2034                 code.emitAnewarray(makeRef(pos, elemtype), type);
  2035             } else if (elemcode == 1) {
  2036                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
  2037             } else {
  2038                 code.emitNewarray(elemcode, type);
  2040             return items.makeStackItem(type);
  2043     public void visitParens(JCParens tree) {
  2044         result = genExpr(tree.expr, tree.expr.type);
  2047     public void visitAssign(JCAssign tree) {
  2048         Item l = genExpr(tree.lhs, tree.lhs.type);
  2049         genExpr(tree.rhs, tree.lhs.type).load();
  2050         result = items.makeAssignItem(l);
  2053     public void visitAssignop(JCAssignOp tree) {
  2054         OperatorSymbol operator = (OperatorSymbol) tree.operator;
  2055         Item l;
  2056         if (operator.opcode == string_add) {
  2057             // Generate code to make a string buffer
  2058             makeStringBuffer(tree.pos());
  2060             // Generate code for first string, possibly save one
  2061             // copy under buffer
  2062             l = genExpr(tree.lhs, tree.lhs.type);
  2063             if (l.width() > 0) {
  2064                 code.emitop0(dup_x1 + 3 * (l.width() - 1));
  2067             // Load first string and append to buffer.
  2068             l.load();
  2069             appendString(tree.lhs);
  2071             // Append all other strings to buffer.
  2072             appendStrings(tree.rhs);
  2074             // Convert buffer to string.
  2075             bufferToString(tree.pos());
  2076         } else {
  2077             // Generate code for first expression
  2078             l = genExpr(tree.lhs, tree.lhs.type);
  2080             // If we have an increment of -32768 to +32767 of a local
  2081             // int variable we can use an incr instruction instead of
  2082             // proceeding further.
  2083             if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
  2084                 l instanceof LocalItem &&
  2085                 tree.lhs.type.getTag().isSubRangeOf(INT) &&
  2086                 tree.rhs.type.getTag().isSubRangeOf(INT) &&
  2087                 tree.rhs.type.constValue() != null) {
  2088                 int ival = ((Number) tree.rhs.type.constValue()).intValue();
  2089                 if (tree.hasTag(MINUS_ASG)) ival = -ival;
  2090                 ((LocalItem)l).incr(ival);
  2091                 result = l;
  2092                 return;
  2094             // Otherwise, duplicate expression, load one copy
  2095             // and complete binary operation.
  2096             l.duplicate();
  2097             l.coerce(operator.type.getParameterTypes().head).load();
  2098             completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type);
  2100         result = items.makeAssignItem(l);
  2103     public void visitUnary(JCUnary tree) {
  2104         OperatorSymbol operator = (OperatorSymbol)tree.operator;
  2105         if (tree.hasTag(NOT)) {
  2106             CondItem od = genCond(tree.arg, false);
  2107             result = od.negate();
  2108         } else {
  2109             Item od = genExpr(tree.arg, operator.type.getParameterTypes().head);
  2110             switch (tree.getTag()) {
  2111             case POS:
  2112                 result = od.load();
  2113                 break;
  2114             case NEG:
  2115                 result = od.load();
  2116                 code.emitop0(operator.opcode);
  2117                 break;
  2118             case COMPL:
  2119                 result = od.load();
  2120                 emitMinusOne(od.typecode);
  2121                 code.emitop0(operator.opcode);
  2122                 break;
  2123             case PREINC: case PREDEC:
  2124                 od.duplicate();
  2125                 if (od instanceof LocalItem &&
  2126                     (operator.opcode == iadd || operator.opcode == isub)) {
  2127                     ((LocalItem)od).incr(tree.hasTag(PREINC) ? 1 : -1);
  2128                     result = od;
  2129                 } else {
  2130                     od.load();
  2131                     code.emitop0(one(od.typecode));
  2132                     code.emitop0(operator.opcode);
  2133                     // Perform narrowing primitive conversion if byte,
  2134                     // char, or short.  Fix for 4304655.
  2135                     if (od.typecode != INTcode &&
  2136                         Code.truncate(od.typecode) == INTcode)
  2137                       code.emitop0(int2byte + od.typecode - BYTEcode);
  2138                     result = items.makeAssignItem(od);
  2140                 break;
  2141             case POSTINC: case POSTDEC:
  2142                 od.duplicate();
  2143                 if (od instanceof LocalItem &&
  2144                     (operator.opcode == iadd || operator.opcode == isub)) {
  2145                     Item res = od.load();
  2146                     ((LocalItem)od).incr(tree.hasTag(POSTINC) ? 1 : -1);
  2147                     result = res;
  2148                 } else {
  2149                     Item res = od.load();
  2150                     od.stash(od.typecode);
  2151                     code.emitop0(one(od.typecode));
  2152                     code.emitop0(operator.opcode);
  2153                     // Perform narrowing primitive conversion if byte,
  2154                     // char, or short.  Fix for 4304655.
  2155                     if (od.typecode != INTcode &&
  2156                         Code.truncate(od.typecode) == INTcode)
  2157                       code.emitop0(int2byte + od.typecode - BYTEcode);
  2158                     od.store();
  2159                     result = res;
  2161                 break;
  2162             case NULLCHK:
  2163                 result = od.load();
  2164                 code.emitop0(dup);
  2165                 genNullCheck(tree.pos());
  2166                 break;
  2167             default:
  2168                 Assert.error();
  2173     /** Generate a null check from the object value at stack top. */
  2174     private void genNullCheck(DiagnosticPosition pos) {
  2175         callMethod(pos, syms.objectType, names.getClass,
  2176                    List.<Type>nil(), false);
  2177         code.emitop0(pop);
  2180     public void visitBinary(JCBinary tree) {
  2181         OperatorSymbol operator = (OperatorSymbol)tree.operator;
  2182         if (operator.opcode == string_add) {
  2183             // Create a string buffer.
  2184             makeStringBuffer(tree.pos());
  2185             // Append all strings to buffer.
  2186             appendStrings(tree);
  2187             // Convert buffer to string.
  2188             bufferToString(tree.pos());
  2189             result = items.makeStackItem(syms.stringType);
  2190         } else if (tree.hasTag(AND)) {
  2191             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
  2192             if (!lcond.isFalse()) {
  2193                 Chain falseJumps = lcond.jumpFalse();
  2194                 code.resolve(lcond.trueJumps);
  2195                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
  2196                 result = items.
  2197                     makeCondItem(rcond.opcode,
  2198                                  rcond.trueJumps,
  2199                                  Code.mergeChains(falseJumps,
  2200                                                   rcond.falseJumps));
  2201             } else {
  2202                 result = lcond;
  2204         } else if (tree.hasTag(OR)) {
  2205             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
  2206             if (!lcond.isTrue()) {
  2207                 Chain trueJumps = lcond.jumpTrue();
  2208                 code.resolve(lcond.falseJumps);
  2209                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
  2210                 result = items.
  2211                     makeCondItem(rcond.opcode,
  2212                                  Code.mergeChains(trueJumps, rcond.trueJumps),
  2213                                  rcond.falseJumps);
  2214             } else {
  2215                 result = lcond;
  2217         } else {
  2218             Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head);
  2219             od.load();
  2220             result = completeBinop(tree.lhs, tree.rhs, operator);
  2223 //where
  2224         /** Make a new string buffer.
  2225          */
  2226         void makeStringBuffer(DiagnosticPosition pos) {
  2227             code.emitop2(new_, makeRef(pos, stringBufferType));
  2228             code.emitop0(dup);
  2229             callMethod(
  2230                 pos, stringBufferType, names.init, List.<Type>nil(), false);
  2233         /** Append value (on tos) to string buffer (on tos - 1).
  2234          */
  2235         void appendString(JCTree tree) {
  2236             Type t = tree.type.baseType();
  2237             if (!t.isPrimitive() && t.tsym != syms.stringType.tsym) {
  2238                 t = syms.objectType;
  2240             items.makeMemberItem(getStringBufferAppend(tree, t), false).invoke();
  2242         Symbol getStringBufferAppend(JCTree tree, Type t) {
  2243             Assert.checkNull(t.constValue());
  2244             Symbol method = stringBufferAppend.get(t);
  2245             if (method == null) {
  2246                 method = rs.resolveInternalMethod(tree.pos(),
  2247                                                   attrEnv,
  2248                                                   stringBufferType,
  2249                                                   names.append,
  2250                                                   List.of(t),
  2251                                                   null);
  2252                 stringBufferAppend.put(t, method);
  2254             return method;
  2257         /** Add all strings in tree to string buffer.
  2258          */
  2259         void appendStrings(JCTree tree) {
  2260             tree = TreeInfo.skipParens(tree);
  2261             if (tree.hasTag(PLUS) && tree.type.constValue() == null) {
  2262                 JCBinary op = (JCBinary) tree;
  2263                 if (op.operator.kind == MTH &&
  2264                     ((OperatorSymbol) op.operator).opcode == string_add) {
  2265                     appendStrings(op.lhs);
  2266                     appendStrings(op.rhs);
  2267                     return;
  2270             genExpr(tree, tree.type).load();
  2271             appendString(tree);
  2274         /** Convert string buffer on tos to string.
  2275          */
  2276         void bufferToString(DiagnosticPosition pos) {
  2277             callMethod(
  2278                 pos,
  2279                 stringBufferType,
  2280                 names.toString,
  2281                 List.<Type>nil(),
  2282                 false);
  2285         /** Complete generating code for operation, with left operand
  2286          *  already on stack.
  2287          *  @param lhs       The tree representing the left operand.
  2288          *  @param rhs       The tree representing the right operand.
  2289          *  @param operator  The operator symbol.
  2290          */
  2291         Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) {
  2292             MethodType optype = (MethodType)operator.type;
  2293             int opcode = operator.opcode;
  2294             if (opcode >= if_icmpeq && opcode <= if_icmple &&
  2295                 rhs.type.constValue() instanceof Number &&
  2296                 ((Number) rhs.type.constValue()).intValue() == 0) {
  2297                 opcode = opcode + (ifeq - if_icmpeq);
  2298             } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
  2299                        TreeInfo.isNull(rhs)) {
  2300                 opcode = opcode + (if_acmp_null - if_acmpeq);
  2301             } else {
  2302                 // The expected type of the right operand is
  2303                 // the second parameter type of the operator, except for
  2304                 // shifts with long shiftcount, where we convert the opcode
  2305                 // to a short shift and the expected type to int.
  2306                 Type rtype = operator.erasure(types).getParameterTypes().tail.head;
  2307                 if (opcode >= ishll && opcode <= lushrl) {
  2308                     opcode = opcode + (ishl - ishll);
  2309                     rtype = syms.intType;
  2311                 // Generate code for right operand and load.
  2312                 genExpr(rhs, rtype).load();
  2313                 // If there are two consecutive opcode instructions,
  2314                 // emit the first now.
  2315                 if (opcode >= (1 << preShift)) {
  2316                     code.emitop0(opcode >> preShift);
  2317                     opcode = opcode & 0xFF;
  2320             if (opcode >= ifeq && opcode <= if_acmpne ||
  2321                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
  2322                 return items.makeCondItem(opcode);
  2323             } else {
  2324                 code.emitop0(opcode);
  2325                 return items.makeStackItem(optype.restype);
  2329     public void visitTypeCast(JCTypeCast tree) {
  2330         setTypeAnnotationPositions(tree.pos);
  2331         result = genExpr(tree.expr, tree.clazz.type).load();
  2332         // Additional code is only needed if we cast to a reference type
  2333         // which is not statically a supertype of the expression's type.
  2334         // For basic types, the coerce(...) in genExpr(...) will do
  2335         // the conversion.
  2336         if (!tree.clazz.type.isPrimitive() &&
  2337             types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
  2338             code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type));
  2342     public void visitWildcard(JCWildcard tree) {
  2343         throw new AssertionError(this.getClass().getName());
  2346     public void visitTypeTest(JCInstanceOf tree) {
  2347         setTypeAnnotationPositions(tree.pos);
  2348         genExpr(tree.expr, tree.expr.type).load();
  2349         code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type));
  2350         result = items.makeStackItem(syms.booleanType);
  2353     public void visitIndexed(JCArrayAccess tree) {
  2354         genExpr(tree.indexed, tree.indexed.type).load();
  2355         genExpr(tree.index, syms.intType).load();
  2356         result = items.makeIndexedItem(tree.type);
  2359     public void visitIdent(JCIdent tree) {
  2360         Symbol sym = tree.sym;
  2361         if (tree.name == names._this || tree.name == names._super) {
  2362             Item res = tree.name == names._this
  2363                 ? items.makeThisItem()
  2364                 : items.makeSuperItem();
  2365             if (sym.kind == MTH) {
  2366                 // Generate code to address the constructor.
  2367                 res.load();
  2368                 res = items.makeMemberItem(sym, true);
  2370             result = res;
  2371         } else if (sym.kind == VAR && sym.owner.kind == MTH) {
  2372             result = items.makeLocalItem((VarSymbol)sym);
  2373         } else if (isInvokeDynamic(sym)) {
  2374             result = items.makeDynamicItem(sym);
  2375         } else if ((sym.flags() & STATIC) != 0) {
  2376             if (!isAccessSuper(env.enclMethod))
  2377                 sym = binaryQualifier(sym, env.enclClass.type);
  2378             result = items.makeStaticItem(sym);
  2379         } else {
  2380             items.makeThisItem().load();
  2381             sym = binaryQualifier(sym, env.enclClass.type);
  2382             result = items.makeMemberItem(sym, (sym.flags() & PRIVATE) != 0);
  2386     public void visitSelect(JCFieldAccess tree) {
  2387         Symbol sym = tree.sym;
  2389         if (tree.name == names._class) {
  2390             Assert.check(target.hasClassLiterals());
  2391             code.emitLdc(makeRef(tree.pos(), tree.selected.type));
  2392             result = items.makeStackItem(pt);
  2393             return;
  2396         Symbol ssym = TreeInfo.symbol(tree.selected);
  2398         // Are we selecting via super?
  2399         boolean selectSuper =
  2400             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
  2402         // Are we accessing a member of the superclass in an access method
  2403         // resulting from a qualified super?
  2404         boolean accessSuper = isAccessSuper(env.enclMethod);
  2406         Item base = (selectSuper)
  2407             ? items.makeSuperItem()
  2408             : genExpr(tree.selected, tree.selected.type);
  2410         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
  2411             // We are seeing a variable that is constant but its selecting
  2412             // expression is not.
  2413             if ((sym.flags() & STATIC) != 0) {
  2414                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
  2415                     base = base.load();
  2416                 base.drop();
  2417             } else {
  2418                 base.load();
  2419                 genNullCheck(tree.selected.pos());
  2421             result = items.
  2422                 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue());
  2423         } else {
  2424             if (isInvokeDynamic(sym)) {
  2425                 result = items.makeDynamicItem(sym);
  2426                 return;
  2427             } else {
  2428                 sym = binaryQualifier(sym, tree.selected.type);
  2430             if ((sym.flags() & STATIC) != 0) {
  2431                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
  2432                     base = base.load();
  2433                 base.drop();
  2434                 result = items.makeStaticItem(sym);
  2435             } else {
  2436                 base.load();
  2437                 if (sym == syms.lengthVar) {
  2438                     code.emitop0(arraylength);
  2439                     result = items.makeStackItem(syms.intType);
  2440                 } else {
  2441                     result = items.
  2442                         makeMemberItem(sym,
  2443                                        (sym.flags() & PRIVATE) != 0 ||
  2444                                        selectSuper || accessSuper);
  2450     public boolean isInvokeDynamic(Symbol sym) {
  2451         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
  2454     public void visitLiteral(JCLiteral tree) {
  2455         if (tree.type.hasTag(BOT)) {
  2456             code.emitop0(aconst_null);
  2457             if (types.dimensions(pt) > 1) {
  2458                 code.emitop2(checkcast, makeRef(tree.pos(), pt));
  2459                 result = items.makeStackItem(pt);
  2460             } else {
  2461                 result = items.makeStackItem(tree.type);
  2464         else
  2465             result = items.makeImmediateItem(tree.type, tree.value);
  2468     public void visitLetExpr(LetExpr tree) {
  2469         int limit = code.nextreg;
  2470         genStats(tree.defs, env);
  2471         result = genExpr(tree.expr, tree.expr.type).load();
  2472         code.endScopes(limit);
  2475     private void generateReferencesToPrunedTree(ClassSymbol classSymbol, Pool pool) {
  2476         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
  2477         if (prunedInfo != null) {
  2478             for (JCTree prunedTree: prunedInfo) {
  2479                 prunedTree.accept(classReferenceVisitor);
  2484 /* ************************************************************************
  2485  * main method
  2486  *************************************************************************/
  2488     /** Generate code for a class definition.
  2489      *  @param env   The attribution environment that belongs to the
  2490      *               outermost class containing this class definition.
  2491      *               We need this for resolving some additional symbols.
  2492      *  @param cdef  The tree representing the class definition.
  2493      *  @return      True if code is generated with no errors.
  2494      */
  2495     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
  2496         try {
  2497             attrEnv = env;
  2498             ClassSymbol c = cdef.sym;
  2499             this.toplevel = env.toplevel;
  2500             this.endPosTable = toplevel.endPositions;
  2501             // If this is a class definition requiring Miranda methods,
  2502             // add them.
  2503             if (generateIproxies &&
  2504                 (c.flags() & (INTERFACE|ABSTRACT)) == ABSTRACT
  2505                 && !allowGenerics // no Miranda methods available with generics
  2507                 implementInterfaceMethods(c);
  2508             cdef.defs = normalizeDefs(cdef.defs, c);
  2509             c.pool = pool;
  2510             pool.reset();
  2511             generateReferencesToPrunedTree(c, pool);
  2512             Env<GenContext> localEnv =
  2513                 new Env<GenContext>(cdef, new GenContext());
  2514             localEnv.toplevel = env.toplevel;
  2515             localEnv.enclClass = cdef;
  2517             /*  We must not analyze synthetic methods
  2518              */
  2519             if (varDebugInfo && (cdef.sym.flags() & SYNTHETIC) == 0) {
  2520                 try {
  2521                     new LVTAssignAnalyzer().analyzeTree(localEnv);
  2522                 } catch (Throwable e) {
  2523                     throw e;
  2527             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
  2528                 genDef(l.head, localEnv);
  2530             if (pool.numEntries() > Pool.MAX_ENTRIES) {
  2531                 log.error(cdef.pos(), "limit.pool");
  2532                 nerrs++;
  2534             if (nerrs != 0) {
  2535                 // if errors, discard code
  2536                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
  2537                     if (l.head.hasTag(METHODDEF))
  2538                         ((JCMethodDecl) l.head).sym.code = null;
  2541             cdef.defs = List.nil(); // discard trees
  2542             return nerrs == 0;
  2543         } finally {
  2544             // note: this method does NOT support recursion.
  2545             attrEnv = null;
  2546             this.env = null;
  2547             toplevel = null;
  2548             endPosTable = null;
  2549             nerrs = 0;
  2553 /* ************************************************************************
  2554  * Auxiliary classes
  2555  *************************************************************************/
  2557     /** An abstract class for finalizer generation.
  2558      */
  2559     abstract class GenFinalizer {
  2560         /** Generate code to clean up when unwinding. */
  2561         abstract void gen();
  2563         /** Generate code to clean up at last. */
  2564         abstract void genLast();
  2566         /** Does this finalizer have some nontrivial cleanup to perform? */
  2567         boolean hasFinalizer() { return true; }
  2570     /** code generation contexts,
  2571      *  to be used as type parameter for environments.
  2572      */
  2573     static class GenContext {
  2575         /** A chain for all unresolved jumps that exit the current environment.
  2576          */
  2577         Chain exit = null;
  2579         /** A chain for all unresolved jumps that continue in the
  2580          *  current environment.
  2581          */
  2582         Chain cont = null;
  2584         /** A closure that generates the finalizer of the current environment.
  2585          *  Only set for Synchronized and Try contexts.
  2586          */
  2587         GenFinalizer finalize = null;
  2589         /** Is this a switch statement?  If so, allocate registers
  2590          * even when the variable declaration is unreachable.
  2591          */
  2592         boolean isSwitch = false;
  2594         /** A list buffer containing all gaps in the finalizer range,
  2595          *  where a catch all exception should not apply.
  2596          */
  2597         ListBuffer<Integer> gaps = null;
  2599         /** Add given chain to exit chain.
  2600          */
  2601         void addExit(Chain c)  {
  2602             exit = Code.mergeChains(c, exit);
  2605         /** Add given chain to cont chain.
  2606          */
  2607         void addCont(Chain c) {
  2608             cont = Code.mergeChains(c, cont);
  2612     class LVTAssignAnalyzer
  2613         extends Flow.AbstractAssignAnalyzer<LVTAssignAnalyzer.LVTAssignPendingExit> {
  2615         final LVTBits lvtInits;
  2617         /*  This class is anchored to a context dependent tree. The tree can
  2618          *  vary inside the same instruction for example in the switch instruction
  2619          *  the same FlowBits instance can be anchored to the whole tree, or
  2620          *  to a given case. The aim is to always anchor the bits to the tree
  2621          *  capable of closing a DA range.
  2622          */
  2623         class LVTBits extends Bits {
  2625             JCTree currentTree;
  2626             private int[] oldBits = null;
  2627             BitsState stateBeforeOp;
  2629             @Override
  2630             public void clear() {
  2631                 generalOp(null, -1, BitsOpKind.CLEAR);
  2634             @Override
  2635             protected void internalReset() {
  2636                 super.internalReset();
  2637                 oldBits = null;
  2640             @Override
  2641             public Bits assign(Bits someBits) {
  2642                 // bits can be null
  2643                 oldBits = bits;
  2644                 stateBeforeOp = currentState;
  2645                 super.assign(someBits);
  2646                 changed();
  2647                 return this;
  2650             @Override
  2651             public void excludeFrom(int start) {
  2652                 generalOp(null, start, BitsOpKind.EXCL_RANGE);
  2655             @Override
  2656             public void excl(int x) {
  2657                 Assert.check(x >= 0);
  2658                 generalOp(null, x, BitsOpKind.EXCL_BIT);
  2661             @Override
  2662             public Bits andSet(Bits xs) {
  2663                return generalOp(xs, -1, BitsOpKind.AND_SET);
  2666             @Override
  2667             public Bits orSet(Bits xs) {
  2668                 return generalOp(xs, -1, BitsOpKind.OR_SET);
  2671             @Override
  2672             public Bits diffSet(Bits xs) {
  2673                 return generalOp(xs, -1, BitsOpKind.DIFF_SET);
  2676             @Override
  2677             public Bits xorSet(Bits xs) {
  2678                 return generalOp(xs, -1, BitsOpKind.XOR_SET);
  2681             private Bits generalOp(Bits xs, int i, BitsOpKind opKind) {
  2682                 Assert.check(currentState != BitsState.UNKNOWN);
  2683                 oldBits = dupBits();
  2684                 stateBeforeOp = currentState;
  2685                 switch (opKind) {
  2686                     case AND_SET:
  2687                         super.andSet(xs);
  2688                         break;
  2689                     case OR_SET:
  2690                         super.orSet(xs);
  2691                         break;
  2692                     case XOR_SET:
  2693                         super.xorSet(xs);
  2694                         break;
  2695                     case DIFF_SET:
  2696                         super.diffSet(xs);
  2697                         break;
  2698                     case CLEAR:
  2699                         super.clear();
  2700                         break;
  2701                     case EXCL_BIT:
  2702                         super.excl(i);
  2703                         break;
  2704                     case EXCL_RANGE:
  2705                         super.excludeFrom(i);
  2706                         break;
  2708                 changed();
  2709                 return this;
  2712             /*  The tree we need to anchor the bits instance to.
  2713              */
  2714             LVTBits at(JCTree tree) {
  2715                 this.currentTree = tree;
  2716                 return this;
  2719             /*  If the instance should be changed but the tree is not a closing
  2720              *  tree then a reset is needed or the former tree can mistakingly be
  2721              *  used.
  2722              */
  2723             LVTBits resetTree() {
  2724                 this.currentTree = null;
  2725                 return this;
  2728             /** This method will be called after any operation that causes a change to
  2729              *  the bits. Subclasses can thus override it in order to extract information
  2730              *  from the changes produced to the bits by the given operation.
  2731              */
  2732             public void changed() {
  2733                 if (currentTree != null &&
  2734                         stateBeforeOp != BitsState.UNKNOWN &&
  2735                         trackTree(currentTree)) {
  2736                     List<VarSymbol> locals = lvtRanges
  2737                             .getVars(currentMethod, currentTree);
  2738                     locals = locals != null ?
  2739                             locals : List.<VarSymbol>nil();
  2740                     for (JCVariableDecl vardecl : vardecls) {
  2741                         //once the first is null, the rest will be so.
  2742                         if (vardecl == null) {
  2743                             break;
  2745                         if (trackVar(vardecl.sym) && bitChanged(vardecl.sym.adr)) {
  2746                             locals = locals.prepend(vardecl.sym);
  2749                     if (!locals.isEmpty()) {
  2750                         lvtRanges.setEntry(currentMethod,
  2751                                 currentTree, locals);
  2756             boolean bitChanged(int x) {
  2757                 boolean isMemberOfBits = isMember(x);
  2758                 int[] tmp = bits;
  2759                 bits = oldBits;
  2760                 boolean isMemberOfOldBits = isMember(x);
  2761                 bits = tmp;
  2762                 return (!isMemberOfBits && isMemberOfOldBits);
  2765             boolean trackVar(VarSymbol var) {
  2766                 return (var.owner.kind == MTH &&
  2767                         (var.flags() & PARAMETER) == 0 &&
  2768                         trackable(var));
  2771             boolean trackTree(JCTree tree) {
  2772                 switch (tree.getTag()) {
  2773                     // of course a method closes the alive range of a local variable.
  2774                     case METHODDEF:
  2775                     // for while loops we want only the body
  2776                     case WHILELOOP:
  2777                         return false;
  2779                 return true;
  2784         public class LVTAssignPendingExit extends
  2785                                     Flow.AbstractAssignAnalyzer<LVTAssignPendingExit>.AbstractAssignPendingExit {
  2787             LVTAssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
  2788                 super(tree, inits, uninits);
  2791             @Override
  2792             public void resolveJump(JCTree tree) {
  2793                 lvtInits.at(tree);
  2794                 super.resolveJump(tree);
  2798         private LVTAssignAnalyzer() {
  2799             flow.super();
  2800             lvtInits = new LVTBits();
  2801             inits = lvtInits;
  2804         @Override
  2805         protected void markDead(JCTree tree) {
  2806             lvtInits.at(tree).inclRange(returnadr, nextadr);
  2807             super.markDead(tree);
  2810         @Override
  2811         protected void merge(JCTree tree) {
  2812             lvtInits.at(tree);
  2813             super.merge(tree);
  2816         boolean isSyntheticOrMandated(Symbol sym) {
  2817             return (sym.flags() & (SYNTHETIC | MANDATED)) != 0;
  2820         @Override
  2821         protected boolean trackable(VarSymbol sym) {
  2822             if (isSyntheticOrMandated(sym)) {
  2823                 //fast check to avoid tracking synthetic or mandated variables
  2824                 return false;
  2826             return super.trackable(sym);
  2829         @Override
  2830         protected void initParam(JCVariableDecl def) {
  2831             if (!isSyntheticOrMandated(def.sym)) {
  2832                 super.initParam(def);
  2836         @Override
  2837         protected void assignToInits(JCTree tree, Bits bits) {
  2838             lvtInits.at(tree);
  2839             lvtInits.assign(bits);
  2842         @Override
  2843         protected void andSetInits(JCTree tree, Bits bits) {
  2844             lvtInits.at(tree);
  2845             lvtInits.andSet(bits);
  2848         @Override
  2849         protected void orSetInits(JCTree tree, Bits bits) {
  2850             lvtInits.at(tree);
  2851             lvtInits.orSet(bits);
  2854         @Override
  2855         protected void exclVarFromInits(JCTree tree, int adr) {
  2856             lvtInits.at(tree);
  2857             lvtInits.excl(adr);
  2860         @Override
  2861         protected LVTAssignPendingExit createNewPendingExit(JCTree tree, Bits inits, Bits uninits) {
  2862             return new LVTAssignPendingExit(tree, inits, uninits);
  2865         MethodSymbol currentMethod;
  2867         @Override
  2868         public void visitMethodDef(JCMethodDecl tree) {
  2869             if ((tree.sym.flags() & (SYNTHETIC | GENERATEDCONSTR)) != 0
  2870                     && (tree.sym.flags() & LAMBDA_METHOD) == 0) {
  2871                 return;
  2873             if (tree.name.equals(names.clinit)) {
  2874                 return;
  2876             boolean enumClass = (tree.sym.owner.flags() & ENUM) != 0;
  2877             if (enumClass &&
  2878                     (tree.name.equals(names.valueOf) ||
  2879                     tree.name.equals(names.values) ||
  2880                     tree.name.equals(names.init))) {
  2881                 return;
  2883             currentMethod = tree.sym;
  2885             super.visitMethodDef(tree);

mercurial