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