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