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