1 /* 2 * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import java.lang.annotation.*; 29 import java.lang.reflect.Method; 30 import java.util.List; 31 import java.util.Arrays; 32 import java.util.HashMap; 33 34 import sun.invoke.util.Wrapper; 35 import java.lang.reflect.Field; 36 37 import static java.lang.invoke.LambdaForm.BasicType.*; 38 import static java.lang.invoke.MethodHandleStatics.*; 39 import static java.lang.invoke.MethodHandleNatives.Constants.*; 40 41 /** 42 * The symbolic, non-executable form of a method handle's invocation semantics. 43 * It consists of a series of names. 44 * The first N (N=arity) names are parameters, 45 * while any remaining names are temporary values. 46 * Each temporary specifies the application of a function to some arguments. 47 * The functions are method handles, while the arguments are mixes of 48 * constant values and local names. 49 * The result of the lambda is defined as one of the names, often the last one. 50 * <p> 51 * Here is an approximate grammar: 52 * <blockquote><pre>{@code 53 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}" 54 * ArgName = "a" N ":" T 55 * TempName = "t" N ":" T "=" Function "(" Argument* ");" 56 * Function = ConstantValue 57 * Argument = NameRef | ConstantValue 58 * Result = NameRef | "void" 59 * NameRef = "a" N | "t" N 60 * N = (any whole number) 61 * T = "L" | "I" | "J" | "F" | "D" | "V" 62 * }</pre></blockquote> 63 * Names are numbered consecutively from left to right starting at zero. 64 * (The letters are merely a taste of syntax sugar.) 65 * Thus, the first temporary (if any) is always numbered N (where N=arity). 66 * Every occurrence of a name reference in an argument list must refer to 67 * a name previously defined within the same lambda. 68 * A lambda has a void result if and only if its result index is -1. 69 * If a temporary has the type "V", it cannot be the subject of a NameRef, 70 * even though possesses a number. 71 * Note that all reference types are erased to "L", which stands for {@code Object}. 72 * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}. 73 * The other types stand for the usual primitive types. 74 * <p> 75 * Function invocation closely follows the static rules of the Java verifier. 76 * Arguments and return values must exactly match when their "Name" types are 77 * considered. 78 * Conversions are allowed only if they do not change the erased type. 79 * <ul> 80 * <li>L = Object: casts are used freely to convert into and out of reference types 81 * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments}) 82 * <li>J = long: no implicit conversions 83 * <li>F = float: no implicit conversions 84 * <li>D = double: no implicit conversions 85 * <li>V = void: a function result may be void if and only if its Name is of type "V" 86 * </ul> 87 * Although implicit conversions are not allowed, explicit ones can easily be 88 * encoded by using temporary expressions which call type-transformed identity functions. 89 * <p> 90 * Examples: 91 * <blockquote><pre>{@code 92 * (a0:J)=>{ a0 } 93 * == identity(long) 94 * (a0:I)=>{ t1:V = System.out#println(a0); void } 95 * == System.out#println(int) 96 * (a0:L)=>{ t1:V = System.out#println(a0); a0 } 97 * == identity, with printing side-effect 98 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 99 * t3:L = BoundMethodHandle#target(a0); 100 * t4:L = MethodHandle#invoke(t3, t2, a1); t4 } 101 * == general invoker for unary insertArgument combination 102 * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0); 103 * t3:L = MethodHandle#invoke(t2, a1); 104 * t4:L = FilterMethodHandle#target(a0); 105 * t5:L = MethodHandle#invoke(t4, t3); t5 } 106 * == general invoker for unary filterArgument combination 107 * (a0:L, a1:L)=>{ ...(same as previous example)... 108 * t5:L = MethodHandle#invoke(t4, t3, a1); t5 } 109 * == general invoker for unary/unary foldArgument combination 110 * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 } 111 * == invoker for identity method handle which performs i2l 112 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 113 * t3:L = Class#cast(t2,a1); t3 } 114 * == invoker for identity method handle which performs cast 115 * }</pre></blockquote> 116 * <p> 117 * @author John Rose, JSR 292 EG 118 */ 119 class LambdaForm { 120 final int arity; 121 final int result; 122 final boolean forceInline; 123 @Stable final Name[] names; 124 final String debugName; 125 MemberName vmentry; // low-level behavior, or null if not yet prepared 126 private boolean isCompiled; 127 128 Object transformCache; // managed by LambdaFormEditor 129 130 public static final int VOID_RESULT = -1, LAST_RESULT = -2; 131 132 enum BasicType { 133 L_TYPE('L', Object.class, Wrapper.OBJECT), // all reference types 134 I_TYPE('I', int.class, Wrapper.INT), 135 J_TYPE('J', long.class, Wrapper.LONG), 136 F_TYPE('F', float.class, Wrapper.FLOAT), 137 D_TYPE('D', double.class, Wrapper.DOUBLE), // all primitive types 138 V_TYPE('V', void.class, Wrapper.VOID); // not valid in all contexts 139 140 static final BasicType[] ALL_TYPES = BasicType.values(); 141 static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1); 142 143 static final int ARG_TYPE_LIMIT = ARG_TYPES.length; 144 static final int TYPE_LIMIT = ALL_TYPES.length; 145 146 private final char btChar; 147 private final Class<?> btClass; 148 private final Wrapper btWrapper; 149 150 private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) { 151 this.btChar = btChar; 152 this.btClass = btClass; 153 this.btWrapper = wrapper; 154 } 155 156 char basicTypeChar() { 157 return btChar; 158 } 159 Class<?> basicTypeClass() { 160 return btClass; 161 } 162 Wrapper basicTypeWrapper() { 163 return btWrapper; 164 } 165 int basicTypeSlots() { 166 return btWrapper.stackSlots(); 167 } 168 169 static BasicType basicType(byte type) { 170 return ALL_TYPES[type]; 171 } 172 static BasicType basicType(char type) { 173 switch (type) { 174 case 'L': return L_TYPE; 175 case 'I': return I_TYPE; 176 case 'J': return J_TYPE; 177 case 'F': return F_TYPE; 178 case 'D': return D_TYPE; 179 case 'V': return V_TYPE; 180 // all subword types are represented as ints 181 case 'Z': 182 case 'B': 183 case 'S': 184 case 'C': 185 return I_TYPE; 186 default: 187 throw newInternalError("Unknown type char: '"+type+"'"); 188 } 189 } 190 static BasicType basicType(Wrapper type) { 191 char c = type.basicTypeChar(); 192 return basicType(c); 193 } 194 static BasicType basicType(Class<?> type) { 195 if (!type.isPrimitive()) return L_TYPE; 196 return basicType(Wrapper.forPrimitiveType(type)); 197 } 198 199 static char basicTypeChar(Class<?> type) { 200 return basicType(type).btChar; 201 } 202 static BasicType[] basicTypes(List<Class<?>> types) { 203 BasicType[] btypes = new BasicType[types.size()]; 204 for (int i = 0; i < btypes.length; i++) { 205 btypes[i] = basicType(types.get(i)); 206 } 207 return btypes; 208 } 209 static BasicType[] basicTypes(String types) { 210 BasicType[] btypes = new BasicType[types.length()]; 211 for (int i = 0; i < btypes.length; i++) { 212 btypes[i] = basicType(types.charAt(i)); 213 } 214 return btypes; 215 } 216 static byte[] basicTypesOrd(BasicType[] btypes) { 217 byte[] ords = new byte[btypes.length]; 218 for (int i = 0; i < btypes.length; i++) { 219 ords[i] = (byte)btypes[i].ordinal(); 220 } 221 return ords; 222 } 223 static boolean isBasicTypeChar(char c) { 224 return "LIJFDV".indexOf(c) >= 0; 225 } 226 static boolean isArgBasicTypeChar(char c) { 227 return "LIJFD".indexOf(c) >= 0; 228 } 229 230 static { assert(checkBasicType()); } 231 private static boolean checkBasicType() { 232 for (int i = 0; i < ARG_TYPE_LIMIT; i++) { 233 assert ARG_TYPES[i].ordinal() == i; 234 assert ARG_TYPES[i] == ALL_TYPES[i]; 235 } 236 for (int i = 0; i < TYPE_LIMIT; i++) { 237 assert ALL_TYPES[i].ordinal() == i; 238 } 239 assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE; 240 assert !Arrays.asList(ARG_TYPES).contains(V_TYPE); 241 return true; 242 } 243 } 244 245 LambdaForm(String debugName, 246 int arity, Name[] names, int result) { 247 this(debugName, arity, names, result, true); 248 } 249 LambdaForm(String debugName, 250 int arity, Name[] names, int result, boolean forceInline) { 251 assert(namesOK(arity, names)); 252 this.arity = arity; 253 this.result = fixResult(result, names); 254 this.names = names.clone(); 255 this.debugName = fixDebugName(debugName); 256 this.forceInline = forceInline; 257 int maxOutArity = normalize(); 258 if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) { 259 // Cannot use LF interpreter on very high arity expressions. 260 assert(maxOutArity <= MethodType.MAX_JVM_ARITY); 261 compileToBytecode(); 262 } 263 } 264 LambdaForm(String debugName, 265 int arity, Name[] names) { 266 this(debugName, arity, names, LAST_RESULT, true); 267 } 268 LambdaForm(String debugName, 269 int arity, Name[] names, boolean forceInline) { 270 this(debugName, arity, names, LAST_RESULT, forceInline); 271 } 272 LambdaForm(String debugName, 273 Name[] formals, Name[] temps, Name result) { 274 this(debugName, 275 formals.length, buildNames(formals, temps, result), LAST_RESULT, true); 276 } 277 LambdaForm(String debugName, 278 Name[] formals, Name[] temps, Name result, boolean forceInline) { 279 this(debugName, 280 formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline); 281 } 282 283 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) { 284 int arity = formals.length; 285 int length = arity + temps.length + (result == null ? 0 : 1); 286 Name[] names = Arrays.copyOf(formals, length); 287 System.arraycopy(temps, 0, names, arity, temps.length); 288 if (result != null) 289 names[length - 1] = result; 290 return names; 291 } 292 293 private LambdaForm(String sig) { 294 this(sig, true); 295 } 296 297 private LambdaForm(String sig, boolean forceInline) { 298 // Make a blank lambda form, which returns a constant zero or null. 299 // It is used as a template for managing the invocation of similar forms that are non-empty. 300 // Called only from getPreparedForm. 301 assert(isValidSignature(sig)); 302 this.arity = signatureArity(sig); 303 this.result = (signatureReturn(sig) == V_TYPE ? -1 : arity); 304 this.names = buildEmptyNames(arity, sig); 305 this.debugName = "LF.zero"; 306 this.forceInline = forceInline; 307 assert(nameRefsAreLegal()); 308 assert(isEmpty()); 309 assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature(); 310 } 311 312 private static Name[] buildEmptyNames(int arity, String basicTypeSignature) { 313 assert(isValidSignature(basicTypeSignature)); 314 int resultPos = arity + 1; // skip '_' 315 if (arity < 0 || basicTypeSignature.length() != resultPos+1) 316 throw new IllegalArgumentException("bad arity for "+basicTypeSignature); 317 int numRes = (basicType(basicTypeSignature.charAt(resultPos)) == V_TYPE ? 0 : 1); 318 Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity)); 319 for (int i = 0; i < numRes; i++) { 320 Name zero = new Name(constantZero(basicType(basicTypeSignature.charAt(resultPos + i)))); 321 names[arity + i] = zero.newIndex(arity + i); 322 } 323 return names; 324 } 325 326 private static int fixResult(int result, Name[] names) { 327 if (result == LAST_RESULT) 328 result = names.length - 1; // might still be void 329 if (result >= 0 && names[result].type == V_TYPE) 330 result = VOID_RESULT; 331 return result; 332 } 333 334 private static String fixDebugName(String debugName) { 335 if (DEBUG_NAME_COUNTERS != null) { 336 int under = debugName.indexOf('_'); 337 int length = debugName.length(); 338 if (under < 0) under = length; 339 String debugNameStem = debugName.substring(0, under); 340 Integer ctr; 341 synchronized (DEBUG_NAME_COUNTERS) { 342 ctr = DEBUG_NAME_COUNTERS.get(debugNameStem); 343 if (ctr == null) ctr = 0; 344 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1); 345 } 346 StringBuilder buf = new StringBuilder(debugNameStem); 347 buf.append('_'); 348 int leadingZero = buf.length(); 349 buf.append((int) ctr); 350 for (int i = buf.length() - leadingZero; i < 3; i++) 351 buf.insert(leadingZero, '0'); 352 if (under < length) { 353 ++under; // skip "_" 354 while (under < length && Character.isDigit(debugName.charAt(under))) { 355 ++under; 356 } 357 if (under < length && debugName.charAt(under) == '_') ++under; 358 if (under < length) 359 buf.append('_').append(debugName, under, length); 360 } 361 return buf.toString(); 362 } 363 return debugName; 364 } 365 366 private static boolean namesOK(int arity, Name[] names) { 367 for (int i = 0; i < names.length; i++) { 368 Name n = names[i]; 369 assert(n != null) : "n is null"; 370 if (i < arity) 371 assert( n.isParam()) : n + " is not param at " + i; 372 else 373 assert(!n.isParam()) : n + " is param at " + i; 374 } 375 return true; 376 } 377 378 /** Renumber and/or replace params so that they are interned and canonically numbered. 379 * @return maximum argument list length among the names (since we have to pass over them anyway) 380 */ 381 private int normalize() { 382 Name[] oldNames = null; 383 int maxOutArity = 0; 384 int changesStart = 0; 385 for (int i = 0; i < names.length; i++) { 386 Name n = names[i]; 387 if (!n.initIndex(i)) { 388 if (oldNames == null) { 389 oldNames = names.clone(); 390 changesStart = i; 391 } 392 names[i] = n.cloneWithIndex(i); 393 } 394 if (n.arguments != null && maxOutArity < n.arguments.length) 395 maxOutArity = n.arguments.length; 396 } 397 if (oldNames != null) { 398 int startFixing = arity; 399 if (startFixing <= changesStart) 400 startFixing = changesStart+1; 401 for (int i = startFixing; i < names.length; i++) { 402 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i); 403 names[i] = fixed.newIndex(i); 404 } 405 } 406 assert(nameRefsAreLegal()); 407 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT); 408 boolean needIntern = false; 409 for (int i = 0; i < maxInterned; i++) { 410 Name n = names[i], n2 = internArgument(n); 411 if (n != n2) { 412 names[i] = n2; 413 needIntern = true; 414 } 415 } 416 if (needIntern) { 417 for (int i = arity; i < names.length; i++) { 418 names[i].internArguments(); 419 } 420 assert(nameRefsAreLegal()); 421 } 422 return maxOutArity; 423 } 424 425 /** 426 * Check that all embedded Name references are localizable to this lambda, 427 * and are properly ordered after their corresponding definitions. 428 * <p> 429 * Note that a Name can be local to multiple lambdas, as long as 430 * it possesses the same index in each use site. 431 * This allows Name references to be freely reused to construct 432 * fresh lambdas, without confusion. 433 */ 434 boolean nameRefsAreLegal() { 435 assert(arity >= 0 && arity <= names.length); 436 assert(result >= -1 && result < names.length); 437 // Do all names possess an index consistent with their local definition order? 438 for (int i = 0; i < arity; i++) { 439 Name n = names[i]; 440 assert(n.index() == i) : Arrays.asList(n.index(), i); 441 assert(n.isParam()); 442 } 443 // Also, do all local name references 444 for (int i = arity; i < names.length; i++) { 445 Name n = names[i]; 446 assert(n.index() == i); 447 for (Object arg : n.arguments) { 448 if (arg instanceof Name) { 449 Name n2 = (Name) arg; 450 int i2 = n2.index; 451 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length; 452 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this); 453 assert(i2 < i); // ref must come after def! 454 } 455 } 456 } 457 return true; 458 } 459 460 /** Invoke this form on the given arguments. */ 461 // final Object invoke(Object... args) throws Throwable { 462 // // NYI: fit this into the fast path? 463 // return interpretWithArguments(args); 464 // } 465 466 /** Report the return type. */ 467 BasicType returnType() { 468 if (result < 0) return V_TYPE; 469 Name n = names[result]; 470 return n.type; 471 } 472 473 /** Report the N-th argument type. */ 474 BasicType parameterType(int n) { 475 return parameter(n).type; 476 } 477 478 /** Report the N-th argument name. */ 479 Name parameter(int n) { 480 assert(n < arity); 481 Name param = names[n]; 482 assert(param.isParam()); 483 return param; 484 } 485 486 /** Report the N-th argument type constraint. */ 487 Object parameterConstraint(int n) { 488 return parameter(n).constraint; 489 } 490 491 /** Report the arity. */ 492 int arity() { 493 return arity; 494 } 495 496 /** Report the number of expressions (non-parameter names). */ 497 int expressionCount() { 498 return names.length - arity; 499 } 500 501 /** Return the method type corresponding to my basic type signature. */ 502 MethodType methodType() { 503 return signatureType(basicTypeSignature()); 504 } 505 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */ 506 final String basicTypeSignature() { 507 StringBuilder buf = new StringBuilder(arity() + 3); 508 for (int i = 0, a = arity(); i < a; i++) 509 buf.append(parameterType(i).basicTypeChar()); 510 return buf.append('_').append(returnType().basicTypeChar()).toString(); 511 } 512 static int signatureArity(String sig) { 513 assert(isValidSignature(sig)); 514 return sig.indexOf('_'); 515 } 516 static BasicType signatureReturn(String sig) { 517 return basicType(sig.charAt(signatureArity(sig) + 1)); 518 } 519 static boolean isValidSignature(String sig) { 520 int arity = sig.indexOf('_'); 521 if (arity < 0) return false; // must be of the form *_* 522 int siglen = sig.length(); 523 if (siglen != arity + 2) return false; // *_X 524 for (int i = 0; i < siglen; i++) { 525 if (i == arity) continue; // skip '_' 526 char c = sig.charAt(i); 527 if (c == 'V') 528 return (i == siglen - 1 && arity == siglen - 2); 529 if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD] 530 } 531 return true; // [LIJFD]*_[LIJFDV] 532 } 533 static MethodType signatureType(String sig) { 534 Class<?>[] ptypes = new Class<?>[signatureArity(sig)]; 535 for (int i = 0; i < ptypes.length; i++) 536 ptypes[i] = basicType(sig.charAt(i)).btClass; 537 Class<?> rtype = signatureReturn(sig).btClass; 538 return MethodType.methodType(rtype, ptypes); 539 } 540 541 /* 542 * Code generation issues: 543 * 544 * Compiled LFs should be reusable in general. 545 * The biggest issue is how to decide when to pull a name into 546 * the bytecode, versus loading a reified form from the MH data. 547 * 548 * For example, an asType wrapper may require execution of a cast 549 * after a call to a MH. The target type of the cast can be placed 550 * as a constant in the LF itself. This will force the cast type 551 * to be compiled into the bytecodes and native code for the MH. 552 * Or, the target type of the cast can be erased in the LF, and 553 * loaded from the MH data. (Later on, if the MH as a whole is 554 * inlined, the data will flow into the inlined instance of the LF, 555 * as a constant, and the end result will be an optimal cast.) 556 * 557 * This erasure of cast types can be done with any use of 558 * reference types. It can also be done with whole method 559 * handles. Erasing a method handle might leave behind 560 * LF code that executes correctly for any MH of a given 561 * type, and load the required MH from the enclosing MH's data. 562 * Or, the erasure might even erase the expected MT. 563 * 564 * Also, for direct MHs, the MemberName of the target 565 * could be erased, and loaded from the containing direct MH. 566 * As a simple case, a LF for all int-valued non-static 567 * field getters would perform a cast on its input argument 568 * (to non-constant base type derived from the MemberName) 569 * and load an integer value from the input object 570 * (at a non-constant offset also derived from the MemberName). 571 * Such MN-erased LFs would be inlinable back to optimized 572 * code, whenever a constant enclosing DMH is available 573 * to supply a constant MN from its data. 574 * 575 * The main problem here is to keep LFs reasonably generic, 576 * while ensuring that hot spots will inline good instances. 577 * "Reasonably generic" means that we don't end up with 578 * repeated versions of bytecode or machine code that do 579 * not differ in their optimized form. Repeated versions 580 * of machine would have the undesirable overheads of 581 * (a) redundant compilation work and (b) extra I$ pressure. 582 * To control repeated versions, we need to be ready to 583 * erase details from LFs and move them into MH data, 584 * whevener those details are not relevant to significant 585 * optimization. "Significant" means optimization of 586 * code that is actually hot. 587 * 588 * Achieving this may require dynamic splitting of MHs, by replacing 589 * a generic LF with a more specialized one, on the same MH, 590 * if (a) the MH is frequently executed and (b) the MH cannot 591 * be inlined into a containing caller, such as an invokedynamic. 592 * 593 * Compiled LFs that are no longer used should be GC-able. 594 * If they contain non-BCP references, they should be properly 595 * interlinked with the class loader(s) that their embedded types 596 * depend on. This probably means that reusable compiled LFs 597 * will be tabulated (indexed) on relevant class loaders, 598 * or else that the tables that cache them will have weak links. 599 */ 600 601 /** 602 * Make this LF directly executable, as part of a MethodHandle. 603 * Invariant: Every MH which is invoked must prepare its LF 604 * before invocation. 605 * (In principle, the JVM could do this very lazily, 606 * as a sort of pre-invocation linkage step.) 607 */ 608 public void prepare() { 609 if (COMPILE_THRESHOLD == 0) { 610 compileToBytecode(); 611 } 612 if (this.vmentry != null) { 613 // already prepared (e.g., a primitive DMH invoker form) 614 return; 615 } 616 LambdaForm prep = getPreparedForm(basicTypeSignature()); 617 this.vmentry = prep.vmentry; 618 // TO DO: Maybe add invokeGeneric, invokeWithArguments 619 } 620 621 /** Generate optimizable bytecode for this form. */ 622 MemberName compileToBytecode() { 623 MethodType invokerType = methodType(); 624 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); 625 if (vmentry != null && isCompiled) { 626 return vmentry; // already compiled somehow 627 } 628 try { 629 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType); 630 if (TRACE_INTERPRETER) 631 traceInterpreter("compileToBytecode", this); 632 isCompiled = true; 633 return vmentry; 634 } catch (Error | Exception ex) { 635 throw newInternalError(this.toString(), ex); 636 } 637 } 638 639 private static void computeInitialPreparedForms() { 640 // Find all predefined invokers and associate them with canonical empty lambda forms. 641 for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) { 642 if (!m.isStatic() || !m.isPackage()) continue; 643 MethodType mt = m.getMethodType(); 644 if (mt.parameterCount() > 0 && 645 mt.parameterType(0) == MethodHandle.class && 646 m.getName().startsWith("interpret_")) { 647 String sig = basicTypeSignature(mt); 648 assert(m.getName().equals("interpret" + sig.substring(sig.indexOf('_')))); 649 LambdaForm form = new LambdaForm(sig); 650 form.vmentry = m; 651 form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form); 652 } 653 } 654 } 655 656 // Set this false to disable use of the interpret_L methods defined in this file. 657 private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true; 658 659 // The following are predefined exact invokers. The system must build 660 // a separate invoker for each distinct signature. 661 static Object interpret_L(MethodHandle mh) throws Throwable { 662 Object[] av = {mh}; 663 String sig = null; 664 assert(argumentTypesMatch(sig = "L_L", av)); 665 Object res = mh.form.interpretWithArguments(av); 666 assert(returnTypesMatch(sig, av, res)); 667 return res; 668 } 669 static Object interpret_L(MethodHandle mh, Object x1) throws Throwable { 670 Object[] av = {mh, x1}; 671 String sig = null; 672 assert(argumentTypesMatch(sig = "LL_L", av)); 673 Object res = mh.form.interpretWithArguments(av); 674 assert(returnTypesMatch(sig, av, res)); 675 return res; 676 } 677 static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable { 678 Object[] av = {mh, x1, x2}; 679 String sig = null; 680 assert(argumentTypesMatch(sig = "LLL_L", av)); 681 Object res = mh.form.interpretWithArguments(av); 682 assert(returnTypesMatch(sig, av, res)); 683 return res; 684 } 685 private static LambdaForm getPreparedForm(String sig) { 686 MethodType mtype = signatureType(sig); 687 LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET); 688 if (prep != null) return prep; 689 assert(isValidSignature(sig)); 690 prep = new LambdaForm(sig); 691 prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig); 692 return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep); 693 } 694 695 // The next few routines are called only from assert expressions 696 // They verify that the built-in invokers process the correct raw data types. 697 private static boolean argumentTypesMatch(String sig, Object[] av) { 698 int arity = signatureArity(sig); 699 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity; 700 assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0]; 701 MethodHandle mh = (MethodHandle) av[0]; 702 MethodType mt = mh.type(); 703 assert(mt.parameterCount() == arity-1); 704 for (int i = 0; i < av.length; i++) { 705 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1)); 706 assert(valueMatches(basicType(sig.charAt(i)), pt, av[i])); 707 } 708 return true; 709 } 710 private static boolean valueMatches(BasicType tc, Class<?> type, Object x) { 711 // The following line is needed because (...)void method handles can use non-void invokers 712 if (type == void.class) tc = V_TYPE; // can drop any kind of value 713 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type); 714 switch (tc) { 715 case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; 716 case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break; 717 case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break; 718 case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break; 719 case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; 720 case V_TYPE: break; // allow anything here; will be dropped 721 default: assert(false); 722 } 723 return true; 724 } 725 private static boolean returnTypesMatch(String sig, Object[] av, Object res) { 726 MethodHandle mh = (MethodHandle) av[0]; 727 return valueMatches(signatureReturn(sig), mh.type().returnType(), res); 728 } 729 private static boolean checkInt(Class<?> type, Object x) { 730 assert(x instanceof Integer); 731 if (type == int.class) return true; 732 Wrapper w = Wrapper.forBasicType(type); 733 assert(w.isSubwordOrInt()); 734 Object x1 = Wrapper.INT.wrap(w.wrap(x)); 735 return x.equals(x1); 736 } 737 private static boolean checkRef(Class<?> type, Object x) { 738 assert(!type.isPrimitive()); 739 if (x == null) return true; 740 if (type.isInterface()) return true; 741 return type.isInstance(x); 742 } 743 744 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */ 745 private static final int COMPILE_THRESHOLD; 746 static { 747 COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD); 748 } 749 private int invocationCounter = 0; 750 751 @Hidden 752 @DontInline 753 /** Interpretively invoke this form on the given arguments. */ 754 Object interpretWithArguments(Object... argumentValues) throws Throwable { 755 if (TRACE_INTERPRETER) 756 return interpretWithArgumentsTracing(argumentValues); 757 checkInvocationCounter(); 758 assert(arityCheck(argumentValues)); 759 Object[] values = Arrays.copyOf(argumentValues, names.length); 760 for (int i = argumentValues.length; i < values.length; i++) { 761 values[i] = interpretName(names[i], values); 762 } 763 Object rv = (result < 0) ? null : values[result]; 764 assert(resultCheck(argumentValues, rv)); 765 return rv; 766 } 767 768 @Hidden 769 @DontInline 770 /** Evaluate a single Name within this form, applying its function to its arguments. */ 771 Object interpretName(Name name, Object[] values) throws Throwable { 772 if (TRACE_INTERPRETER) 773 traceInterpreter("| interpretName", name.debugString(), (Object[]) null); 774 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class); 775 for (int i = 0; i < arguments.length; i++) { 776 Object a = arguments[i]; 777 if (a instanceof Name) { 778 int i2 = ((Name)a).index(); 779 assert(names[i2] == a); 780 a = values[i2]; 781 arguments[i] = a; 782 } 783 } 784 return name.function.invokeWithArguments(arguments); 785 } 786 787 private void checkInvocationCounter() { 788 if (COMPILE_THRESHOLD != 0 && 789 invocationCounter < COMPILE_THRESHOLD) { 790 invocationCounter++; // benign race 791 if (invocationCounter >= COMPILE_THRESHOLD) { 792 // Replace vmentry with a bytecode version of this LF. 793 compileToBytecode(); 794 } 795 } 796 } 797 Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable { 798 traceInterpreter("[ interpretWithArguments", this, argumentValues); 799 if (invocationCounter < COMPILE_THRESHOLD) { 800 int ctr = invocationCounter++; // benign race 801 traceInterpreter("| invocationCounter", ctr); 802 if (invocationCounter >= COMPILE_THRESHOLD) { 803 compileToBytecode(); 804 } 805 } 806 Object rval; 807 try { 808 assert(arityCheck(argumentValues)); 809 Object[] values = Arrays.copyOf(argumentValues, names.length); 810 for (int i = argumentValues.length; i < values.length; i++) { 811 values[i] = interpretName(names[i], values); 812 } 813 rval = (result < 0) ? null : values[result]; 814 } catch (Throwable ex) { 815 traceInterpreter("] throw =>", ex); 816 throw ex; 817 } 818 traceInterpreter("] return =>", rval); 819 return rval; 820 } 821 822 static void traceInterpreter(String event, Object obj, Object... args) { 823 if (TRACE_INTERPRETER) { 824 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : "")); 825 } 826 } 827 static void traceInterpreter(String event, Object obj) { 828 traceInterpreter(event, obj, (Object[])null); 829 } 830 private boolean arityCheck(Object[] argumentValues) { 831 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length"; 832 // also check that the leading (receiver) argument is somehow bound to this LF: 833 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0]; 834 MethodHandle mh = (MethodHandle) argumentValues[0]; 835 assert(mh.internalForm() == this); 836 // note: argument #0 could also be an interface wrapper, in the future 837 argumentTypesMatch(basicTypeSignature(), argumentValues); 838 return true; 839 } 840 private boolean resultCheck(Object[] argumentValues, Object result) { 841 MethodHandle mh = (MethodHandle) argumentValues[0]; 842 MethodType mt = mh.type(); 843 assert(valueMatches(returnType(), mt.returnType(), result)); 844 return true; 845 } 846 847 private boolean isEmpty() { 848 if (result < 0) 849 return (names.length == arity); 850 else if (result == arity && names.length == arity + 1) 851 return names[arity].isConstantZero(); 852 else 853 return false; 854 } 855 856 public String toString() { 857 StringBuilder buf = new StringBuilder(debugName+"=Lambda("); 858 for (int i = 0; i < names.length; i++) { 859 if (i == arity) buf.append(")=>{"); 860 Name n = names[i]; 861 if (i >= arity) buf.append("\n "); 862 buf.append(n.paramString()); 863 if (i < arity) { 864 if (i+1 < arity) buf.append(","); 865 continue; 866 } 867 buf.append("=").append(n.exprString()); 868 buf.append(";"); 869 } 870 if (arity == names.length) buf.append(")=>{"); 871 buf.append(result < 0 ? "void" : names[result]).append("}"); 872 if (TRACE_INTERPRETER) { 873 // Extra verbosity: 874 buf.append(":").append(basicTypeSignature()); 875 buf.append("/").append(vmentry); 876 } 877 return buf.toString(); 878 } 879 880 @Override 881 public boolean equals(Object obj) { 882 return obj instanceof LambdaForm && equals((LambdaForm)obj); 883 } 884 public boolean equals(LambdaForm that) { 885 if (this.result != that.result) return false; 886 return Arrays.equals(this.names, that.names); 887 } 888 public int hashCode() { 889 return result + 31 * Arrays.hashCode(names); 890 } 891 LambdaFormEditor editor() { 892 return LambdaFormEditor.lambdaFormEditor(this); 893 } 894 895 boolean contains(Name name) { 896 int pos = name.index(); 897 if (pos >= 0) { 898 return pos < names.length && name.equals(names[pos]); 899 } 900 for (int i = arity; i < names.length; i++) { 901 if (name.equals(names[i])) 902 return true; 903 } 904 return false; 905 } 906 907 LambdaForm addArguments(int pos, BasicType... types) { 908 // names array has MH in slot 0; skip it. 909 int argpos = pos + 1; 910 assert(argpos <= arity); 911 int length = names.length; 912 int inTypes = types.length; 913 Name[] names2 = Arrays.copyOf(names, length + inTypes); 914 int arity2 = arity + inTypes; 915 int result2 = result; 916 if (result2 >= argpos) 917 result2 += inTypes; 918 // Note: The LF constructor will rename names2[argpos...]. 919 // Make space for new arguments (shift temporaries). 920 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos); 921 for (int i = 0; i < inTypes; i++) { 922 names2[argpos + i] = new Name(types[i]); 923 } 924 return new LambdaForm(debugName, arity2, names2, result2); 925 } 926 927 LambdaForm addArguments(int pos, List<Class<?>> types) { 928 return addArguments(pos, basicTypes(types)); 929 } 930 931 LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) { 932 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg. 933 // The types are the types of the new (incoming) arguments. 934 int length = names.length; 935 int inTypes = types.length; 936 int outArgs = reorder.length; 937 assert(skip+outArgs == arity); 938 assert(permutedTypesMatch(reorder, types, names, skip)); 939 int pos = 0; 940 // skip trivial first part of reordering: 941 while (pos < outArgs && reorder[pos] == pos) pos += 1; 942 Name[] names2 = new Name[length - outArgs + inTypes]; 943 System.arraycopy(names, 0, names2, 0, skip+pos); 944 // copy the body: 945 int bodyLength = length - arity; 946 System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength); 947 int arity2 = names2.length - bodyLength; 948 int result2 = result; 949 if (result2 >= 0) { 950 if (result2 < skip+outArgs) { 951 // return the corresponding inArg 952 result2 = reorder[result2-skip]; 953 } else { 954 result2 = result2 - outArgs + inTypes; 955 } 956 } 957 // rework names in the body: 958 for (int j = pos; j < outArgs; j++) { 959 Name n = names[skip+j]; 960 int i = reorder[j]; 961 // replace names[skip+j] by names2[skip+i] 962 Name n2 = names2[skip+i]; 963 if (n2 == null) 964 names2[skip+i] = n2 = new Name(types[i]); 965 else 966 assert(n2.type == types[i]); 967 for (int k = arity2; k < names2.length; k++) { 968 names2[k] = names2[k].replaceName(n, n2); 969 } 970 } 971 // some names are unused, but must be filled in 972 for (int i = skip+pos; i < arity2; i++) { 973 if (names2[i] == null) 974 names2[i] = argument(i, types[i - skip]); 975 } 976 for (int j = arity; j < names.length; j++) { 977 int i = j - arity + arity2; 978 // replace names2[i] by names[j] 979 Name n = names[j]; 980 Name n2 = names2[i]; 981 if (n != n2) { 982 for (int k = i+1; k < names2.length; k++) { 983 names2[k] = names2[k].replaceName(n, n2); 984 } 985 } 986 } 987 return new LambdaForm(debugName, arity2, names2, result2); 988 } 989 990 static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) { 991 int inTypes = types.length; 992 int outArgs = reorder.length; 993 for (int i = 0; i < outArgs; i++) { 994 assert(names[skip+i].isParam()); 995 assert(names[skip+i].type == types[reorder[i]]); 996 } 997 return true; 998 } 999 1000 static class NamedFunction { 1001 final MemberName member; 1002 @Stable MethodHandle resolvedHandle; 1003 @Stable MethodHandle invoker; 1004 1005 NamedFunction(MethodHandle resolvedHandle) { 1006 this(resolvedHandle.internalMemberName(), resolvedHandle); 1007 } 1008 NamedFunction(MemberName member, MethodHandle resolvedHandle) { 1009 this.member = member; 1010 this.resolvedHandle = resolvedHandle; 1011 // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest. 1012 //assert(!isInvokeBasic()); 1013 } 1014 NamedFunction(MethodType basicInvokerType) { 1015 assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType; 1016 if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) { 1017 this.resolvedHandle = basicInvokerType.invokers().basicInvoker(); 1018 this.member = resolvedHandle.internalMemberName(); 1019 } else { 1020 // necessary to pass BigArityTest 1021 this.member = Invokers.invokeBasicMethod(basicInvokerType); 1022 } 1023 assert(isInvokeBasic()); 1024 } 1025 1026 private boolean isInvokeBasic() { 1027 return member != null && 1028 member.isMethodHandleInvoke() && 1029 "invokeBasic".equals(member.getName()); 1030 } 1031 1032 // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc. 1033 // Any LambdaForm containing such a member is not interpretable. 1034 // This is OK, since all such LFs are prepared with special primitive vmentry points. 1035 // And even without the resolvedHandle, the name can still be compiled and optimized. 1036 NamedFunction(Method method) { 1037 this(new MemberName(method)); 1038 } 1039 NamedFunction(Field field) { 1040 this(new MemberName(field)); 1041 } 1042 NamedFunction(MemberName member) { 1043 this.member = member; 1044 this.resolvedHandle = null; 1045 } 1046 1047 MethodHandle resolvedHandle() { 1048 if (resolvedHandle == null) resolve(); 1049 return resolvedHandle; 1050 } 1051 1052 void resolve() { 1053 resolvedHandle = DirectMethodHandle.make(member); 1054 } 1055 1056 @Override 1057 public boolean equals(Object other) { 1058 if (this == other) return true; 1059 if (other == null) return false; 1060 if (!(other instanceof NamedFunction)) return false; 1061 NamedFunction that = (NamedFunction) other; 1062 return this.member != null && this.member.equals(that.member); 1063 } 1064 1065 @Override 1066 public int hashCode() { 1067 if (member != null) 1068 return member.hashCode(); 1069 return super.hashCode(); 1070 } 1071 1072 // Put the predefined NamedFunction invokers into the table. 1073 static void initializeInvokers() { 1074 for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) { 1075 if (!m.isStatic() || !m.isPackage()) continue; 1076 MethodType type = m.getMethodType(); 1077 if (type.equals(INVOKER_METHOD_TYPE) && 1078 m.getName().startsWith("invoke_")) { 1079 String sig = m.getName().substring("invoke_".length()); 1080 int arity = LambdaForm.signatureArity(sig); 1081 MethodType srcType = MethodType.genericMethodType(arity); 1082 if (LambdaForm.signatureReturn(sig) == V_TYPE) 1083 srcType = srcType.changeReturnType(void.class); 1084 MethodTypeForm typeForm = srcType.form(); 1085 typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m)); 1086 } 1087 } 1088 } 1089 1090 // The following are predefined NamedFunction invokers. The system must build 1091 // a separate invoker for each distinct signature. 1092 /** void return type invokers. */ 1093 @Hidden 1094 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable { 1095 assert(arityCheck(0, void.class, mh, a)); 1096 mh.invokeBasic(); 1097 return null; 1098 } 1099 @Hidden 1100 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable { 1101 assert(arityCheck(1, void.class, mh, a)); 1102 mh.invokeBasic(a[0]); 1103 return null; 1104 } 1105 @Hidden 1106 static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable { 1107 assert(arityCheck(2, void.class, mh, a)); 1108 mh.invokeBasic(a[0], a[1]); 1109 return null; 1110 } 1111 @Hidden 1112 static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable { 1113 assert(arityCheck(3, void.class, mh, a)); 1114 mh.invokeBasic(a[0], a[1], a[2]); 1115 return null; 1116 } 1117 @Hidden 1118 static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable { 1119 assert(arityCheck(4, void.class, mh, a)); 1120 mh.invokeBasic(a[0], a[1], a[2], a[3]); 1121 return null; 1122 } 1123 @Hidden 1124 static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable { 1125 assert(arityCheck(5, void.class, mh, a)); 1126 mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]); 1127 return null; 1128 } 1129 /** Object return type invokers. */ 1130 @Hidden 1131 static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable { 1132 assert(arityCheck(0, mh, a)); 1133 return mh.invokeBasic(); 1134 } 1135 @Hidden 1136 static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable { 1137 assert(arityCheck(1, mh, a)); 1138 return mh.invokeBasic(a[0]); 1139 } 1140 @Hidden 1141 static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable { 1142 assert(arityCheck(2, mh, a)); 1143 return mh.invokeBasic(a[0], a[1]); 1144 } 1145 @Hidden 1146 static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable { 1147 assert(arityCheck(3, mh, a)); 1148 return mh.invokeBasic(a[0], a[1], a[2]); 1149 } 1150 @Hidden 1151 static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable { 1152 assert(arityCheck(4, mh, a)); 1153 return mh.invokeBasic(a[0], a[1], a[2], a[3]); 1154 } 1155 @Hidden 1156 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable { 1157 assert(arityCheck(5, mh, a)); 1158 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]); 1159 } 1160 private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) { 1161 return arityCheck(arity, Object.class, mh, a); 1162 } 1163 private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) { 1164 assert(a.length == arity) 1165 : Arrays.asList(a.length, arity); 1166 assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype)) 1167 : Arrays.asList(mh, rtype, arity); 1168 MemberName member = mh.internalMemberName(); 1169 if (member != null && member.getName().equals("invokeBasic") && member.isMethodHandleInvoke()) { 1170 assert(arity > 0); 1171 assert(a[0] instanceof MethodHandle); 1172 MethodHandle mh2 = (MethodHandle) a[0]; 1173 assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype)) 1174 : Arrays.asList(member, mh2, rtype, arity); 1175 } 1176 return true; 1177 } 1178 1179 static final MethodType INVOKER_METHOD_TYPE = 1180 MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1181 1182 private static MethodHandle computeInvoker(MethodTypeForm typeForm) { 1183 typeForm = typeForm.basicType().form(); // normalize to basic type 1184 MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1185 if (mh != null) return mh; 1186 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while 1187 mh = DirectMethodHandle.make(invoker); 1188 MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1189 if (mh2 != null) return mh2; // benign race 1190 if (!mh.type().equals(INVOKER_METHOD_TYPE)) 1191 throw newInternalError(mh.debugString()); 1192 return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh); 1193 } 1194 1195 @Hidden 1196 Object invokeWithArguments(Object... arguments) throws Throwable { 1197 // If we have a cached invoker, call it right away. 1198 // NOTE: The invoker always returns a reference value. 1199 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments); 1200 assert(checkArgumentTypes(arguments, methodType())); 1201 return invoker().invokeBasic(resolvedHandle(), arguments); 1202 } 1203 1204 @Hidden 1205 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable { 1206 Object rval; 1207 try { 1208 traceInterpreter("[ call", this, arguments); 1209 if (invoker == null) { 1210 traceInterpreter("| getInvoker", this); 1211 invoker(); 1212 } 1213 if (resolvedHandle == null) { 1214 traceInterpreter("| resolve", this); 1215 resolvedHandle(); 1216 } 1217 assert(checkArgumentTypes(arguments, methodType())); 1218 rval = invoker().invokeBasic(resolvedHandle(), arguments); 1219 } catch (Throwable ex) { 1220 traceInterpreter("] throw =>", ex); 1221 throw ex; 1222 } 1223 traceInterpreter("] return =>", rval); 1224 return rval; 1225 } 1226 1227 private MethodHandle invoker() { 1228 if (invoker != null) return invoker; 1229 // Get an invoker and cache it. 1230 return invoker = computeInvoker(methodType().form()); 1231 } 1232 1233 private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) { 1234 if (true) return true; // FIXME 1235 MethodType dstType = methodType.form().erasedType(); 1236 MethodType srcType = dstType.basicType().wrap(); 1237 Class<?>[] ptypes = new Class<?>[arguments.length]; 1238 for (int i = 0; i < arguments.length; i++) { 1239 Object arg = arguments[i]; 1240 Class<?> ptype = arg == null ? Object.class : arg.getClass(); 1241 // If the dest. type is a primitive we keep the 1242 // argument type. 1243 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class; 1244 } 1245 MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap(); 1246 assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType; 1247 return true; 1248 } 1249 1250 MethodType methodType() { 1251 if (resolvedHandle != null) 1252 return resolvedHandle.type(); 1253 else 1254 // only for certain internal LFs during bootstrapping 1255 return member.getInvocationType(); 1256 } 1257 1258 MemberName member() { 1259 assert(assertMemberIsConsistent()); 1260 return member; 1261 } 1262 1263 // Called only from assert. 1264 private boolean assertMemberIsConsistent() { 1265 if (resolvedHandle instanceof DirectMethodHandle) { 1266 MemberName m = resolvedHandle.internalMemberName(); 1267 assert(m.equals(member)); 1268 } 1269 return true; 1270 } 1271 1272 Class<?> memberDeclaringClassOrNull() { 1273 return (member == null) ? null : member.getDeclaringClass(); 1274 } 1275 1276 BasicType returnType() { 1277 return basicType(methodType().returnType()); 1278 } 1279 1280 BasicType parameterType(int n) { 1281 return basicType(methodType().parameterType(n)); 1282 } 1283 1284 int arity() { 1285 return methodType().parameterCount(); 1286 } 1287 1288 public String toString() { 1289 if (member == null) return String.valueOf(resolvedHandle); 1290 return member.getDeclaringClass().getSimpleName()+"."+member.getName(); 1291 } 1292 1293 public boolean isIdentity() { 1294 return this.equals(identity(returnType())); 1295 } 1296 1297 public boolean isConstantZero() { 1298 return this.equals(constantZero(returnType())); 1299 } 1300 1301 public MethodHandleImpl.Intrinsic intrinsicName() { 1302 return resolvedHandle == null ? MethodHandleImpl.Intrinsic.NONE 1303 : resolvedHandle.intrinsicName(); 1304 } 1305 } 1306 1307 public static String basicTypeSignature(MethodType type) { 1308 char[] sig = new char[type.parameterCount() + 2]; 1309 int sigp = 0; 1310 for (Class<?> pt : type.parameterList()) { 1311 sig[sigp++] = basicTypeChar(pt); 1312 } 1313 sig[sigp++] = '_'; 1314 sig[sigp++] = basicTypeChar(type.returnType()); 1315 assert(sigp == sig.length); 1316 return String.valueOf(sig); 1317 } 1318 public static String shortenSignature(String signature) { 1319 // Hack to make signatures more readable when they show up in method names. 1320 final int NO_CHAR = -1, MIN_RUN = 3; 1321 int c0, c1 = NO_CHAR, c1reps = 0; 1322 StringBuilder buf = null; 1323 int len = signature.length(); 1324 if (len < MIN_RUN) return signature; 1325 for (int i = 0; i <= len; i++) { 1326 // shift in the next char: 1327 c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i)); 1328 if (c1 == c0) { ++c1reps; continue; } 1329 // shift in the next count: 1330 int c0reps = c1reps; c1reps = 1; 1331 // end of a character run 1332 if (c0reps < MIN_RUN) { 1333 if (buf != null) { 1334 while (--c0reps >= 0) 1335 buf.append((char)c0); 1336 } 1337 continue; 1338 } 1339 // found three or more in a row 1340 if (buf == null) 1341 buf = new StringBuilder().append(signature, 0, i - c0reps); 1342 buf.append((char)c0).append(c0reps); 1343 } 1344 return (buf == null) ? signature : buf.toString(); 1345 } 1346 1347 static final class Name { 1348 final BasicType type; 1349 private short index; 1350 final NamedFunction function; 1351 final Object constraint; // additional type information, if not null 1352 @Stable final Object[] arguments; 1353 1354 private Name(int index, BasicType type, NamedFunction function, Object[] arguments) { 1355 this.index = (short)index; 1356 this.type = type; 1357 this.function = function; 1358 this.arguments = arguments; 1359 this.constraint = null; 1360 assert(this.index == index); 1361 } 1362 private Name(Name that, Object constraint) { 1363 this.index = that.index; 1364 this.type = that.type; 1365 this.function = that.function; 1366 this.arguments = that.arguments; 1367 this.constraint = constraint; 1368 assert(constraint == null || isParam()); // only params have constraints 1369 assert(constraint == null || constraint instanceof BoundMethodHandle.SpeciesData || constraint instanceof Class); 1370 } 1371 Name(MethodHandle function, Object... arguments) { 1372 this(new NamedFunction(function), arguments); 1373 } 1374 Name(MethodType functionType, Object... arguments) { 1375 this(new NamedFunction(functionType), arguments); 1376 assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE); 1377 } 1378 Name(MemberName function, Object... arguments) { 1379 this(new NamedFunction(function), arguments); 1380 } 1381 Name(NamedFunction function, Object... arguments) { 1382 this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class)); 1383 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString(); 1384 for (int i = 0; i < arguments.length; i++) 1385 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString(); 1386 } 1387 /** Create a raw parameter of the given type, with an expected index. */ 1388 Name(int index, BasicType type) { 1389 this(index, type, null, null); 1390 } 1391 /** Create a raw parameter of the given type. */ 1392 Name(BasicType type) { this(-1, type); } 1393 1394 BasicType type() { return type; } 1395 int index() { return index; } 1396 boolean initIndex(int i) { 1397 if (index != i) { 1398 if (index != -1) return false; 1399 index = (short)i; 1400 } 1401 return true; 1402 } 1403 char typeChar() { 1404 return type.btChar; 1405 } 1406 1407 void resolve() { 1408 if (function != null) 1409 function.resolve(); 1410 } 1411 1412 Name newIndex(int i) { 1413 if (initIndex(i)) return this; 1414 return cloneWithIndex(i); 1415 } 1416 Name cloneWithIndex(int i) { 1417 Object[] newArguments = (arguments == null) ? null : arguments.clone(); 1418 return new Name(i, type, function, newArguments).withConstraint(constraint); 1419 } 1420 Name withConstraint(Object constraint) { 1421 if (constraint == this.constraint) return this; 1422 return new Name(this, constraint); 1423 } 1424 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly 1425 if (oldName == newName) return this; 1426 @SuppressWarnings("LocalVariableHidesMemberVariable") 1427 Object[] arguments = this.arguments; 1428 if (arguments == null) return this; 1429 boolean replaced = false; 1430 for (int j = 0; j < arguments.length; j++) { 1431 if (arguments[j] == oldName) { 1432 if (!replaced) { 1433 replaced = true; 1434 arguments = arguments.clone(); 1435 } 1436 arguments[j] = newName; 1437 } 1438 } 1439 if (!replaced) return this; 1440 return new Name(function, arguments); 1441 } 1442 /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i]. 1443 * Limit such replacements to {@code start<=i<end}. Return possibly changed self. 1444 */ 1445 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) { 1446 if (start >= end) return this; 1447 @SuppressWarnings("LocalVariableHidesMemberVariable") 1448 Object[] arguments = this.arguments; 1449 boolean replaced = false; 1450 eachArg: 1451 for (int j = 0; j < arguments.length; j++) { 1452 if (arguments[j] instanceof Name) { 1453 Name n = (Name) arguments[j]; 1454 int check = n.index; 1455 // harmless check to see if the thing is already in newNames: 1456 if (check >= 0 && check < newNames.length && n == newNames[check]) 1457 continue eachArg; 1458 // n might not have the correct index: n != oldNames[n.index]. 1459 for (int i = start; i < end; i++) { 1460 if (n == oldNames[i]) { 1461 if (n == newNames[i]) 1462 continue eachArg; 1463 if (!replaced) { 1464 replaced = true; 1465 arguments = arguments.clone(); 1466 } 1467 arguments[j] = newNames[i]; 1468 continue eachArg; 1469 } 1470 } 1471 } 1472 } 1473 if (!replaced) return this; 1474 return new Name(function, arguments); 1475 } 1476 void internArguments() { 1477 @SuppressWarnings("LocalVariableHidesMemberVariable") 1478 Object[] arguments = this.arguments; 1479 for (int j = 0; j < arguments.length; j++) { 1480 if (arguments[j] instanceof Name) { 1481 Name n = (Name) arguments[j]; 1482 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT) 1483 arguments[j] = internArgument(n); 1484 } 1485 } 1486 } 1487 boolean isParam() { 1488 return function == null; 1489 } 1490 boolean isConstantZero() { 1491 return !isParam() && arguments.length == 0 && function.isConstantZero(); 1492 } 1493 1494 public String toString() { 1495 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar(); 1496 } 1497 public String debugString() { 1498 String s = paramString(); 1499 return (function == null) ? s : s + "=" + exprString(); 1500 } 1501 public String paramString() { 1502 String s = toString(); 1503 Object c = constraint; 1504 if (c == null) 1505 return s; 1506 if (c instanceof Class) c = ((Class<?>)c).getSimpleName(); 1507 return s + "/" + c; 1508 } 1509 public String exprString() { 1510 if (function == null) return toString(); 1511 StringBuilder buf = new StringBuilder(function.toString()); 1512 buf.append("("); 1513 String cma = ""; 1514 for (Object a : arguments) { 1515 buf.append(cma); cma = ","; 1516 if (a instanceof Name || a instanceof Integer) 1517 buf.append(a); 1518 else 1519 buf.append("(").append(a).append(")"); 1520 } 1521 buf.append(")"); 1522 return buf.toString(); 1523 } 1524 1525 static boolean typesMatch(BasicType parameterType, Object object) { 1526 if (object instanceof Name) { 1527 return ((Name)object).type == parameterType; 1528 } 1529 switch (parameterType) { 1530 case I_TYPE: return object instanceof Integer; 1531 case J_TYPE: return object instanceof Long; 1532 case F_TYPE: return object instanceof Float; 1533 case D_TYPE: return object instanceof Double; 1534 } 1535 assert(parameterType == L_TYPE); 1536 return true; 1537 } 1538 1539 /** Return the index of the last occurrence of n in the argument array. 1540 * Return -1 if the name is not used. 1541 */ 1542 int lastUseIndex(Name n) { 1543 if (arguments == null) return -1; 1544 for (int i = arguments.length; --i >= 0; ) { 1545 if (arguments[i] == n) return i; 1546 } 1547 return -1; 1548 } 1549 1550 /** Return the number of occurrences of n in the argument array. 1551 * Return 0 if the name is not used. 1552 */ 1553 int useCount(Name n) { 1554 if (arguments == null) return 0; 1555 int count = 0; 1556 for (int i = arguments.length; --i >= 0; ) { 1557 if (arguments[i] == n) ++count; 1558 } 1559 return count; 1560 } 1561 1562 boolean contains(Name n) { 1563 return this == n || lastUseIndex(n) >= 0; 1564 } 1565 1566 public boolean equals(Name that) { 1567 if (this == that) return true; 1568 if (isParam()) 1569 // each parameter is a unique atom 1570 return false; // this != that 1571 return 1572 //this.index == that.index && 1573 this.type == that.type && 1574 this.function.equals(that.function) && 1575 Arrays.equals(this.arguments, that.arguments); 1576 } 1577 @Override 1578 public boolean equals(Object x) { 1579 return x instanceof Name && equals((Name)x); 1580 } 1581 @Override 1582 public int hashCode() { 1583 if (isParam()) 1584 return index | (type.ordinal() << 8); 1585 return function.hashCode() ^ Arrays.hashCode(arguments); 1586 } 1587 } 1588 1589 /** Return the index of the last name which contains n as an argument. 1590 * Return -1 if the name is not used. Return names.length if it is the return value. 1591 */ 1592 int lastUseIndex(Name n) { 1593 int ni = n.index, nmax = names.length; 1594 assert(names[ni] == n); 1595 if (result == ni) return nmax; // live all the way beyond the end 1596 for (int i = nmax; --i > ni; ) { 1597 if (names[i].lastUseIndex(n) >= 0) 1598 return i; 1599 } 1600 return -1; 1601 } 1602 1603 /** Return the number of times n is used as an argument or return value. */ 1604 int useCount(Name n) { 1605 int ni = n.index, nmax = names.length; 1606 int end = lastUseIndex(n); 1607 if (end < 0) return 0; 1608 int count = 0; 1609 if (end == nmax) { count++; end--; } 1610 int beg = n.index() + 1; 1611 if (beg < arity) beg = arity; 1612 for (int i = beg; i <= end; i++) { 1613 count += names[i].useCount(n); 1614 } 1615 return count; 1616 } 1617 1618 static Name argument(int which, char type) { 1619 return argument(which, basicType(type)); 1620 } 1621 static Name argument(int which, BasicType type) { 1622 if (which >= INTERNED_ARGUMENT_LIMIT) 1623 return new Name(which, type); 1624 return INTERNED_ARGUMENTS[type.ordinal()][which]; 1625 } 1626 static Name internArgument(Name n) { 1627 assert(n.isParam()) : "not param: " + n; 1628 assert(n.index < INTERNED_ARGUMENT_LIMIT); 1629 if (n.constraint != null) return n; 1630 return argument(n.index, n.type); 1631 } 1632 static Name[] arguments(int extra, String types) { 1633 int length = types.length(); 1634 Name[] names = new Name[length + extra]; 1635 for (int i = 0; i < length; i++) 1636 names[i] = argument(i, types.charAt(i)); 1637 return names; 1638 } 1639 static Name[] arguments(int extra, char... types) { 1640 int length = types.length; 1641 Name[] names = new Name[length + extra]; 1642 for (int i = 0; i < length; i++) 1643 names[i] = argument(i, types[i]); 1644 return names; 1645 } 1646 static Name[] arguments(int extra, List<Class<?>> types) { 1647 int length = types.size(); 1648 Name[] names = new Name[length + extra]; 1649 for (int i = 0; i < length; i++) 1650 names[i] = argument(i, basicType(types.get(i))); 1651 return names; 1652 } 1653 static Name[] arguments(int extra, Class<?>... types) { 1654 int length = types.length; 1655 Name[] names = new Name[length + extra]; 1656 for (int i = 0; i < length; i++) 1657 names[i] = argument(i, basicType(types[i])); 1658 return names; 1659 } 1660 static Name[] arguments(int extra, MethodType types) { 1661 int length = types.parameterCount(); 1662 Name[] names = new Name[length + extra]; 1663 for (int i = 0; i < length; i++) 1664 names[i] = argument(i, basicType(types.parameterType(i))); 1665 return names; 1666 } 1667 static final int INTERNED_ARGUMENT_LIMIT = 10; 1668 private static final Name[][] INTERNED_ARGUMENTS 1669 = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT]; 1670 static { 1671 for (BasicType type : BasicType.ARG_TYPES) { 1672 int ord = type.ordinal(); 1673 for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) { 1674 INTERNED_ARGUMENTS[ord][i] = new Name(i, type); 1675 } 1676 } 1677 } 1678 1679 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 1680 1681 static LambdaForm identityForm(BasicType type) { 1682 return LF_identityForm[type.ordinal()]; 1683 } 1684 static LambdaForm zeroForm(BasicType type) { 1685 return LF_zeroForm[type.ordinal()]; 1686 } 1687 static NamedFunction identity(BasicType type) { 1688 return NF_identity[type.ordinal()]; 1689 } 1690 static NamedFunction constantZero(BasicType type) { 1691 return NF_zero[type.ordinal()]; 1692 } 1693 private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT]; 1694 private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT]; 1695 private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT]; 1696 private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT]; 1697 private static void createIdentityForms() { 1698 for (BasicType type : BasicType.ALL_TYPES) { 1699 int ord = type.ordinal(); 1700 char btChar = type.basicTypeChar(); 1701 boolean isVoid = (type == V_TYPE); 1702 Class<?> btClass = type.btClass; 1703 MethodType zeType = MethodType.methodType(btClass); 1704 MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass); 1705 1706 // Look up some symbolic names. It might not be necessary to have these, 1707 // but if we need to emit direct references to bytecodes, it helps. 1708 // Zero is built from a call to an identity function with a constant zero input. 1709 MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic); 1710 MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic); 1711 try { 1712 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class); 1713 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class); 1714 } catch (IllegalAccessException|NoSuchMethodException ex) { 1715 throw newInternalError(ex); 1716 } 1717 1718 NamedFunction idFun = new NamedFunction(idMem); 1719 LambdaForm idForm; 1720 if (isVoid) { 1721 Name[] idNames = new Name[] { argument(0, L_TYPE) }; 1722 idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT); 1723 } else { 1724 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) }; 1725 idForm = new LambdaForm(idMem.getName(), 2, idNames, 1); 1726 } 1727 LF_identityForm[ord] = idForm; 1728 NF_identity[ord] = idFun; 1729 1730 NamedFunction zeFun = new NamedFunction(zeMem); 1731 LambdaForm zeForm; 1732 if (isVoid) { 1733 zeForm = idForm; 1734 } else { 1735 Object zeValue = Wrapper.forBasicType(btChar).zero(); 1736 Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) }; 1737 zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1); 1738 } 1739 LF_zeroForm[ord] = zeForm; 1740 NF_zero[ord] = zeFun; 1741 1742 assert(idFun.isIdentity()); 1743 assert(zeFun.isConstantZero()); 1744 assert(new Name(zeFun).isConstantZero()); 1745 } 1746 1747 // Do this in a separate pass, so that SimpleMethodHandle.make can see the tables. 1748 for (BasicType type : BasicType.ALL_TYPES) { 1749 int ord = type.ordinal(); 1750 NamedFunction idFun = NF_identity[ord]; 1751 LambdaForm idForm = LF_identityForm[ord]; 1752 MemberName idMem = idFun.member; 1753 idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm); 1754 1755 NamedFunction zeFun = NF_zero[ord]; 1756 LambdaForm zeForm = LF_zeroForm[ord]; 1757 MemberName zeMem = zeFun.member; 1758 zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm); 1759 1760 assert(idFun.isIdentity()); 1761 assert(zeFun.isConstantZero()); 1762 assert(new Name(zeFun).isConstantZero()); 1763 } 1764 } 1765 1766 // Avoid appealing to ValueConversions at bootstrap time: 1767 private static int identity_I(int x) { return x; } 1768 private static long identity_J(long x) { return x; } 1769 private static float identity_F(float x) { return x; } 1770 private static double identity_D(double x) { return x; } 1771 private static Object identity_L(Object x) { return x; } 1772 private static void identity_V() { return; } // same as zeroV, but that's OK 1773 private static int zero_I() { return 0; } 1774 private static long zero_J() { return 0; } 1775 private static float zero_F() { return 0; } 1776 private static double zero_D() { return 0; } 1777 private static Object zero_L() { return null; } 1778 private static void zero_V() { return; } 1779 1780 /** 1781 * Internal marker for byte-compiled LambdaForms. 1782 */ 1783 /*non-public*/ 1784 @Target(ElementType.METHOD) 1785 @Retention(RetentionPolicy.RUNTIME) 1786 @interface Compiled { 1787 } 1788 1789 /** 1790 * Internal marker for LambdaForm interpreter frames. 1791 */ 1792 /*non-public*/ 1793 @Target(ElementType.METHOD) 1794 @Retention(RetentionPolicy.RUNTIME) 1795 @interface Hidden { 1796 } 1797 1798 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS; 1799 static { 1800 if (debugEnabled()) 1801 DEBUG_NAME_COUNTERS = new HashMap<>(); 1802 else 1803 DEBUG_NAME_COUNTERS = null; 1804 } 1805 1806 // Put this last, so that previous static inits can run before. 1807 static { 1808 createIdentityForms(); 1809 if (USE_PREDEFINED_INTERPRET_METHODS) 1810 computeInitialPreparedForms(); 1811 NamedFunction.initializeInvokers(); 1812 } 1813 1814 // The following hack is necessary in order to suppress TRACE_INTERPRETER 1815 // during execution of the static initializes of this class. 1816 // Turning on TRACE_INTERPRETER too early will cause 1817 // stack overflows and other misbehavior during attempts to trace events 1818 // that occur during LambdaForm.<clinit>. 1819 // Therefore, do not move this line higher in this file, and do not remove. 1820 private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER; 1821 }