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

Thu, 12 Oct 2017 19:50:01 +0800

author
aoqi
date
Thu, 12 Oct 2017 19:50:01 +0800
changeset 2702
9ca8d8713094
parent 2657
d42678403377
parent 2525
2eb010b6cb22
child 2893
ca5783d9a597
permissions
-rw-r--r--

merge

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

mercurial