src/share/classes/com/sun/tools/javac/jvm/Gen.java

Wed, 23 Jan 2013 13:27:24 -0800

author
jjg
date
Wed, 23 Jan 2013 13:27:24 -0800
changeset 1521
71f35e4b93a5
parent 1452
de1ec6fc93fe
child 1555
762d0af062f5
permissions
-rw-r--r--

8006775: JSR 308: Compiler changes in JDK8
Reviewed-by: jjg
Contributed-by: mernst@cs.washington.edu, wmdietl@cs.washington.edu, mpapi@csail.mit.edu, mahmood@notnoop.com

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

mercurial