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