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