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