1 /*
  2  * Copyright (c) 1997, 2025, 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 #ifndef SHARE_RUNTIME_SHAREDRUNTIME_HPP
 26 #define SHARE_RUNTIME_SHAREDRUNTIME_HPP
 27 
 28 #include "classfile/compactHashtable.hpp"
 29 #include "code/codeBlob.hpp"
 30 #include "code/vmreg.hpp"
 31 #include "interpreter/linkResolver.hpp"
 32 #include "memory/allStatic.hpp"
 33 #include "memory/metaspaceClosure.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "runtime/stubInfo.hpp"
 36 #include "utilities/macros.hpp"
 37 
 38 class AdapterHandlerEntry;
 39 class AdapterFingerPrint;
 40 class vframeStream;
 41 class MetaspaceClosure;
 42 
 43 // Runtime is the base class for various runtime interfaces
 44 // (InterpreterRuntime, CompilerRuntime, etc.). It provides
 45 // shared functionality such as exception forwarding (C++ to
 46 // Java exceptions), locking/unlocking mechanisms, statistical
 47 // information, etc.
 48 
 49 class SharedRuntime: AllStatic {
 50  private:
 51   // Declare shared stub fields
 52 #define SHARED_STUB_FIELD_DECLARE(name, type) \
 53   static type*       BLOB_FIELD_NAME(name);
 54   SHARED_STUBS_DO(SHARED_STUB_FIELD_DECLARE)
 55 #undef SHARED_STUB_FIELD_DECLARE
 56 
 57 #ifdef ASSERT
 58   static bool is_resolve_id(StubId id) {
 59     return (id == StubId::shared_wrong_method_id ||
 60             id == StubId::shared_wrong_method_abstract_id ||
 61             id == StubId::shared_ic_miss_id ||
 62             id == StubId::shared_resolve_opt_virtual_call_id ||
 63             id == StubId::shared_resolve_virtual_call_id ||
 64             id == StubId::shared_resolve_static_call_id);
 65   }
 66   static bool is_polling_page_id(StubId id) {
 67     return (id == StubId::shared_polling_page_vectors_safepoint_handler_id ||
 68             id == StubId::shared_polling_page_safepoint_handler_id ||
 69             id == StubId::shared_polling_page_return_handler_id);
 70   }
 71   static bool is_throw_id(StubId id) {
 72     return (id == StubId::shared_throw_AbstractMethodError_id ||
 73             id == StubId::shared_throw_IncompatibleClassChangeError_id ||
 74             id == StubId::shared_throw_NullPointerException_at_call_id ||
 75             id == StubId::shared_throw_StackOverflowError_id ||
 76             id == StubId::shared_throw_delayed_StackOverflowError_id);
 77   }
 78 #endif
 79 
 80   // cont_doYieldStub is not yet folded into the general model for
 81   // shared stub/blob handling. It is actually a specially generated
 82   // native wrapper for a specific native method, as also is it's
 83   // counterpart the continuation do_enter method.
 84   static nmethod*            _cont_doYield_stub;
 85 
 86 #ifndef PRODUCT
 87   // Counters
 88   static int64_t _nof_megamorphic_calls;         // total # of megamorphic calls (through vtable)
 89 #endif // !PRODUCT
 90 
 91  private:
 92   static SafepointBlob* generate_handler_blob(StubId id, address call_ptr);
 93   static RuntimeStub*   generate_resolve_blob(StubId id, address destination);
 94   static RuntimeStub*   generate_throw_exception(StubId id, address runtime_entry);
 95  public:
 96   static void generate_initial_stubs(void);
 97   static void generate_stubs(void);
 98 #if INCLUDE_JFR
 99   static void generate_jfr_stubs(void);
100   // For c2: c_rarg0 is junk, call to runtime to write a checkpoint.
101   // It returns a jobject handle to the event writer.
102   // The handle is dereferenced and the return value is the event writer oop.
103   static RuntimeStub* generate_jfr_write_checkpoint();
104   // For c2: call to runtime to return a buffer lease.
105   static RuntimeStub* generate_jfr_return_lease();
106 #endif
107   static void init_adapter_library();
108 
109   static const char *stub_name(StubId id) {
110     assert(StubInfo::is_shared(id), "not a shared stub %s", StubInfo::name(id));
111     return StubInfo::name(id);
112   }
113 
114   // max bytes for each dtrace string parameter
115   enum { max_dtrace_string_size = 256 };
116 
117   // The following arithmetic routines are used on platforms that do
118   // not have machine instructions to implement their functionality.
119   // Do not remove these.
120 
121   // long arithmetics
122   static jlong   lmul(jlong y, jlong x);
123   static jlong   ldiv(jlong y, jlong x);
124   static jlong   lrem(jlong y, jlong x);
125 
126   // float and double remainder
127   static jfloat  frem(jfloat  x, jfloat  y);
128   static jdouble drem(jdouble x, jdouble y);
129 
130 
131 #ifdef _WIN64
132   // Workaround for fmod issue in the Windows x64 CRT
133   static double fmod_winx64(double x, double y);
134 #endif
135 
136 #ifdef __SOFTFP__
137   static jfloat  fadd(jfloat x, jfloat y);
138   static jfloat  fsub(jfloat x, jfloat y);
139   static jfloat  fmul(jfloat x, jfloat y);
140   static jfloat  fdiv(jfloat x, jfloat y);
141 
142   static jdouble dadd(jdouble x, jdouble y);
143   static jdouble dsub(jdouble x, jdouble y);
144   static jdouble dmul(jdouble x, jdouble y);
145   static jdouble ddiv(jdouble x, jdouble y);
146 #endif // __SOFTFP__
147 
148   // float conversion (needs to set appropriate rounding mode)
149   static jint    f2i (jfloat  x);
150   static jlong   f2l (jfloat  x);
151   static jint    d2i (jdouble x);
152   static jlong   d2l (jdouble x);
153   static jfloat  d2f (jdouble x);
154   static jfloat  l2f (jlong   x);
155   static jdouble l2d (jlong   x);
156   static jfloat  i2f (jint    x);
157 
158 #ifdef __SOFTFP__
159   static jdouble i2d (jint    x);
160   static jdouble f2d (jfloat  x);
161 #endif // __SOFTFP__
162 
163   // double trigonometrics and transcendentals
164   static jdouble dsin(jdouble x);
165   static jdouble dcos(jdouble x);
166   static jdouble dtan(jdouble x);
167   static jdouble dlog(jdouble x);
168   static jdouble dlog10(jdouble x);
169   static jdouble dexp(jdouble x);
170   static jdouble dpow(jdouble x, jdouble y);
171 
172 #if defined(__SOFTFP__) || defined(E500V2)
173   static double dabs(double f);
174 #endif
175 
176 #if defined(__SOFTFP__)
177   static double dsqrt(double f);
178 #endif
179 
180   // Montgomery multiplication
181   static void montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
182                                   jint len, jlong inv, jint *m_ints);
183   static void montgomery_square(jint *a_ints, jint *n_ints,
184                                 jint len, jlong inv, jint *m_ints);
185 
186 #ifdef __SOFTFP__
187   // C++ compiler generates soft float instructions as well as passing
188   // float and double in registers.
189   static int  fcmpl(float x, float y);
190   static int  fcmpg(float x, float y);
191   static int  dcmpl(double x, double y);
192   static int  dcmpg(double x, double y);
193 
194   static int unordered_fcmplt(float x, float y);
195   static int unordered_dcmplt(double x, double y);
196   static int unordered_fcmple(float x, float y);
197   static int unordered_dcmple(double x, double y);
198   static int unordered_fcmpge(float x, float y);
199   static int unordered_dcmpge(double x, double y);
200   static int unordered_fcmpgt(float x, float y);
201   static int unordered_dcmpgt(double x, double y);
202 
203   static float  fneg(float f);
204   static double dneg(double f);
205 #endif
206 
207   // exception handling across interpreter/compiler boundaries
208   static address raw_exception_handler_for_return_address(JavaThread* current, address return_address);
209   static address exception_handler_for_return_address(JavaThread* current, address return_address);
210 
211   // exception handling and implicit exceptions
212   static address compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
213                                               bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred);
214   enum ImplicitExceptionKind {
215     IMPLICIT_NULL,
216     IMPLICIT_DIVIDE_BY_ZERO,
217     STACK_OVERFLOW
218   };
219   static void    throw_AbstractMethodError(JavaThread* current);
220   static void    throw_IncompatibleClassChangeError(JavaThread* current);
221   static void    throw_ArithmeticException(JavaThread* current);
222   static void    throw_NullPointerException(JavaThread* current);
223   static void    throw_NullPointerException_at_call(JavaThread* current);
224   static void    throw_StackOverflowError(JavaThread* current);
225   static void    throw_delayed_StackOverflowError(JavaThread* current);
226   static void    throw_StackOverflowError_common(JavaThread* current, bool delayed);
227   static address continuation_for_implicit_exception(JavaThread* current,
228                                                      address faulting_pc,
229                                                      ImplicitExceptionKind exception_kind);
230 
231   // Post-slow-path-allocation, pre-initializing-stores step for
232   // implementing e.g. ReduceInitialCardMarks
233   static void on_slowpath_allocation_exit(JavaThread* current);
234 
235   static void enable_stack_reserved_zone(JavaThread* current);
236   static frame look_for_reserved_stack_annotated_method(JavaThread* current, frame fr);
237 
238   // Shared stub locations
239   static address get_poll_stub(address pc);
240 
241   static address get_ic_miss_stub() {
242     assert(_ic_miss_blob!= nullptr, "oops");
243     return _ic_miss_blob->entry_point();
244   }
245 
246   static address get_handle_wrong_method_stub() {
247     assert(_wrong_method_blob!= nullptr, "oops");
248     return _wrong_method_blob->entry_point();
249   }
250 
251   static address get_handle_wrong_method_abstract_stub() {
252     assert(_wrong_method_abstract_blob!= nullptr, "oops");
253     return _wrong_method_abstract_blob->entry_point();
254   }
255 
256   static address get_resolve_opt_virtual_call_stub() {
257     assert(_resolve_opt_virtual_call_blob != nullptr, "oops");
258     return _resolve_opt_virtual_call_blob->entry_point();
259   }
260   static address get_resolve_virtual_call_stub() {
261     assert(_resolve_virtual_call_blob != nullptr, "oops");
262     return _resolve_virtual_call_blob->entry_point();
263   }
264   static address get_resolve_static_call_stub() {
265     assert(_resolve_static_call_blob != nullptr, "oops");
266     return _resolve_static_call_blob->entry_point();
267   }
268 
269   static SafepointBlob* polling_page_return_handler_blob()     { return _polling_page_return_handler_blob; }
270   static SafepointBlob* polling_page_safepoint_handler_blob()  { return _polling_page_safepoint_handler_blob; }
271   static SafepointBlob* polling_page_vectors_safepoint_handler_blob()  { return _polling_page_vectors_safepoint_handler_blob; }
272 
273   static nmethod* cont_doYield_stub() {
274     assert(_cont_doYield_stub != nullptr, "oops");
275     return _cont_doYield_stub;
276   }
277 
278   // Implicit exceptions
279   static address throw_AbstractMethodError_entry()          {
280     assert(_throw_AbstractMethodError_blob != nullptr, "");
281     return _throw_AbstractMethodError_blob->entry_point();
282   }
283   static address throw_IncompatibleClassChangeError_entry() {
284     assert(_throw_IncompatibleClassChangeError_blob != nullptr, "");
285     return  _throw_IncompatibleClassChangeError_blob->entry_point();
286   }
287   static address throw_NullPointerException_at_call_entry() {
288     assert(_throw_NullPointerException_at_call_blob != nullptr, "");
289     return  _throw_NullPointerException_at_call_blob->entry_point();
290   }
291   static address throw_StackOverflowError_entry()           {
292     assert(_throw_StackOverflowError_blob != nullptr, "");
293     return _throw_StackOverflowError_blob->entry_point();
294   }
295   static address throw_delayed_StackOverflowError_entry()   {
296     assert(_throw_delayed_StackOverflowError_blob != nullptr, "");
297     return _throw_delayed_StackOverflowError_blob->entry_point();
298   }
299 
300 #if INCLUDE_JFR
301   static address jfr_write_checkpoint() {
302     assert(_jfr_write_checkpoint_blob != nullptr, "");
303     return _jfr_write_checkpoint_blob->entry_point();
304   }
305   static address jfr_return_lease()     {
306     assert(_jfr_return_lease_blob != nullptr, "");
307     return _jfr_return_lease_blob->entry_point();
308   }
309 #endif
310 
311   // Counters
312 #ifndef PRODUCT
313   static address nof_megamorphic_calls_addr() { return (address)&_nof_megamorphic_calls; }
314 #endif // PRODUCT
315 
316   // Helper routine for full-speed JVMTI exception throwing support
317   static void throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception);
318   static void throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message = nullptr);
319 
320 #if INCLUDE_JVMTI
321   // Functions for JVMTI notifications
322   static void notify_jvmti_vthread_start(oopDesc* vt, jboolean hide, JavaThread* current);
323   static void notify_jvmti_vthread_end(oopDesc* vt, jboolean hide, JavaThread* current);
324   static void notify_jvmti_vthread_mount(oopDesc* vt, jboolean hide, JavaThread* current);
325   static void notify_jvmti_vthread_unmount(oopDesc* vt, jboolean hide, JavaThread* current);
326 #endif
327 
328   // RedefineClasses() tracing support for obsolete method entry
329   static int rc_trace_method_entry(JavaThread* thread, Method* m);
330 
331   // To be used as the entry point for unresolved native methods.
332   static address native_method_throw_unsatisfied_link_error_entry();
333 
334   static void register_finalizer(JavaThread* thread, oopDesc* obj);
335 
336   // dtrace notifications
337   static int dtrace_object_alloc(oopDesc* o);
338   static int dtrace_object_alloc(JavaThread* thread, oopDesc* o);
339   static int dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size);
340   static int dtrace_method_entry(JavaThread* thread, Method* m);
341   static int dtrace_method_exit(JavaThread* thread, Method* m);
342 
343   // Utility method for retrieving the Java thread id, returns 0 if the
344   // thread is not a well formed Java thread.
345   static jlong get_java_tid(JavaThread* thread);
346 
347 
348   // used by native wrappers to re-enable yellow if overflow happened in native code
349   static void reguard_yellow_pages();
350 
351   // Fill in the "X cannot be cast to a Y" message for ClassCastException
352   //
353   // @param thr the current thread
354   // @param caster_klass the class of the object we are casting
355   // @return the dynamically allocated exception message (must be freed
356   // by the caller using a resource mark)
357   //
358   // BCP must refer to the current 'checkcast' opcode for the frame
359   // on top of the stack.
360   // The caller (or one of its callers) must use a ResourceMark
361   // in order to correctly free the result.
362   //
363   static char* generate_class_cast_message(JavaThread* thr, Klass* caster_klass);
364 
365   // Fill in the "X cannot be cast to a Y" message for ClassCastException
366   //
367   // @param caster_klass the class of the object we are casting
368   // @param target_klass the target klass attempt
369   // @return the dynamically allocated exception message (must be freed
370   // by the caller using a resource mark)
371   //
372   // This version does not require access the frame, so it can be called
373   // from interpreted code
374   // The caller (or one of it's callers) must use a ResourceMark
375   // in order to correctly free the result.
376   //
377   static char* generate_class_cast_message(Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name = nullptr);
378 
379   // Resolves a call site- may patch in the destination of the call into the
380   // compiled code.
381   static methodHandle resolve_helper(bool is_virtual, bool is_optimized, TRAPS);
382 
383  private:
384   // deopt blob
385   static void generate_deopt_blob(void);
386 
387   static bool handle_ic_miss_helper_internal(Handle receiver, nmethod* caller_nm, const frame& caller_frame,
388                                              methodHandle callee_method, Bytecodes::Code bc, CallInfo& call_info,
389                                              bool& needs_ic_stub_refill, TRAPS);
390 
391  public:
392   static DeoptimizationBlob* deopt_blob(void)      { return _deopt_blob; }
393 
394   // Resets a call-site in compiled code so it will get resolved again.
395   static methodHandle reresolve_call_site(TRAPS);
396 
397   // In the code prolog, if the klass comparison fails, the inline cache
398   // misses and the call site is patched to megamorphic
399   static methodHandle handle_ic_miss_helper(TRAPS);
400 
401   // Find the method that called us.
402   static methodHandle find_callee_method(TRAPS);
403 
404   static void monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* thread);
405 
406   static void monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current);
407 
408   // Issue UL warning for unlocked JNI monitor on virtual thread termination
409   static void log_jni_monitor_still_held();
410 
411  private:
412   static Handle find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS);
413   static Handle find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc, CallInfo& callinfo, TRAPS);
414 
415   static Method* extract_attached_method(vframeStream& vfst);
416 
417 #if defined(X86) && defined(COMPILER1)
418   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
419   static void inline_check_hashcode_from_object_header(MacroAssembler* masm, const methodHandle& method, Register obj_reg, Register result);
420 #endif // X86 && COMPILER1
421 
422  public:
423 
424   // Read the array of BasicTypes from a Java signature, and compute where
425   // compiled Java code would like to put the results.  Values in reg_lo and
426   // reg_hi refer to 4-byte quantities.  Values less than SharedInfo::stack0 are
427   // registers, those above refer to 4-byte stack slots.  All stack slots are
428   // based off of the window top.  SharedInfo::stack0 refers to the first usable
429   // slot in the bottom of the frame. SharedInfo::stack0+1 refers to the memory word
430   // 4-bytes higher.
431   // return value is the maximum number of VMReg stack slots the convention will use.
432   static int java_calling_convention(const BasicType* sig_bt, VMRegPair* regs, int total_args_passed);
433 
434   static void check_member_name_argument_is_last_argument(const methodHandle& method,
435                                                           const BasicType* sig_bt,
436                                                           const VMRegPair* regs) NOT_DEBUG_RETURN;
437 
438   // Ditto except for calling C
439   //
440   // C argument in register AND stack slot.
441   // Some architectures require that an argument must be passed in a register
442   // AND in a stack slot. These architectures provide a second VMRegPair array
443   // to be filled by the c_calling_convention method. On other architectures,
444   // null is being passed as the second VMRegPair array, so arguments are either
445   // passed in a register OR in a stack slot.
446   static int c_calling_convention(const BasicType *sig_bt, VMRegPair *regs, int total_args_passed);
447 
448   static int vector_calling_convention(VMRegPair *regs,
449                                        uint num_bits,
450                                        uint total_args_passed);
451 
452   // Generate I2C and C2I adapters. These adapters are simple argument marshalling
453   // blobs. Unlike adapters in the tiger and earlier releases the code in these
454   // blobs does not create a new frame and are therefore virtually invisible
455   // to the stack walking code. In general these blobs extend the callers stack
456   // as needed for the conversion of argument locations.
457 
458   // When calling a c2i blob the code will always call the interpreter even if
459   // by the time we reach the blob there is compiled code available. This allows
460   // the blob to pass the incoming stack pointer (the sender sp) in a known
461   // location for the interpreter to record. This is used by the frame code
462   // to correct the sender code to match up with the stack pointer when the
463   // thread left the compiled code. In addition it allows the interpreter
464   // to remove the space the c2i adapter allocated to do its argument conversion.
465 
466   // Although a c2i blob will always run interpreted even if compiled code is
467   // present if we see that compiled code is present the compiled call site
468   // will be patched/re-resolved so that later calls will run compiled.
469 
470   // Additionally a c2i blob need to have a unverified entry because it can be reached
471   // in situations where the call site is an inlined cache site and may go megamorphic.
472 
473   // A i2c adapter is simpler than the c2i adapter. This is because it is assumed
474   // that the interpreter before it does any call dispatch will record the current
475   // stack pointer in the interpreter frame. On return it will restore the stack
476   // pointer as needed. This means the i2c adapter code doesn't need any special
477   // handshaking path with compiled code to keep the stack walking correct.
478 
479   static void generate_i2c2i_adapters(MacroAssembler *_masm,
480                                int total_args_passed,
481                                int max_arg,
482                                const BasicType *sig_bt,
483                                const VMRegPair *regs,
484                                AdapterHandlerEntry* handler);
485 
486   static void gen_i2c_adapter(MacroAssembler *_masm,
487                               int total_args_passed,
488                               int comp_args_on_stack,
489                               const BasicType *sig_bt,
490                               const VMRegPair *regs);
491 
492   // OSR support
493 
494   // OSR_migration_begin will extract the jvm state from an interpreter
495   // frame (locals, monitors) and store the data in a piece of C heap
496   // storage. This then allows the interpreter frame to be removed from the
497   // stack and the OSR nmethod to be called. That method is called with a
498   // pointer to the C heap storage. This pointer is the return value from
499   // OSR_migration_begin.
500 
501   static intptr_t* OSR_migration_begin(JavaThread *thread);
502 
503   // OSR_migration_end is a trivial routine. It is called after the compiled
504   // method has extracted the jvm state from the C heap that OSR_migration_begin
505   // created. It's entire job is to simply free this storage.
506   static void OSR_migration_end(intptr_t* buf);
507 
508   // Convert a sig into a calling convention register layout
509   // and find interesting things about it.
510   static VMRegPair* find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int *arg_size);
511   static VMReg name_for_receiver();
512 
513   // "Top of Stack" slots that may be unused by the calling convention but must
514   // otherwise be preserved.
515   // On Intel these are not necessary and the value can be zero.
516   // On Sparc this describes the words reserved for storing a register window
517   // when an interrupt occurs.
518   static uint out_preserve_stack_slots();
519 
520   // Stack slots that may be unused by the calling convention but must
521   // otherwise be preserved.  On Intel this includes the return address.
522   // On PowerPC it includes the 4 words holding the old TOC & LR glue.
523   static uint in_preserve_stack_slots();
524 
525   static VMReg thread_register();
526 
527   static void continuation_enter_cleanup(MacroAssembler* masm);
528 
529   // Is vector's size (in bytes) bigger than a size saved by default?
530   // For example, on x86 16 bytes XMM registers are saved by default.
531   static bool is_wide_vector(int size);
532 
533   // Save and restore a native result
534   static void    save_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots);
535   static void restore_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots);
536 
537   // Generate a native wrapper for a given method.  The method takes arguments
538   // in the Java compiled code convention, marshals them to the native
539   // convention (handlizes oops, etc), transitions to native, makes the call,
540   // returns to java state (possibly blocking), unhandlizes any result and
541   // returns.
542   //
543   // The wrapper may contain special-case code if the given method
544   // is a compiled method handle adapter, such as _invokeBasic, _linkToVirtual, etc.
545   static nmethod* generate_native_wrapper(MacroAssembler* masm,
546                                           const methodHandle& method,
547                                           int compile_id,
548                                           BasicType* sig_bt,
549                                           VMRegPair* regs,
550                                           BasicType ret_type);
551 
552   // A compiled caller has just called the interpreter, but compiled code
553   // exists.  Patch the caller so he no longer calls into the interpreter.
554   static void fixup_callers_callsite(Method* moop, address ret_pc);
555   static bool should_fixup_call_destination(address destination, address entry_point, address caller_pc, Method* moop, CodeBlob* cb);
556 
557   // Slow-path Locking and Unlocking
558   static void complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current);
559   static void complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current);
560 
561   // Resolving of calls
562   static address get_resolved_entry        (JavaThread* current, methodHandle callee_method);
563   static address resolve_static_call_C     (JavaThread* current);
564   static address resolve_virtual_call_C    (JavaThread* current);
565   static address resolve_opt_virtual_call_C(JavaThread* current);
566 
567   // arraycopy, the non-leaf version.  (See StubRoutines for all the leaf calls.)
568   static void slow_arraycopy_C(oopDesc* src,  jint src_pos,
569                                oopDesc* dest, jint dest_pos,
570                                jint length, JavaThread* thread);
571 
572   // handle ic miss with caller being compiled code
573   // wrong method handling (inline cache misses)
574   static address handle_wrong_method(JavaThread* current);
575   static address handle_wrong_method_abstract(JavaThread* current);
576   static address handle_wrong_method_ic_miss(JavaThread* current);
577 
578   static address handle_unsafe_access(JavaThread* thread, address next_pc);
579 
580  private:
581   static PerfTickCounters* _perf_resolve_opt_virtual_total_time;
582   static PerfTickCounters* _perf_resolve_virtual_total_time;
583   static PerfTickCounters* _perf_resolve_static_total_time;
584   static PerfTickCounters* _perf_handle_wrong_method_total_time;
585   static PerfTickCounters* _perf_ic_miss_total_time;
586  public:
587   static uint _ic_miss_ctr;                      // total # of IC misses
588   static uint _wrong_method_ctr;
589   static uint _resolve_static_ctr;
590   static uint _resolve_virtual_ctr;
591   static uint _resolve_opt_virtual_ctr;
592 
593   static void print_counters_on(outputStream* st);
594 
595 #ifndef PRODUCT
596 
597   // Collect and print inline cache miss statistics
598  private:
599   enum { maxICmiss_count = 100 };
600   static int     _ICmiss_index;                  // length of IC miss histogram
601   static int     _ICmiss_count[maxICmiss_count]; // miss counts
602   static address _ICmiss_at[maxICmiss_count];    // miss addresses
603   static void trace_ic_miss(address at);
604 
605  public:
606   static uint _implicit_null_throws;
607   static uint _implicit_div0_throws;
608 
609   static uint _jbyte_array_copy_ctr;       // Slow-path byte array copy
610   static uint _jshort_array_copy_ctr;      // Slow-path short array copy
611   static uint _jint_array_copy_ctr;        // Slow-path int array copy
612   static uint _jlong_array_copy_ctr;       // Slow-path long array copy
613   static uint _oop_array_copy_ctr;         // Slow-path oop array copy
614   static uint _checkcast_array_copy_ctr;   // Slow-path oop array copy, with cast
615   static uint _unsafe_array_copy_ctr;      // Slow-path includes alignment checks
616   static uint _generic_array_copy_ctr;     // Slow-path includes type decoding
617   static uint _slow_array_copy_ctr;        // Slow-path failed out to a method call
618 
619   static uint _unsafe_set_memory_ctr;      // Slow-path includes alignment checks
620 
621   static uint _new_instance_ctr;           // 'new' object requires GC
622   static uint _new_array_ctr;              // 'new' array requires GC
623   static uint _multi2_ctr, _multi3_ctr, _multi4_ctr, _multi5_ctr;
624   static uint _find_handler_ctr;           // find exception handler
625   static uint _rethrow_ctr;                // rethrow exception
626   static uint _mon_enter_stub_ctr;         // monitor enter stub
627   static uint _mon_exit_stub_ctr;          // monitor exit stub
628   static uint _mon_enter_ctr;              // monitor enter slow
629   static uint _mon_exit_ctr;               // monitor exit slow
630   static uint _partial_subtype_ctr;        // SubRoutines::partial_subtype_check
631 
632   // Statistics code
633   // stats for "normal" compiled calls (non-interface)
634   static int64_t _nof_normal_calls;               // total # of calls
635   static int64_t _nof_inlined_calls;              // total # of inlined normal calls
636   static int64_t _nof_static_calls;               // total # of calls to static methods or super methods (invokespecial)
637   static int64_t _nof_inlined_static_calls;       // total # of inlined static calls
638   // stats for compiled interface calls
639   static int64_t _nof_interface_calls;            // total # of compiled calls
640   static int64_t _nof_inlined_interface_calls;    // total # of inlined interface calls
641 
642  public: // for compiler
643   static address nof_normal_calls_addr()                { return (address)&_nof_normal_calls; }
644   static address nof_inlined_calls_addr()               { return (address)&_nof_inlined_calls; }
645   static address nof_static_calls_addr()                { return (address)&_nof_static_calls; }
646   static address nof_inlined_static_calls_addr()        { return (address)&_nof_inlined_static_calls; }
647   static address nof_interface_calls_addr()             { return (address)&_nof_interface_calls; }
648   static address nof_inlined_interface_calls_addr()     { return (address)&_nof_inlined_interface_calls; }
649 
650   static void print_call_statistics_on(outputStream* st);
651   static void print_ic_miss_histogram_on(outputStream* st);
652 #endif // PRODUCT
653 
654   static void print_statistics() PRODUCT_RETURN;
655 };
656 
657 
658 // ---------------------------------------------------------------------------
659 // Implementation of AdapterHandlerLibrary
660 //
661 // This library manages argument marshaling adapters and native wrappers.
662 // There are 2 flavors of adapters: I2C and C2I.
663 //
664 // The I2C flavor takes a stock interpreted call setup, marshals the
665 // arguments for a Java-compiled call, and jumps to Rmethod-> code()->
666 // code_begin().  It is broken to call it without an nmethod assigned.
667 // The usual behavior is to lift any register arguments up out of the
668 // stack and possibly re-pack the extra arguments to be contiguous.
669 // I2C adapters will save what the interpreter's stack pointer will be
670 // after arguments are popped, then adjust the interpreter's frame
671 // size to force alignment and possibly to repack the arguments.
672 // After re-packing, it jumps to the compiled code start.  There are
673 // no safepoints in this adapter code and a GC cannot happen while
674 // marshaling is in progress.
675 //
676 // The C2I flavor takes a stock compiled call setup plus the target method in
677 // Rmethod, marshals the arguments for an interpreted call and jumps to
678 // Rmethod->_i2i_entry.  On entry, the interpreted frame has not yet been
679 // setup.  Compiled frames are fixed-size and the args are likely not in the
680 // right place.  Hence all the args will likely be copied into the
681 // interpreter's frame, forcing that frame to grow.  The compiled frame's
682 // outgoing stack args will be dead after the copy.
683 //
684 // Native wrappers, like adapters, marshal arguments.  Unlike adapters they
685 // also perform an official frame push & pop.  They have a call to the native
686 // routine in their middles and end in a return (instead of ending in a jump).
687 // The native wrappers are stored in real nmethods instead of the BufferBlobs
688 // used by the adapters.  The code generation happens here because it's very
689 // similar to what the adapters have to do.
690 
691 class AdapterHandlerEntry : public MetaspaceObj {
692   friend class AdapterHandlerLibrary;
693 
694  public:
695   static const int ENTRIES_COUNT = 4;
696 
697  private:
698   AdapterFingerPrint* _fingerprint;
699   address _i2c_entry;
700   address _c2i_entry;
701   address _c2i_unverified_entry;
702   address _c2i_no_clinit_check_entry;
703   bool    _linked;
704 
705   static const char *_entry_names[];
706 
707 #ifdef ASSERT
708   // Captures code and signature used to generate this adapter when
709   // verifying adapter equivalence.
710   unsigned char* _saved_code;
711   int            _saved_code_length;
712 #endif
713 
714   AdapterHandlerEntry(AdapterFingerPrint* fingerprint) :
715     _fingerprint(fingerprint),
716     _i2c_entry(nullptr),
717     _c2i_entry(nullptr),
718     _c2i_unverified_entry(nullptr),
719     _c2i_no_clinit_check_entry(nullptr),
720     _linked(false)
721 #ifdef ASSERT
722     , _saved_code(nullptr),
723     _saved_code_length(0)
724 #endif
725   { }
726 
727   ~AdapterHandlerEntry();
728 
729   // Allocate on CHeap instead of metaspace (see JDK-8331086).
730   // Dummy argument is used to avoid C++ warning about using
731   // deleted opearator MetaspaceObj::delete().
732   void* operator new(size_t size, size_t dummy) throw() {
733     assert(size == BytesPerWord * heap_word_size(sizeof(AdapterHandlerEntry)), "should match");
734     void* p = AllocateHeap(size, mtCode);
735     memset(p, 0, size);
736     return p;
737   }
738 
739  public:
740   static AdapterHandlerEntry* allocate(AdapterFingerPrint* fingerprint) {
741     return new(0) AdapterHandlerEntry(fingerprint);
742   }
743 
744   static void deallocate(AdapterHandlerEntry *handler) {
745     handler->~AdapterHandlerEntry();
746   }
747 
748   void set_entry_points(address i2c_entry, address c2i_entry, address c2i_unverified_entry, address c2i_no_clinit_check_entry, bool linked = true) {
749     _i2c_entry = i2c_entry;
750     _c2i_entry = c2i_entry;
751     _c2i_unverified_entry = c2i_unverified_entry;
752     _c2i_no_clinit_check_entry = c2i_no_clinit_check_entry;
753     _linked = linked;
754   }
755 
756   address get_i2c_entry()                  const { return _i2c_entry; }
757   address get_c2i_entry()                  const { return _c2i_entry; }
758   address get_c2i_unverified_entry()       const { return _c2i_unverified_entry; }
759   address get_c2i_no_clinit_check_entry()  const { return _c2i_no_clinit_check_entry; }
760 
761   static const char* entry_name(int i) {
762     assert(i >=0 && i < ENTRIES_COUNT, "entry id out of range");
763     return _entry_names[i];
764   }
765 
766   bool is_linked() const { return _linked; }
767   address base_address();
768   void relocate(address new_base);
769 
770   AdapterFingerPrint* fingerprint() const { return _fingerprint; }
771 
772 #ifdef ASSERT
773   // Used to verify that code generated for shared adapters is equivalent
774   void save_code   (unsigned char* code, int length);
775   bool compare_code(AdapterHandlerEntry* other);
776 #endif
777 
778   //virtual void print_on(outputStream* st) const;  DO NOT USE
779   void print_adapter_on(outputStream* st) const;
780 
781   void metaspace_pointers_do(MetaspaceClosure* it);
782   int size() const {return (int)heap_word_size(sizeof(AdapterHandlerEntry)); }
783   MetaspaceObj::Type type() const { return AdapterHandlerEntryType; }
784 
785   void remove_unshareable_info() NOT_CDS_RETURN;
786   void link() NOT_CDS_RETURN;
787 };
788 
789 #if INCLUDE_CDS
790 class ArchivedAdapterTable;
791 #endif // INCLUDE_CDS
792 
793 class AdapterHandlerLibrary: public AllStatic {
794   friend class SharedRuntime;
795  private:
796   static BufferBlob* _buffer; // the temporary code buffer in CodeCache
797   static AdapterHandlerEntry* _no_arg_handler;
798   static AdapterHandlerEntry* _int_arg_handler;
799   static AdapterHandlerEntry* _obj_arg_handler;
800   static AdapterHandlerEntry* _obj_int_arg_handler;
801   static AdapterHandlerEntry* _obj_obj_arg_handler;
802 #if INCLUDE_CDS
803   static ArchivedAdapterTable _aot_adapter_handler_table;
804 #endif // INCLUDE_CDS
805 
806   static BufferBlob* buffer_blob();
807   static void initialize();
808   static AdapterHandlerEntry* get_simple_adapter(const methodHandle& method);
809   static AdapterBlob* lookup_aot_cache(AdapterHandlerEntry* handler);
810   static AdapterHandlerEntry* create_adapter(AdapterBlob*& new_adapter,
811                                              int total_args_passed,
812                                              BasicType* sig_bt,
813                                              bool is_transient = false);
814   static void lookup_simple_adapters() NOT_CDS_RETURN;
815 #ifndef PRODUCT
816   static void print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler, AdapterBlob* adapter_blob);
817 #endif // PRODUCT
818  public:
819 
820   static AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint);
821   static void create_native_wrapper(const methodHandle& method);
822   static AdapterHandlerEntry* get_adapter(const methodHandle& method);
823   static AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt);
824   static bool generate_adapter_code(AdapterBlob*& adapter_blob,
825                                     AdapterHandlerEntry* handler,
826                                     int total_args_passed,
827                                     BasicType* sig_bt,
828                                     bool is_transient);
829 
830 #ifdef ASSERT
831   static void verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached);
832 #endif // ASSERT
833 
834   static void print_handler(const CodeBlob* b) { print_handler_on(tty, b); }
835   static void print_handler_on(outputStream* st, const CodeBlob* b);
836   static bool contains(const CodeBlob* b);
837   static const char* name(AdapterFingerPrint* fingerprint);
838   static uint32_t id(AdapterFingerPrint* fingerprint);
839 #ifndef PRODUCT
840   static void print_statistics_on(outputStream* st);
841 #endif // PRODUCT
842 
843   static AdapterBlob* link_aot_adapter_handler(AdapterHandlerEntry* handler) NOT_CDS_RETURN_(nullptr);
844   static void dump_aot_adapter_table() NOT_CDS_RETURN;
845   static void serialize_shared_table_header(SerializeClosure* soc) NOT_CDS_RETURN;
846   static void link_aot_adapters() NOT_CDS_RETURN;
847 };
848 
849 #endif // SHARE_RUNTIME_SHAREDRUNTIME_HPP