1 /*
  2  * Copyright (c) 1997, 2024, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "asm/macroAssembler.hpp"
 27 #include "classfile/vmClasses.hpp"
 28 #include "compiler/disassembler.hpp"
 29 #include "classfile/javaClasses.inline.hpp"
 30 #include "interpreter/interpreter.hpp"
 31 #include "interpreter/interpreterRuntime.hpp"
 32 #include "jvm.h"
 33 #include "logging/log.hpp"
 34 #include "logging/logStream.hpp"
 35 #include "memory/allocation.inline.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "prims/jvmtiExport.hpp"
 38 #include "prims/methodHandles.hpp"
 39 #include "runtime/flags/flagSetting.hpp"
 40 #include "runtime/frame.inline.hpp"
 41 #include "runtime/stubRoutines.hpp"
 42 #include "utilities/formatBuffer.hpp"
 43 #include "utilities/preserveException.hpp"
 44 
 45 #define __ Disassembler::hook<MacroAssembler>(__FILE__, __LINE__, _masm)->
 46 
 47 #ifdef PRODUCT
 48 #define BLOCK_COMMENT(str) /* nothing */
 49 #define STOP(error) stop(error)
 50 #else
 51 #define BLOCK_COMMENT(str) __ block_comment(str)
 52 #define STOP(error) block_comment(error); __ stop(error)
 53 #endif
 54 
 55 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 56 
 57 void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
 58   if (VerifyMethodHandles)
 59     verify_klass(_masm, klass_reg, VM_CLASS_ID(java_lang_Class),
 60                  "MH argument is a Class");
 61   __ movptr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset()));
 62 }
 63 
 64 #ifdef ASSERT
 65 static int check_nonzero(const char* xname, int x) {
 66   assert(x != 0, "%s should be nonzero", xname);
 67   return x;
 68 }
 69 #define NONZERO(x) check_nonzero(#x, x)
 70 #else //ASSERT
 71 #define NONZERO(x) (x)
 72 #endif //ASSERT
 73 
 74 #ifdef ASSERT
 75 void MethodHandles::verify_klass(MacroAssembler* _masm,
 76                                  Register obj, vmClassID klass_id,
 77                                  const char* error_message) {
 78   InstanceKlass** klass_addr = vmClasses::klass_addr_at(klass_id);
 79   Klass* klass = vmClasses::klass_at(klass_id);
 80   Register temp = rdi;
 81   Label L_ok, L_bad;
 82   BLOCK_COMMENT("verify_klass {");
 83   __ verify_oop(obj);
 84   __ testptr(obj, obj);
 85   __ jcc(Assembler::zero, L_bad);
 86 #define PUSH { __ push(temp); LP64_ONLY(  __ push(rscratch1); )               }
 87 #define POP  {                LP64_ONLY(  __ pop(rscratch1);  ) __ pop(temp); }
 88   PUSH;
 89   __ load_klass(temp, obj, rscratch1);
 90   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 91   __ jcc(Assembler::equal, L_ok);
 92   intptr_t super_check_offset = klass->super_check_offset();
 93   __ movptr(temp, Address(temp, super_check_offset));
 94   __ cmpptr(temp, ExternalAddress((address) klass_addr), rscratch1);
 95   __ jcc(Assembler::equal, L_ok);
 96   POP;
 97   __ bind(L_bad);
 98   __ STOP(error_message);
 99   __ BIND(L_ok);
100   POP;
101   BLOCK_COMMENT("} verify_klass");
102 #undef POP
103 #undef PUSH
104 }
105 
106 void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) {
107   Label L;
108   BLOCK_COMMENT("verify_ref_kind {");
109   __ movl(temp, Address(member_reg, NONZERO(java_lang_invoke_MemberName::flags_offset())));
110   __ shrl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT);
111   __ andl(temp, java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK);
112   __ cmpl(temp, ref_kind);
113   __ jcc(Assembler::equal, L);
114   { //char* buf = NEW_C_HEAP_ARRAY(char, 100, mtInternal);
115     //jio_snprintf(buf, 100, "verify_ref_kind expected %x", ref_kind);
116     const char* buf = "verify_ref_kind"; // avoid allocating new strings
117     if (ref_kind == JVM_REF_invokeVirtual ||
118         ref_kind == JVM_REF_invokeSpecial) {
119       // could do this for all ref_kinds, but would explode assembly code size
120       trace_method_handle(_masm, buf);
121     }
122     __ STOP(buf);
123   }
124   BLOCK_COMMENT("} verify_ref_kind");
125   __ bind(L);
126 }
127 
128 #endif //ASSERT
129 
130 void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
131                                             bool for_compiler_entry) {
132   assert(method == rbx, "interpreter calling convention");
133 
134    Label L_no_such_method;
135    __ testptr(rbx, rbx);
136    __ jcc(Assembler::zero, L_no_such_method);
137 
138   __ verify_method_ptr(method);
139 
140   if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
141     Label run_compiled_code;
142     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
143     // compiled code in threads for which the event is enabled.  Check here for
144     // interp_only_mode if these events CAN be enabled.
145 #ifdef _LP64
146     Register rthread = r15_thread;
147 #else
148     Register rthread = temp;
149     __ get_thread(rthread);
150 #endif
151     // interp_only is an int, on little endian it is sufficient to test the byte only
152     // Is a cmpl faster?
153     __ cmpb(Address(rthread, JavaThread::interp_only_mode_offset()), 0);
154     __ jccb(Assembler::zero, run_compiled_code);
155     __ jmp(Address(method, Method::interpreter_entry_offset()));
156     __ BIND(run_compiled_code);
157   }
158 
159   const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_offset() :
160                                                      Method::from_interpreted_offset();
161   __ jmp(Address(method, entry_offset));
162 
163   __ bind(L_no_such_method);
164   __ jump(RuntimeAddress(SharedRuntime::throw_AbstractMethodError_entry()));
165 }
166 
167 void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
168                                         Register recv, Register method_temp,
169                                         Register temp2,
170                                         bool for_compiler_entry) {
171   BLOCK_COMMENT("jump_to_lambda_form {");
172   // This is the initial entry point of a lazy method handle.
173   // After type checking, it picks up the invoker from the LambdaForm.
174   assert_different_registers(recv, method_temp, temp2);
175   assert(recv != noreg, "required register");
176   assert(method_temp == rbx, "required register for loading method");
177 
178   // Load the invoker, as MH -> MH.form -> LF.vmentry
179   __ verify_oop(recv);
180   __ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset())), temp2);
181   __ verify_oop(method_temp);
182   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset())), temp2);
183   __ verify_oop(method_temp);
184   __ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset())), temp2);
185   __ verify_oop(method_temp);
186   __ access_load_at(T_ADDRESS, IN_HEAP, method_temp,
187                     Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset())),
188                     noreg, noreg);
189 
190   if (VerifyMethodHandles && !for_compiler_entry) {
191     // make sure recv is already on stack
192     __ movptr(temp2, Address(method_temp, Method::const_offset()));
193     __ load_sized_value(temp2,
194                         Address(temp2, ConstMethod::size_of_parameters_offset()),
195                         sizeof(u2), /*is_signed*/ false);
196     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
197     Label L;
198     __ cmpoop(recv, __ argument_address(temp2, -1));
199     __ jcc(Assembler::equal, L);
200     __ movptr(rax, __ argument_address(temp2, -1));
201     __ STOP("receiver not on stack");
202     __ BIND(L);
203   }
204 
205   jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry);
206   BLOCK_COMMENT("} jump_to_lambda_form");
207 }
208 
209 void MethodHandles::jump_to_native_invoker(MacroAssembler* _masm, Register nep_reg, Register temp_target) {
210   BLOCK_COMMENT("jump_to_native_invoker {");
211   assert_different_registers(nep_reg, temp_target);
212   assert(nep_reg != noreg, "required register");
213 
214   // Load the invoker, as NEP -> .invoker
215   __ verify_oop(nep_reg);
216   __ access_load_at(T_ADDRESS, IN_HEAP, temp_target,
217                     Address(nep_reg, NONZERO(jdk_internal_foreign_abi_NativeEntryPoint::downcall_stub_address_offset_in_bytes())),
218                     noreg, noreg);
219 
220   __ jmp(temp_target);
221   BLOCK_COMMENT("} jump_to_native_invoker");
222 }
223 
224 
225 // Code generation
226 address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
227                                                                 vmIntrinsics::ID iid) {
228   const bool not_for_compiler_entry = false;  // this is the interpreter entry
229   assert(is_signature_polymorphic(iid), "expected invoke iid");
230   if (iid == vmIntrinsics::_invokeGeneric ||
231       iid == vmIntrinsics::_compiledLambdaForm) {
232     // Perhaps surprisingly, the symbolic references visible to Java are not directly used.
233     // They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
234     // They all allow an appendix argument.
235     __ hlt();           // empty stubs make SG sick
236     return nullptr;
237   }
238 
239   // No need in interpreter entry for linkToNative for now.
240   // Interpreter calls compiled entry through i2c.
241   if (iid == vmIntrinsics::_linkToNative) {
242     __ hlt();
243     return nullptr;
244   }
245 
246   // rsi/r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
247   // rbx: Method*
248   // rdx: argument locator (parameter slot count, added to rsp)
249   // rcx: used as temp to hold mh or receiver
250   // rax, rdi: garbage temps, blown away
251   Register rdx_argp   = rdx;   // argument list ptr, live on error paths
252   Register rax_temp   = rax;
253   Register rcx_mh     = rcx;   // MH receiver; dies quickly and is recycled
254   Register rbx_method = rbx;   // eventual target of this invocation
255 
256   // here's where control starts out:
257   __ align(CodeEntryAlignment);
258   address entry_point = __ pc();
259 
260   if (VerifyMethodHandles) {
261     assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
262 
263     Label L;
264     BLOCK_COMMENT("verify_intrinsic_id {");
265     __ cmpw(Address(rbx_method, Method::intrinsic_id_offset()), (int) iid);
266     __ jcc(Assembler::equal, L);
267     if (iid == vmIntrinsics::_linkToVirtual ||
268         iid == vmIntrinsics::_linkToSpecial) {
269       // could do this for all kinds, but would explode assembly code size
270       trace_method_handle(_masm, "bad Method*::intrinsic_id");
271     }
272     __ STOP("bad Method*::intrinsic_id");
273     __ bind(L);
274     BLOCK_COMMENT("} verify_intrinsic_id");
275   }
276 
277   // First task:  Find out how big the argument list is.
278   Address rdx_first_arg_addr;
279   int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
280   assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
281   if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
282     __ movptr(rdx_argp, Address(rbx_method, Method::const_offset()));
283     __ load_sized_value(rdx_argp,
284                         Address(rdx_argp, ConstMethod::size_of_parameters_offset()),
285                         sizeof(u2), /*is_signed*/ false);
286     // assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
287     rdx_first_arg_addr = __ argument_address(rdx_argp, -1);
288   } else {
289     DEBUG_ONLY(rdx_argp = noreg);
290   }
291 
292   if (!is_signature_polymorphic_static(iid)) {
293     __ movptr(rcx_mh, rdx_first_arg_addr);
294     DEBUG_ONLY(rdx_argp = noreg);
295   }
296 
297   // rdx_first_arg_addr is live!
298 
299   trace_method_handle_interpreter_entry(_masm, iid);
300 
301   if (iid == vmIntrinsics::_invokeBasic) {
302     generate_method_handle_dispatch(_masm, iid, rcx_mh, noreg, not_for_compiler_entry);
303 
304   } else {
305     // Adjust argument list by popping the trailing MemberName argument.
306     Register rcx_recv = noreg;
307     if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
308       // Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
309       __ movptr(rcx_recv = rcx, rdx_first_arg_addr);
310     }
311     DEBUG_ONLY(rdx_argp = noreg);
312     Register rbx_member = rbx_method;  // MemberName ptr; incoming method ptr is dead now
313     __ pop(rax_temp);           // return address
314     __ pop(rbx_member);         // extract last argument
315     __ push(rax_temp);          // re-push return address
316     generate_method_handle_dispatch(_masm, iid, rcx_recv, rbx_member, not_for_compiler_entry);
317   }
318 
319   return entry_point;
320 }
321 
322 void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
323                                                     vmIntrinsics::ID iid,
324                                                     Register receiver_reg,
325                                                     Register member_reg,
326                                                     bool for_compiler_entry) {
327   assert(is_signature_polymorphic(iid), "expected invoke iid");
328   Register rbx_method = rbx;   // eventual target of this invocation
329   // temps used in this code are not used in *either* compiled or interpreted calling sequences
330 #ifdef _LP64
331   Register temp1 = rscratch1;
332   Register temp2 = rscratch2;
333   Register temp3 = rax;
334   if (for_compiler_entry) {
335     assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic || iid == vmIntrinsics::_linkToNative ? noreg : j_rarg0), "only valid assignment");
336     assert_different_registers(temp1,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
337     assert_different_registers(temp2,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
338     assert_different_registers(temp3,        j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5);
339   }
340 #else
341   Register temp1 = (for_compiler_entry ? rsi : rdx);
342   Register temp2 = rdi;
343   Register temp3 = rax;
344   if (for_compiler_entry) {
345     assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic || iid == vmIntrinsics::_linkToNative ? noreg : rcx), "only valid assignment");
346     assert_different_registers(temp1,        rcx, rdx);
347     assert_different_registers(temp2,        rcx, rdx);
348     assert_different_registers(temp3,        rcx, rdx);
349   }
350 #endif
351   else {
352     assert_different_registers(temp1, temp2, temp3, saved_last_sp_register());  // don't trash lastSP
353   }
354   assert_different_registers(temp1, temp2, temp3, receiver_reg);
355   assert_different_registers(temp1, temp2, temp3, member_reg);
356 
357   if (iid == vmIntrinsics::_invokeBasic) {
358     // indirect through MH.form.vmentry.vmtarget
359     jump_to_lambda_form(_masm, receiver_reg, rbx_method, temp1, for_compiler_entry);
360   } else if (iid == vmIntrinsics::_linkToNative) {
361     assert(for_compiler_entry, "only compiler entry is supported");
362     jump_to_native_invoker(_masm, member_reg, temp1);
363   } else {
364     // The method is a member invoker used by direct method handles.
365     if (VerifyMethodHandles) {
366       // make sure the trailing argument really is a MemberName (caller responsibility)
367       verify_klass(_masm, member_reg, VM_CLASS_ID(java_lang_invoke_MemberName),
368                    "MemberName required for invokeVirtual etc.");
369     }
370 
371     Address member_clazz(    member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset()));
372     Address member_vmindex(  member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset()));
373     Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset()));
374     Address vmtarget_method( rbx_method, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset()));
375 
376     Register temp1_recv_klass = temp1;
377     if (iid != vmIntrinsics::_linkToStatic) {
378       __ verify_oop(receiver_reg);
379       if (iid == vmIntrinsics::_linkToSpecial) {
380         // Don't actually load the klass; just null-check the receiver.
381         __ null_check(receiver_reg);
382       } else {
383         // load receiver klass itself
384         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
385         __ verify_klass_ptr(temp1_recv_klass);
386       }
387       BLOCK_COMMENT("check_receiver {");
388       // The receiver for the MemberName must be in receiver_reg.
389       // Check the receiver against the MemberName.clazz
390       if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
391         // Did not load it above...
392         __ load_klass(temp1_recv_klass, receiver_reg, temp2);
393         __ verify_klass_ptr(temp1_recv_klass);
394       }
395       if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
396         Label L_ok;
397         Register temp2_defc = temp2;
398         __ load_heap_oop(temp2_defc, member_clazz, temp3);
399         load_klass_from_Class(_masm, temp2_defc);
400         __ verify_klass_ptr(temp2_defc);
401         __ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
402         // If we get here, the type check failed!
403         __ STOP("receiver class disagrees with MemberName.clazz");
404         __ bind(L_ok);
405       }
406       BLOCK_COMMENT("} check_receiver");
407     }
408     if (iid == vmIntrinsics::_linkToSpecial ||
409         iid == vmIntrinsics::_linkToStatic) {
410       DEBUG_ONLY(temp1_recv_klass = noreg);  // these guys didn't load the recv_klass
411     }
412 
413     // Live registers at this point:
414     //  member_reg - MemberName that was the trailing argument
415     //  temp1_recv_klass - klass of stacked receiver, if needed
416     //  rsi/r13 - interpreter linkage (if interpreted)
417     //  rcx, rdx, rsi, rdi, r8 - compiler arguments (if compiled)
418 
419     Label L_incompatible_class_change_error;
420     switch (iid) {
421     case vmIntrinsics::_linkToSpecial:
422       if (VerifyMethodHandles) {
423         verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
424       }
425       __ load_heap_oop(rbx_method, member_vmtarget);
426       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg, noreg);
427       break;
428 
429     case vmIntrinsics::_linkToStatic:
430       if (VerifyMethodHandles) {
431         verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
432       }
433       __ load_heap_oop(rbx_method, member_vmtarget);
434       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_method, vmtarget_method, noreg, noreg);
435       break;
436 
437     case vmIntrinsics::_linkToVirtual:
438     {
439       // same as TemplateTable::invokevirtual,
440       // minus the CP setup and profiling:
441 
442       if (VerifyMethodHandles) {
443         verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
444       }
445 
446       // pick out the vtable index from the MemberName, and then we can discard it:
447       Register temp2_index = temp2;
448       __ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg, noreg);
449 
450       if (VerifyMethodHandles) {
451         Label L_index_ok;
452         __ cmpl(temp2_index, 0);
453         __ jcc(Assembler::greaterEqual, L_index_ok);
454         __ STOP("no virtual index");
455         __ BIND(L_index_ok);
456       }
457 
458       // Note:  The verifier invariants allow us to ignore MemberName.clazz and vmtarget
459       // at this point.  And VerifyMethodHandles has already checked clazz, if needed.
460 
461       // get target Method* & entry point
462       __ lookup_virtual_method(temp1_recv_klass, temp2_index, rbx_method);
463       break;
464     }
465 
466     case vmIntrinsics::_linkToInterface:
467     {
468       // same as TemplateTable::invokeinterface
469       // (minus the CP setup and profiling, with different argument motion)
470       if (VerifyMethodHandles) {
471         verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
472       }
473 
474       Register temp3_intf = temp3;
475       __ load_heap_oop(temp3_intf, member_clazz);
476       load_klass_from_Class(_masm, temp3_intf);
477       __ verify_klass_ptr(temp3_intf);
478 
479       Register rbx_index = rbx_method;
480       __ access_load_at(T_ADDRESS, IN_HEAP, rbx_index, member_vmindex, noreg, noreg);
481       if (VerifyMethodHandles) {
482         Label L;
483         __ cmpl(rbx_index, 0);
484         __ jcc(Assembler::greaterEqual, L);
485         __ STOP("invalid vtable index for MH.invokeInterface");
486         __ bind(L);
487       }
488 
489       // given intf, index, and recv klass, dispatch to the implementation method
490       __ lookup_interface_method(temp1_recv_klass, temp3_intf,
491                                  // note: next two args must be the same:
492                                  rbx_index, rbx_method,
493                                  temp2,
494                                  L_incompatible_class_change_error);
495       break;
496     }
497 
498     default:
499       fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
500       break;
501     }
502 
503     // Live at this point:
504     //   rbx_method
505     //   rsi/r13 (if interpreted)
506 
507     // After figuring out which concrete method to call, jump into it.
508     // Note that this works in the interpreter with no data motion.
509     // But the compiled version will require that rcx_recv be shifted out.
510     __ verify_method_ptr(rbx_method);
511     jump_from_method_handle(_masm, rbx_method, temp1, for_compiler_entry);
512 
513     if (iid == vmIntrinsics::_linkToInterface) {
514       __ bind(L_incompatible_class_change_error);
515       __ jump(RuntimeAddress(SharedRuntime::throw_IncompatibleClassChangeError_entry()));
516     }
517   }
518 }
519 
520 #ifndef PRODUCT
521 void trace_method_handle_stub(const char* adaptername,
522                               oopDesc* mh,
523                               intptr_t* saved_regs,
524                               intptr_t* entry_sp) {
525   // called as a leaf from native code: do not block the JVM!
526   bool has_mh = (strstr(adaptername, "/static") == nullptr &&
527                  strstr(adaptername, "linkTo") == nullptr);    // static linkers don't have MH
528   const char* mh_reg_name = has_mh ? "rcx_mh" : "rcx";
529   log_info(methodhandles)("MH %s %s=" PTR_FORMAT " sp=" PTR_FORMAT, adaptername, mh_reg_name, p2i(mh), p2i(entry_sp));
530 
531   LogTarget(Trace, methodhandles) lt;
532   if (lt.is_enabled()) {
533     ResourceMark rm;
534     LogStream ls(lt);
535     ls.print_cr("Registers:");
536     const int saved_regs_count = Register::number_of_registers;
537     for (int i = 0; i < saved_regs_count; i++) {
538       Register r = as_Register(i);
539       // The registers are stored in reverse order on the stack (by pusha).
540 #ifdef AMD64
541       int num_regs = UseAPX ? 32 : 16;
542       assert(Register::available_gp_registers() == num_regs, "sanity");
543       if (r == rsp) {
544         // rsp is actually not stored by pusha(), compute the old rsp from saved_regs (rsp after pusha): saved_regs + 16 = old rsp
545         ls.print("%3s=" PTR_FORMAT, r->name(), (intptr_t)(&saved_regs[num_regs]));
546       } else {
547         ls.print("%3s=" PTR_FORMAT, r->name(), saved_regs[((saved_regs_count - 1) - i)]);
548       }
549 #else
550       ls.print("%3s=" PTR_FORMAT, r->name(), saved_regs[((saved_regs_count - 1) - i)]);
551 #endif
552       if ((i + 1) % 4 == 0) {
553         ls.cr();
554       } else {
555         ls.print(", ");
556       }
557     }
558     ls.cr();
559 
560     // Note: We want to allow trace_method_handle from any call site.
561     // While trace_method_handle creates a frame, it may be entered
562     // without a PC on the stack top (e.g. not just after a call).
563     // Walking that frame could lead to failures due to that invalid PC.
564     // => carefully detect that frame when doing the stack walking
565 
566     {
567       // dumping last frame with frame::describe
568 
569       JavaThread* p = JavaThread::active();
570 
571       // may not be needed by safer and unexpensive here
572       PreserveExceptionMark pem(Thread::current());
573       FrameValues values;
574 
575       frame cur_frame = os::current_frame();
576 
577       if (cur_frame.fp() != nullptr) { // not walkable
578 
579         // Robust search of trace_calling_frame (independent of inlining).
580         // Assumes saved_regs comes from a pusha in the trace_calling_frame.
581         //
582         // We have to start the search from cur_frame, because trace_calling_frame may be it.
583         // It is guaranteed that trace_calling_frame is different from the top frame.
584         // But os::current_frame() does NOT return the top frame: it returns the next frame under it (caller's frame).
585         // (Due to inlining and tail call optimizations, caller's frame doesn't necessarily correspond to the immediate
586         // caller in the source code.)
587         assert(cur_frame.sp() < saved_regs, "registers not saved on stack ?");
588         frame trace_calling_frame = cur_frame;
589         while (trace_calling_frame.fp() < saved_regs) {
590           assert(trace_calling_frame.cb() == nullptr, "not a C frame");
591           trace_calling_frame = os::get_sender_for_C_frame(&trace_calling_frame);
592         }
593         assert(trace_calling_frame.sp() < saved_regs, "wrong frame");
594 
595         // safely create a frame and call frame::describe
596         intptr_t *dump_sp = trace_calling_frame.sender_sp();
597         intptr_t *dump_fp = trace_calling_frame.link();
598 
599         if (has_mh) {
600           // The previous definition of walkable may have to be refined
601           // if new call sites cause the next frame constructor to start
602           // failing. Alternatively, frame constructors could be
603           // modified to support the current or future non walkable
604           // frames (but this is more intrusive and is not considered as
605           // part of this RFE, which will instead use a simpler output).
606           frame dump_frame = frame(dump_sp, dump_fp);
607           dump_frame.describe(values, 1);
608         } else {
609           // Stack may not be walkable (invalid PC above FP):
610           // Add descriptions without building a Java frame to avoid issues
611           values.describe(-1, dump_fp, "fp for #1 <not parsed, cannot trust pc>");
612           values.describe(-1, dump_sp, "sp for #1");
613         }
614       }
615       values.describe(-1, entry_sp, "raw top of stack");
616 
617       ls.print_cr("Stack layout:");
618       values.print_on(p, &ls);
619     }
620     if (has_mh && oopDesc::is_oop(mh)) {
621       mh->print_on(&ls);
622       if (java_lang_invoke_MethodHandle::is_instance(mh)) {
623         java_lang_invoke_MethodHandle::form(mh)->print_on(&ls);
624       }
625     }
626   }
627 }
628 
629 // The stub wraps the arguments in a struct on the stack to avoid
630 // dealing with the different calling conventions for passing 6
631 // arguments.
632 struct MethodHandleStubArguments {
633   const char* adaptername;
634   oopDesc* mh;
635   intptr_t* saved_regs;
636   intptr_t* entry_sp;
637 };
638 void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) {
639   trace_method_handle_stub(args->adaptername,
640                            args->mh,
641                            args->saved_regs,
642                            args->entry_sp);
643 }
644 
645 void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) {
646   if (!log_is_enabled(Info, methodhandles))  return;
647   BLOCK_COMMENT(err_msg("trace_method_handle %s {", adaptername));
648   __ enter();
649   __ andptr(rsp, -16); // align stack if needed for FPU state
650   __ pusha();
651   __ mov(rbx, rsp); // for retrieving saved_regs
652   // Note: saved_regs must be in the entered frame for the
653   // robust stack walking implemented in trace_method_handle_stub.
654 
655   // save FP result, valid at some call sites (adapter_opt_return_float, ...)
656   __ decrement(rsp, 2 * wordSize);
657 #ifdef _LP64
658   __ movdbl(Address(rsp, 0), xmm0);
659 #else
660   if  (UseSSE >= 2) {
661     __ movdbl(Address(rsp, 0), xmm0);
662   } else if (UseSSE == 1) {
663     __ movflt(Address(rsp, 0), xmm0);
664   } else {
665     __ fst_d(Address(rsp, 0));
666   }
667 #endif // LP64
668 
669   // Incoming state:
670   // rcx: method handle
671   //
672   // To avoid calling convention issues, build a record on the stack
673   // and pass the pointer to that instead.
674   __ push(rbp);               // entry_sp (with extra align space)
675   __ push(rbx);               // pusha saved_regs
676   __ push(rcx);               // mh
677   __ push(rcx);               // slot for adaptername
678   __ movptr(Address(rsp, 0), (intptr_t) adaptername, rscratch1);
679   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, trace_method_handle_stub_wrapper), rsp);
680   __ increment(rsp, sizeof(MethodHandleStubArguments));
681 
682 #ifdef _LP64
683   __ movdbl(xmm0, Address(rsp, 0));
684 #else
685   if  (UseSSE >= 2) {
686     __ movdbl(xmm0, Address(rsp, 0));
687   } else if (UseSSE == 1) {
688     __ movflt(xmm0, Address(rsp, 0));
689   } else {
690     __ fld_d(Address(rsp, 0));
691   }
692 #endif // LP64
693   __ increment(rsp, 2 * wordSize);
694 
695   __ popa();
696   __ leave();
697   BLOCK_COMMENT("} trace_method_handle");
698 }
699 #endif //PRODUCT