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