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