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

Fri, 09 Jan 2015 09:27:16 -0800

author
darcy
date
Fri, 09 Jan 2015 09:27:16 -0800
changeset 2707
63a9b573847d
parent 2566
58e7e71b302e
child 2657
d42678403377
child 2709
dca7f60e618d
permissions
-rw-r--r--

8068639: Make certain annotation classfile warnings opt-in
Reviewed-by: jjg

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

mercurial