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

Tue, 14 May 2013 15:04:06 -0700

author
jjg
date
Tue, 14 May 2013 15:04:06 -0700
changeset 1755
ddb4a2bfcd82
parent 1676
e9d986381414
child 1802
8fb68f73d4b1
permissions
-rw-r--r--

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

mercurial