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