1 /*
2 * Copyright (c) 1997, 2026, 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 "cds/aotCompressedPointers.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveUtils.inline.hpp"
28 #include "classfile/classLoader.hpp"
29 #include "classfile/compactHashtable.hpp"
30 #include "classfile/javaClasses.inline.hpp"
31 #include "classfile/stringTable.hpp"
32 #include "classfile/vmClasses.hpp"
33 #include "classfile/vmSymbols.hpp"
34 #include "code/aotCodeCache.hpp"
35 #include "code/codeCache.hpp"
36 #include "code/compiledIC.hpp"
37 #include "code/nmethod.inline.hpp"
38 #include "code/scopeDesc.hpp"
39 #include "code/vtableStubs.hpp"
40 #include "compiler/abstractCompiler.hpp"
41 #include "compiler/compileBroker.hpp"
42 #include "compiler/disassembler.hpp"
43 #include "gc/shared/barrierSet.hpp"
44 #include "gc/shared/collectedHeap.hpp"
45 #include "interpreter/interpreter.hpp"
46 #include "interpreter/interpreterRuntime.hpp"
47 #include "jfr/jfrEvents.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "memory/resourceArea.hpp"
51 #include "memory/universe.hpp"
52 #include "metaprogramming/primitiveConversions.hpp"
53 #include "oops/klass.hpp"
54 #include "oops/method.inline.hpp"
55 #include "oops/objArrayKlass.hpp"
56 #include "oops/oop.inline.hpp"
57 #include "prims/forte.hpp"
58 #include "prims/jvmtiExport.hpp"
59 #include "prims/jvmtiThreadState.hpp"
60 #include "prims/methodHandles.hpp"
61 #include "prims/nativeLookup.hpp"
62 #include "runtime/arguments.hpp"
63 #include "runtime/atomicAccess.hpp"
64 #include "runtime/basicLock.inline.hpp"
65 #include "runtime/frame.inline.hpp"
66 #include "runtime/handles.inline.hpp"
67 #include "runtime/init.hpp"
68 #include "runtime/interfaceSupport.inline.hpp"
69 #include "runtime/java.hpp"
70 #include "runtime/javaCalls.hpp"
71 #include "runtime/jniHandles.inline.hpp"
72 #include "runtime/osThread.hpp"
73 #include "runtime/perfData.hpp"
74 #include "runtime/sharedRuntime.hpp"
75 #include "runtime/stackWatermarkSet.hpp"
76 #include "runtime/stubRoutines.hpp"
77 #include "runtime/synchronizer.hpp"
78 #include "runtime/timerTrace.hpp"
79 #include "runtime/vframe.inline.hpp"
80 #include "runtime/vframeArray.hpp"
81 #include "runtime/vm_version.hpp"
82 #include "utilities/copy.hpp"
83 #include "utilities/dtrace.hpp"
84 #include "utilities/events.hpp"
85 #include "utilities/exceptions.hpp"
86 #include "utilities/globalDefinitions.hpp"
87 #include "utilities/hashTable.hpp"
88 #include "utilities/macros.hpp"
89 #include "utilities/xmlstream.hpp"
90 #ifdef COMPILER1
91 #include "c1/c1_Runtime1.hpp"
92 #endif
93 #ifdef COMPILER2
94 #include "opto/runtime.hpp"
95 #endif
96 #if INCLUDE_JFR
97 #include "jfr/jfr.inline.hpp"
98 #endif
99
100 // Shared runtime stub routines reside in their own unique blob with a
101 // single entry point
102
103
104 #define SHARED_STUB_FIELD_DEFINE(name, type) \
105 type* SharedRuntime::BLOB_FIELD_NAME(name);
106 SHARED_STUBS_DO(SHARED_STUB_FIELD_DEFINE)
107 #undef SHARED_STUB_FIELD_DEFINE
108
109 nmethod* SharedRuntime::_cont_doYield_stub;
110
111 #if 0
112 // TODO tweak global stub name generation to match this
113 #define SHARED_STUB_NAME_DECLARE(name, type) "Shared Runtime " # name "_blob",
114 const char *SharedRuntime::_stub_names[] = {
115 SHARED_STUBS_DO(SHARED_STUB_NAME_DECLARE)
116 };
117 #endif
118
119 //----------------------------generate_stubs-----------------------------------
120 void SharedRuntime::generate_initial_stubs() {
121 // Build this early so it's available for the interpreter.
122 _throw_StackOverflowError_blob =
123 generate_throw_exception(StubId::shared_throw_StackOverflowError_id,
124 CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError));
125 }
126
127 void SharedRuntime::generate_stubs() {
128 _wrong_method_blob =
129 generate_resolve_blob(StubId::shared_wrong_method_id,
130 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method));
131 _wrong_method_abstract_blob =
132 generate_resolve_blob(StubId::shared_wrong_method_abstract_id,
133 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract));
134 _ic_miss_blob =
135 generate_resolve_blob(StubId::shared_ic_miss_id,
136 CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss));
137 _resolve_opt_virtual_call_blob =
138 generate_resolve_blob(StubId::shared_resolve_opt_virtual_call_id,
139 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C));
140 _resolve_virtual_call_blob =
141 generate_resolve_blob(StubId::shared_resolve_virtual_call_id,
142 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C));
143 _resolve_static_call_blob =
144 generate_resolve_blob(StubId::shared_resolve_static_call_id,
145 CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C));
146
147 _throw_delayed_StackOverflowError_blob =
148 generate_throw_exception(StubId::shared_throw_delayed_StackOverflowError_id,
149 CAST_FROM_FN_PTR(address, SharedRuntime::throw_delayed_StackOverflowError));
150
151 _throw_AbstractMethodError_blob =
152 generate_throw_exception(StubId::shared_throw_AbstractMethodError_id,
153 CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError));
154
155 _throw_IncompatibleClassChangeError_blob =
156 generate_throw_exception(StubId::shared_throw_IncompatibleClassChangeError_id,
157 CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError));
158
159 _throw_NullPointerException_at_call_blob =
160 generate_throw_exception(StubId::shared_throw_NullPointerException_at_call_id,
161 CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call));
162
163 #ifdef COMPILER2
164 // Vectors are generated only by C2.
165 bool support_wide = is_wide_vector(MaxVectorSize);
166 if (support_wide) {
167 _polling_page_vectors_safepoint_handler_blob =
168 generate_handler_blob(StubId::shared_polling_page_vectors_safepoint_handler_id,
169 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
170 }
171 #endif // COMPILER2
172 _polling_page_safepoint_handler_blob =
173 generate_handler_blob(StubId::shared_polling_page_safepoint_handler_id,
174 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
175 _polling_page_return_handler_blob =
176 generate_handler_blob(StubId::shared_polling_page_return_handler_id,
177 CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception));
178
179 generate_deopt_blob();
180
181 #if INCLUDE_CDS
182 // disallow any further generation of runtime stubs
183 AOTCodeCache::set_shared_stubs_complete();
184 #endif // INCLUDE_CDS
185 }
186
187 void SharedRuntime::init_adapter_library() {
188 AdapterHandlerLibrary::initialize();
189 }
190
191 #if INCLUDE_JFR
192 //------------------------------generate jfr runtime stubs ------
193 void SharedRuntime::generate_jfr_stubs() {
194 ResourceMark rm;
195 const char* timer_msg = "SharedRuntime generate_jfr_stubs";
196 TraceTime timer(timer_msg, TRACETIME_LOG(Info, startuptime));
197
198 _jfr_write_checkpoint_blob = generate_jfr_write_checkpoint();
199 _jfr_return_lease_blob = generate_jfr_return_lease();
200 }
201
202 #endif // INCLUDE_JFR
203
204 #include <math.h>
205
206 // Implementation of SharedRuntime
207
208 #ifndef PRODUCT
209 // For statistics
210 uint SharedRuntime::_ic_miss_ctr = 0;
211 uint SharedRuntime::_wrong_method_ctr = 0;
212 uint SharedRuntime::_resolve_static_ctr = 0;
213 uint SharedRuntime::_resolve_virtual_ctr = 0;
214 uint SharedRuntime::_resolve_opt_virtual_ctr = 0;
215 uint SharedRuntime::_implicit_null_throws = 0;
216 uint SharedRuntime::_implicit_div0_throws = 0;
217
218 int64_t SharedRuntime::_nof_normal_calls = 0;
219 int64_t SharedRuntime::_nof_inlined_calls = 0;
220 int64_t SharedRuntime::_nof_megamorphic_calls = 0;
221 int64_t SharedRuntime::_nof_static_calls = 0;
222 int64_t SharedRuntime::_nof_inlined_static_calls = 0;
223 int64_t SharedRuntime::_nof_interface_calls = 0;
224 int64_t SharedRuntime::_nof_inlined_interface_calls = 0;
225
226 uint SharedRuntime::_new_instance_ctr=0;
227 uint SharedRuntime::_new_array_ctr=0;
228 uint SharedRuntime::_multi2_ctr=0;
229 uint SharedRuntime::_multi3_ctr=0;
230 uint SharedRuntime::_multi4_ctr=0;
231 uint SharedRuntime::_multi5_ctr=0;
232 uint SharedRuntime::_mon_enter_stub_ctr=0;
233 uint SharedRuntime::_mon_exit_stub_ctr=0;
234 uint SharedRuntime::_mon_enter_ctr=0;
235 uint SharedRuntime::_mon_exit_ctr=0;
236 uint SharedRuntime::_partial_subtype_ctr=0;
237 uint SharedRuntime::_jbyte_array_copy_ctr=0;
238 uint SharedRuntime::_jshort_array_copy_ctr=0;
239 uint SharedRuntime::_jint_array_copy_ctr=0;
240 uint SharedRuntime::_jlong_array_copy_ctr=0;
241 uint SharedRuntime::_oop_array_copy_ctr=0;
242 uint SharedRuntime::_checkcast_array_copy_ctr=0;
243 uint SharedRuntime::_unsafe_array_copy_ctr=0;
244 uint SharedRuntime::_generic_array_copy_ctr=0;
245 uint SharedRuntime::_slow_array_copy_ctr=0;
246 uint SharedRuntime::_find_handler_ctr=0;
247 uint SharedRuntime::_rethrow_ctr=0;
248 uint SharedRuntime::_unsafe_set_memory_ctr=0;
249
250 int SharedRuntime::_ICmiss_index = 0;
251 int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
252 address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
253
254
255 void SharedRuntime::trace_ic_miss(address at) {
256 for (int i = 0; i < _ICmiss_index; i++) {
257 if (_ICmiss_at[i] == at) {
258 _ICmiss_count[i]++;
259 return;
260 }
261 }
262 int index = _ICmiss_index++;
263 if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
264 _ICmiss_at[index] = at;
265 _ICmiss_count[index] = 1;
266 }
267
268 void SharedRuntime::print_ic_miss_histogram() {
269 if (ICMissHistogram) {
270 tty->print_cr("IC Miss Histogram:");
271 int tot_misses = 0;
272 for (int i = 0; i < _ICmiss_index; i++) {
273 tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", p2i(_ICmiss_at[i]), _ICmiss_count[i]);
274 tot_misses += _ICmiss_count[i];
275 }
276 tty->print_cr("Total IC misses: %7d", tot_misses);
277 }
278 }
279
280 #ifdef COMPILER2
281 // Runtime methods for printf-style debug nodes (same printing format as fieldDescriptor::print_on_for)
282 void SharedRuntime::debug_print_value(jboolean x) {
283 tty->print_cr("boolean %d", x);
284 }
285
286 void SharedRuntime::debug_print_value(jbyte x) {
287 tty->print_cr("byte %d", x);
288 }
289
290 void SharedRuntime::debug_print_value(jshort x) {
291 tty->print_cr("short %d", x);
292 }
293
294 void SharedRuntime::debug_print_value(jchar x) {
295 tty->print_cr("char %c %d", isprint(x) ? x : ' ', x);
296 }
297
298 void SharedRuntime::debug_print_value(jint x) {
299 tty->print_cr("int %d", x);
300 }
301
302 void SharedRuntime::debug_print_value(jlong x) {
303 tty->print_cr("long " JLONG_FORMAT, x);
304 }
305
306 void SharedRuntime::debug_print_value(jfloat x) {
307 tty->print_cr("float %f", x);
308 }
309
310 void SharedRuntime::debug_print_value(jdouble x) {
311 tty->print_cr("double %lf", x);
312 }
313
314 void SharedRuntime::debug_print_value(oopDesc* x) {
315 x->print();
316 }
317 #endif // COMPILER2
318
319 #endif // PRODUCT
320
321
322 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
323 return x * y;
324 JRT_END
325
326
327 JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
328 if (x == min_jlong && y == CONST64(-1)) {
329 return x;
330 } else {
331 return x / y;
332 }
333 JRT_END
334
335
336 JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
337 if (x == min_jlong && y == CONST64(-1)) {
338 return 0;
339 } else {
340 return x % y;
341 }
342 JRT_END
343
344
345 #ifdef _WIN64
346 const juint float_sign_mask = 0x7FFFFFFF;
347 const juint float_infinity = 0x7F800000;
348 const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
349 const julong double_infinity = CONST64(0x7FF0000000000000);
350 #endif
351
352 #if !defined(X86)
353 JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y))
354 #ifdef _WIN64
355 // 64-bit Windows on amd64 returns the wrong values for
356 // infinity operands.
357 juint xbits = PrimitiveConversions::cast<juint>(x);
358 juint ybits = PrimitiveConversions::cast<juint>(y);
359 // x Mod Infinity == x unless x is infinity
360 if (((xbits & float_sign_mask) != float_infinity) &&
361 ((ybits & float_sign_mask) == float_infinity) ) {
362 return x;
363 }
364 return ((jfloat)fmod_winx64((double)x, (double)y));
365 #else
366 return ((jfloat)fmod((double)x,(double)y));
367 #endif
368 JRT_END
369
370 JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
371 #ifdef _WIN64
372 julong xbits = PrimitiveConversions::cast<julong>(x);
373 julong ybits = PrimitiveConversions::cast<julong>(y);
374 // x Mod Infinity == x unless x is infinity
375 if (((xbits & double_sign_mask) != double_infinity) &&
376 ((ybits & double_sign_mask) == double_infinity) ) {
377 return x;
378 }
379 return ((jdouble)fmod_winx64((double)x, (double)y));
380 #else
381 return ((jdouble)fmod((double)x,(double)y));
382 #endif
383 JRT_END
384 #endif // !X86
385
386 JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
387 return (jfloat)x;
388 JRT_END
389
390 #ifdef __SOFTFP__
391 JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
392 return x + y;
393 JRT_END
394
395 JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
396 return x - y;
397 JRT_END
398
399 JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
400 return x * y;
401 JRT_END
402
403 JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
404 return x / y;
405 JRT_END
406
407 JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
408 return x + y;
409 JRT_END
410
411 JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
412 return x - y;
413 JRT_END
414
415 JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
416 return x * y;
417 JRT_END
418
419 JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
420 return x / y;
421 JRT_END
422
423 JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
424 return (jdouble)x;
425 JRT_END
426
427 JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
428 return (jdouble)x;
429 JRT_END
430
431 JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y))
432 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan*/
433 JRT_END
434
435 JRT_LEAF(int, SharedRuntime::fcmpg(float x, float y))
436 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
437 JRT_END
438
439 JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y))
440 return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
441 JRT_END
442
443 JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y))
444 return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
445 JRT_END
446
447 // Functions to return the opposite of the aeabi functions for nan.
448 JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
449 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
450 JRT_END
451
452 JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
453 return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
454 JRT_END
455
456 JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
457 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
458 JRT_END
459
460 JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
461 return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
462 JRT_END
463
464 JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
465 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
466 JRT_END
467
468 JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
469 return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
470 JRT_END
471
472 JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
473 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
474 JRT_END
475
476 JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
477 return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
478 JRT_END
479
480 // Intrinsics make gcc generate code for these.
481 float SharedRuntime::fneg(float f) {
482 return -f;
483 }
484
485 double SharedRuntime::dneg(double f) {
486 return -f;
487 }
488
489 #endif // __SOFTFP__
490
491 #if defined(__SOFTFP__) || defined(E500V2)
492 // Intrinsics make gcc generate code for these.
493 double SharedRuntime::dabs(double f) {
494 return (f <= (double)0.0) ? (double)0.0 - f : f;
495 }
496
497 #endif
498
499 #if defined(__SOFTFP__)
500 double SharedRuntime::dsqrt(double f) {
501 return sqrt(f);
502 }
503 #endif
504
505 JRT_LEAF(jint, SharedRuntime::f2i(jfloat x))
506 if (g_isnan(x))
507 return 0;
508 if (x >= (jfloat) max_jint)
509 return max_jint;
510 if (x <= (jfloat) min_jint)
511 return min_jint;
512 return (jint) x;
513 JRT_END
514
515
516 JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x))
517 if (g_isnan(x))
518 return 0;
519 if (x >= (jfloat) max_jlong)
520 return max_jlong;
521 if (x <= (jfloat) min_jlong)
522 return min_jlong;
523 return (jlong) x;
524 JRT_END
525
526
527 JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
528 if (g_isnan(x))
529 return 0;
530 if (x >= (jdouble) max_jint)
531 return max_jint;
532 if (x <= (jdouble) min_jint)
533 return min_jint;
534 return (jint) x;
535 JRT_END
536
537
538 JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
539 if (g_isnan(x))
540 return 0;
541 if (x >= (jdouble) max_jlong)
542 return max_jlong;
543 if (x <= (jdouble) min_jlong)
544 return min_jlong;
545 return (jlong) x;
546 JRT_END
547
548
549 JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
550 return (jfloat)x;
551 JRT_END
552
553
554 JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
555 return (jfloat)x;
556 JRT_END
557
558
559 JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
560 return (jdouble)x;
561 JRT_END
562
563
564 // Exception handling across interpreter/compiler boundaries
565 //
566 // exception_handler_for_return_address(...) returns the continuation address.
567 // The continuation address is the entry point of the exception handler of the
568 // previous frame depending on the return address.
569
570 address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* current, address return_address) {
571 // Note: This is called when we have unwound the frame of the callee that did
572 // throw an exception. So far, no check has been performed by the StackWatermarkSet.
573 // Notably, the stack is not walkable at this point, and hence the check must
574 // be deferred until later. Specifically, any of the handlers returned here in
575 // this function, will get dispatched to, and call deferred checks to
576 // StackWatermarkSet::after_unwind at a point where the stack is walkable.
577 assert(frame::verify_return_pc(return_address), "must be a return address: " INTPTR_FORMAT, p2i(return_address));
578 assert(current->frames_to_pop_failed_realloc() == 0 || Interpreter::contains(return_address), "missed frames to pop?");
579
580 if (Continuation::is_return_barrier_entry(return_address)) {
581 return StubRoutines::cont_returnBarrierExc();
582 }
583
584 // The fastest case first
585 CodeBlob* blob = CodeCache::find_blob(return_address);
586 nmethod* nm = (blob != nullptr) ? blob->as_nmethod_or_null() : nullptr;
587 if (nm != nullptr) {
588 // native nmethods don't have exception handlers
589 assert(!nm->is_native_method() || nm->method()->is_continuation_enter_intrinsic(), "no exception handler");
590 assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
591 if (nm->is_deopt_pc(return_address)) {
592 // If we come here because of a stack overflow, the stack may be
593 // unguarded. Reguard the stack otherwise if we return to the
594 // deopt blob and the stack bang causes a stack overflow we
595 // crash.
596 StackOverflow* overflow_state = current->stack_overflow_state();
597 bool guard_pages_enabled = overflow_state->reguard_stack_if_needed();
598 if (overflow_state->reserved_stack_activation() != current->stack_base()) {
599 overflow_state->set_reserved_stack_activation(current->stack_base());
600 }
601 assert(guard_pages_enabled, "stack banging in deopt blob may cause crash");
602 // The deferred StackWatermarkSet::after_unwind check will be performed in
603 // Deoptimization::fetch_unroll_info (with exec_mode == Unpack_exception)
604 return SharedRuntime::deopt_blob()->unpack_with_exception();
605 } else {
606 // The deferred StackWatermarkSet::after_unwind check will be performed in
607 // * OptoRuntime::handle_exception_C_helper for C2 code
608 // * exception_handler_for_pc_helper via Runtime1::handle_exception_from_callee_id for C1 code
609 #ifdef COMPILER2
610 if (nm->compiler_type() == compiler_c2) {
611 return OptoRuntime::exception_blob()->entry_point();
612 }
613 #endif // COMPILER2
614 return nm->exception_begin();
615 }
616 }
617
618 // Entry code
619 if (StubRoutines::returns_to_call_stub(return_address)) {
620 // The deferred StackWatermarkSet::after_unwind check will be performed in
621 // JavaCallWrapper::~JavaCallWrapper
622 assert (StubRoutines::catch_exception_entry() != nullptr, "must be generated before");
623 return StubRoutines::catch_exception_entry();
624 }
625 if (blob != nullptr && blob->is_upcall_stub()) {
626 return StubRoutines::upcall_stub_exception_handler();
627 }
628 // Interpreted code
629 if (Interpreter::contains(return_address)) {
630 // The deferred StackWatermarkSet::after_unwind check will be performed in
631 // InterpreterRuntime::exception_handler_for_exception
632 return Interpreter::rethrow_exception_entry();
633 }
634
635 guarantee(blob == nullptr || !blob->is_runtime_stub(), "caller should have skipped stub");
636 guarantee(!VtableStubs::contains(return_address), "null exceptions in vtables should have been handled already!");
637
638 #ifndef PRODUCT
639 { ResourceMark rm;
640 tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", p2i(return_address));
641 os::print_location(tty, (intptr_t)return_address);
642 tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
643 tty->print_cr("b) other problem");
644 }
645 #endif // PRODUCT
646 ShouldNotReachHere();
647 return nullptr;
648 }
649
650
651 JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* current, address return_address))
652 return raw_exception_handler_for_return_address(current, return_address);
653 JRT_END
654
655
656 address SharedRuntime::get_poll_stub(address pc) {
657 address stub;
658 // Look up the code blob
659 CodeBlob *cb = CodeCache::find_blob(pc);
660
661 // Should be an nmethod
662 guarantee(cb != nullptr && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod");
663
664 // Look up the relocation information
665 assert(cb->as_nmethod()->is_at_poll_or_poll_return(pc),
666 "safepoint polling: type must be poll at pc " INTPTR_FORMAT, p2i(pc));
667
668 #ifdef ASSERT
669 if (!((NativeInstruction*)pc)->is_safepoint_poll()) {
670 tty->print_cr("bad pc: " PTR_FORMAT, p2i(pc));
671 Disassembler::decode(cb);
672 fatal("Only polling locations are used for safepoint");
673 }
674 #endif
675
676 bool at_poll_return = cb->as_nmethod()->is_at_poll_return(pc);
677 bool has_wide_vectors = cb->as_nmethod()->has_wide_vectors();
678 if (at_poll_return) {
679 assert(SharedRuntime::polling_page_return_handler_blob() != nullptr,
680 "polling page return stub not created yet");
681 stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
682 } else if (has_wide_vectors) {
683 assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != nullptr,
684 "polling page vectors safepoint stub not created yet");
685 stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
686 } else {
687 assert(SharedRuntime::polling_page_safepoint_handler_blob() != nullptr,
688 "polling page safepoint stub not created yet");
689 stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
690 }
691 log_trace(safepoint)("Polling page exception: thread = " INTPTR_FORMAT " [%d], pc = "
692 INTPTR_FORMAT " (%s), stub = " INTPTR_FORMAT,
693 p2i(Thread::current()),
694 Thread::current()->osthread()->thread_id(),
695 p2i(pc),
696 at_poll_return ? "return" : "loop",
697 p2i(stub));
698 return stub;
699 }
700
701 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Handle h_exception) {
702 if (JvmtiExport::can_post_on_exceptions()) {
703 vframeStream vfst(current, true);
704 methodHandle method = methodHandle(current, vfst.method());
705 address bcp = method()->bcp_from(vfst.bci());
706 JvmtiExport::post_exception_throw(current, method(), bcp, h_exception());
707 }
708
709 Exceptions::_throw(current, __FILE__, __LINE__, h_exception);
710 }
711
712 void SharedRuntime::throw_and_post_jvmti_exception(JavaThread* current, Symbol* name, const char *message) {
713 Handle h_exception = Exceptions::new_exception(current, name, message);
714 throw_and_post_jvmti_exception(current, h_exception);
715 }
716
717 // The interpreter code to call this tracing function is only
718 // called/generated when UL is on for redefine, class and has the right level
719 // and tags. Since obsolete methods are never compiled, we don't have
720 // to modify the compilers to generate calls to this function.
721 //
722 JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
723 JavaThread* thread, Method* method))
724 if (method->is_obsolete()) {
725 // We are calling an obsolete method, but this is not necessarily
726 // an error. Our method could have been redefined just after we
727 // fetched the Method* from the constant pool.
728 ResourceMark rm;
729 log_trace(redefine, class, obsolete)("calling obsolete method '%s'", method->name_and_sig_as_C_string());
730 }
731 return 0;
732 JRT_END
733
734 // ret_pc points into caller; we are returning caller's exception handler
735 // for given exception
736 // Note that the implementation of this method assumes it's only called when an exception has actually occured
737 address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
738 bool force_unwind, bool top_frame_only, bool& recursive_exception_occurred) {
739 assert(nm != nullptr, "must exist");
740 ResourceMark rm;
741
742 ScopeDesc* sd = nm->scope_desc_at(ret_pc);
743 // determine handler bci, if any
744 EXCEPTION_MARK;
745
746 Handle orig_exception(THREAD, exception());
747
748 int handler_bci = -1;
749 int scope_depth = 0;
750 if (!force_unwind) {
751 int bci = sd->bci();
752 bool recursive_exception = false;
753 do {
754 bool skip_scope_increment = false;
755 // exception handler lookup
756 Klass* ek = exception->klass();
757 methodHandle mh(THREAD, sd->method());
758 handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
759 if (HAS_PENDING_EXCEPTION) {
760 recursive_exception = true;
761 // We threw an exception while trying to find the exception handler.
762 // Transfer the new exception to the exception handle which will
763 // be set into thread local storage, and do another lookup for an
764 // exception handler for this exception, this time starting at the
765 // BCI of the exception handler which caused the exception to be
766 // thrown (bugs 4307310 and 4546590). Set "exception" reference
767 // argument to ensure that the correct exception is thrown (4870175).
768 recursive_exception_occurred = true;
769 exception.replace(PENDING_EXCEPTION);
770 CLEAR_PENDING_EXCEPTION;
771 if (handler_bci >= 0) {
772 bci = handler_bci;
773 handler_bci = -1;
774 skip_scope_increment = true;
775 }
776 }
777 else {
778 recursive_exception = false;
779 }
780 if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
781 sd = sd->sender();
782 if (sd != nullptr) {
783 bci = sd->bci();
784 }
785 ++scope_depth;
786 }
787 } while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != nullptr));
788 }
789
790 // found handling method => lookup exception handler
791 int catch_pco = pointer_delta_as_int(ret_pc, nm->code_begin());
792
793 ExceptionHandlerTable table(nm);
794 HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
795
796 // If the compiler did not anticipate a recursive exception, resulting in an exception
797 // thrown from the catch bci, then the compiled exception handler might be missing.
798 // This is rare. Just deoptimize and let the interpreter rethrow the original
799 // exception at the original bci.
800 if (t == nullptr && recursive_exception_occurred) {
801 exception.replace(orig_exception()); // restore original exception
802 bool make_not_entrant = false;
803 return Deoptimization::deoptimize_for_missing_exception_handler(nm, make_not_entrant);
804 }
805
806 if (t == nullptr && (nm->is_compiled_by_c1() || handler_bci != -1)) {
807 // Allow abbreviated catch tables. The idea is to allow a method
808 // to materialize its exceptions without committing to the exact
809 // routing of exceptions. In particular this is needed for adding
810 // a synthetic handler to unlock monitors when inlining
811 // synchronized methods since the unlock path isn't represented in
812 // the bytecodes.
813 t = table.entry_for(catch_pco, -1, 0);
814 }
815
816 #ifdef COMPILER1
817 if (t == nullptr && nm->is_compiled_by_c1()) {
818 assert(nm->unwind_handler_begin() != nullptr, "");
819 return nm->unwind_handler_begin();
820 }
821 #endif
822
823 if (t == nullptr) {
824 ttyLocker ttyl;
825 tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d, catch_pco: %d", p2i(ret_pc), handler_bci, catch_pco);
826 tty->print_cr(" Exception:");
827 exception->print();
828 tty->cr();
829 tty->print_cr(" Compiled exception table :");
830 table.print();
831 nm->print();
832 nm->print_code();
833 guarantee(false, "missing exception handler");
834 return nullptr;
835 }
836
837 if (handler_bci != -1) { // did we find a handler in this method?
838 sd->method()->set_exception_handler_entered(handler_bci); // profile
839 }
840 return nm->code_begin() + t->pco();
841 }
842
843 JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* current))
844 // These errors occur only at call sites
845 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_AbstractMethodError());
846 JRT_END
847
848 JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* current))
849 // These errors occur only at call sites
850 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
851 JRT_END
852
853 JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* current))
854 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
855 JRT_END
856
857 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* current))
858 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
859 JRT_END
860
861 JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* current))
862 // This entry point is effectively only used for NullPointerExceptions which occur at inline
863 // cache sites (when the callee activation is not yet set up) so we are at a call site
864 throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException(), nullptr);
865 JRT_END
866
867 JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* current))
868 throw_StackOverflowError_common(current, false);
869 JRT_END
870
871 JRT_ENTRY(void, SharedRuntime::throw_delayed_StackOverflowError(JavaThread* current))
872 throw_StackOverflowError_common(current, true);
873 JRT_END
874
875 void SharedRuntime::throw_StackOverflowError_common(JavaThread* current, bool delayed) {
876 // We avoid using the normal exception construction in this case because
877 // it performs an upcall to Java, and we're already out of stack space.
878 JavaThread* THREAD = current; // For exception macros.
879 InstanceKlass* k = vmClasses::StackOverflowError_klass();
880 oop exception_oop = k->allocate_instance(CHECK);
881 if (delayed) {
882 java_lang_Throwable::set_message(exception_oop,
883 Universe::delayed_stack_overflow_error_message());
884 }
885 Handle exception (current, exception_oop);
886 if (StackTraceInThrowable) {
887 java_lang_Throwable::fill_in_stack_trace(exception);
888 }
889 // Remove the ScopedValue bindings in case we got a
890 // StackOverflowError while we were trying to remove ScopedValue
891 // bindings.
892 current->clear_scopedValueBindings();
893 // Increment counter for hs_err file reporting
894 Exceptions::increment_stack_overflow_errors();
895 throw_and_post_jvmti_exception(current, exception);
896 }
897
898 address SharedRuntime::continuation_for_implicit_exception(JavaThread* current,
899 address pc,
900 ImplicitExceptionKind exception_kind)
901 {
902 address target_pc = nullptr;
903
904 if (Interpreter::contains(pc)) {
905 switch (exception_kind) {
906 case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry();
907 case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
908 case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry();
909 default: ShouldNotReachHere();
910 }
911 } else {
912 switch (exception_kind) {
913 case STACK_OVERFLOW: {
914 // Stack overflow only occurs upon frame setup; the callee is
915 // going to be unwound. Dispatch to a shared runtime stub
916 // which will cause the StackOverflowError to be fabricated
917 // and processed.
918 // Stack overflow should never occur during deoptimization:
919 // the compiled method bangs the stack by as much as the
920 // interpreter would need in case of a deoptimization. The
921 // deoptimization blob and uncommon trap blob bang the stack
922 // in a debug VM to verify the correctness of the compiled
923 // method stack banging.
924 assert(current->deopt_mark() == nullptr, "no stack overflow from deopt blob/uncommon trap");
925 Events::log_exception(current, "StackOverflowError at " INTPTR_FORMAT, p2i(pc));
926 return SharedRuntime::throw_StackOverflowError_entry();
927 }
928
929 case IMPLICIT_NULL: {
930 if (VtableStubs::contains(pc)) {
931 // We haven't yet entered the callee frame. Fabricate an
932 // exception and begin dispatching it in the caller. Since
933 // the caller was at a call site, it's safe to destroy all
934 // caller-saved registers, as these entry points do.
935 VtableStub* vt_stub = VtableStubs::stub_containing(pc);
936
937 // If vt_stub is null, then return null to signal handler to report the SEGV error.
938 if (vt_stub == nullptr) return nullptr;
939
940 if (vt_stub->is_abstract_method_error(pc)) {
941 assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
942 Events::log_exception(current, "AbstractMethodError at " INTPTR_FORMAT, p2i(pc));
943 // Instead of throwing the abstract method error here directly, we re-resolve
944 // and will throw the AbstractMethodError during resolve. As a result, we'll
945 // get a more detailed error message.
946 return SharedRuntime::get_handle_wrong_method_stub();
947 } else {
948 Events::log_exception(current, "NullPointerException at vtable entry " INTPTR_FORMAT, p2i(pc));
949 // Assert that the signal comes from the expected location in stub code.
950 assert(vt_stub->is_null_pointer_exception(pc),
951 "obtained signal from unexpected location in stub code");
952 return SharedRuntime::throw_NullPointerException_at_call_entry();
953 }
954 } else {
955 CodeBlob* cb = CodeCache::find_blob(pc);
956
957 // If code blob is null, then return null to signal handler to report the SEGV error.
958 if (cb == nullptr) return nullptr;
959
960 // Exception happened in CodeCache. Must be either:
961 // 1. Inline-cache check in C2I handler blob,
962 // 2. Inline-cache check in nmethod, or
963 // 3. Implicit null exception in nmethod
964
965 if (!cb->is_nmethod()) {
966 bool is_in_blob = cb->is_adapter_blob() || cb->is_method_handles_adapter_blob();
967 if (!is_in_blob) {
968 // Allow normal crash reporting to handle this
969 return nullptr;
970 }
971 Events::log_exception(current, "NullPointerException in code blob at " INTPTR_FORMAT, p2i(pc));
972 // There is no handler here, so we will simply unwind.
973 return SharedRuntime::throw_NullPointerException_at_call_entry();
974 }
975
976 // Otherwise, it's a compiled method. Consult its exception handlers.
977 nmethod* nm = cb->as_nmethod();
978 if (nm->inlinecache_check_contains(pc)) {
979 // exception happened inside inline-cache check code
980 // => the nmethod is not yet active (i.e., the frame
981 // is not set up yet) => use return address pushed by
982 // caller => don't push another return address
983 Events::log_exception(current, "NullPointerException in IC check " INTPTR_FORMAT, p2i(pc));
984 return SharedRuntime::throw_NullPointerException_at_call_entry();
985 }
986
987 if (nm->method()->is_method_handle_intrinsic()) {
988 // exception happened inside MH dispatch code, similar to a vtable stub
989 Events::log_exception(current, "NullPointerException in MH adapter " INTPTR_FORMAT, p2i(pc));
990 return SharedRuntime::throw_NullPointerException_at_call_entry();
991 }
992
993 #ifndef PRODUCT
994 _implicit_null_throws++;
995 #endif
996 target_pc = nm->continuation_for_implicit_exception(pc);
997 // If there's an unexpected fault, target_pc might be null,
998 // in which case we want to fall through into the normal
999 // error handling code.
1000 }
1001
1002 break; // fall through
1003 }
1004
1005
1006 case IMPLICIT_DIVIDE_BY_ZERO: {
1007 nmethod* nm = CodeCache::find_nmethod(pc);
1008 guarantee(nm != nullptr, "must have containing compiled method for implicit division-by-zero exceptions");
1009 #ifndef PRODUCT
1010 _implicit_div0_throws++;
1011 #endif
1012 target_pc = nm->continuation_for_implicit_exception(pc);
1013 // If there's an unexpected fault, target_pc might be null,
1014 // in which case we want to fall through into the normal
1015 // error handling code.
1016 break; // fall through
1017 }
1018
1019 default: ShouldNotReachHere();
1020 }
1021
1022 assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
1023
1024 if (exception_kind == IMPLICIT_NULL) {
1025 #ifndef PRODUCT
1026 // for AbortVMOnException flag
1027 Exceptions::debug_check_abort("java.lang.NullPointerException");
1028 #endif //PRODUCT
1029 Events::log_exception(current, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1030 } else {
1031 #ifndef PRODUCT
1032 // for AbortVMOnException flag
1033 Exceptions::debug_check_abort("java.lang.ArithmeticException");
1034 #endif //PRODUCT
1035 Events::log_exception(current, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(target_pc));
1036 }
1037 return target_pc;
1038 }
1039
1040 ShouldNotReachHere();
1041 return nullptr;
1042 }
1043
1044
1045 /**
1046 * Throws an java/lang/UnsatisfiedLinkError. The address of this method is
1047 * installed in the native function entry of all native Java methods before
1048 * they get linked to their actual native methods.
1049 *
1050 * \note
1051 * This method actually never gets called! The reason is because
1052 * the interpreter's native entries call NativeLookup::lookup() which
1053 * throws the exception when the lookup fails. The exception is then
1054 * caught and forwarded on the return from NativeLookup::lookup() call
1055 * before the call to the native function. This might change in the future.
1056 */
1057 JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
1058 {
1059 // We return a bad value here to make sure that the exception is
1060 // forwarded before we look at the return value.
1061 THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
1062 }
1063 JNI_END
1064
1065 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
1066 return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
1067 }
1068
1069 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
1070 assert(oopDesc::is_oop(obj), "must be a valid oop");
1071 assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
1072 InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
1073 JRT_END
1074
1075 jlong SharedRuntime::get_java_tid(JavaThread* thread) {
1076 assert(thread != nullptr, "No thread");
1077 if (thread == nullptr) {
1078 return 0;
1079 }
1080 guarantee(Thread::current() != thread || thread->is_oop_safe(),
1081 "current cannot touch oops after its GC barrier is detached.");
1082 oop obj = thread->threadObj();
1083 return (obj == nullptr) ? 0 : java_lang_Thread::thread_id(obj);
1084 }
1085
1086 /**
1087 * This function ought to be a void function, but cannot be because
1088 * it gets turned into a tail-call on sparc, which runs into dtrace bug
1089 * 6254741. Once that is fixed we can remove the dummy return value.
1090 */
1091 int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
1092 return dtrace_object_alloc(JavaThread::current(), o, o->size());
1093 }
1094
1095 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o) {
1096 return dtrace_object_alloc(thread, o, o->size());
1097 }
1098
1099 int SharedRuntime::dtrace_object_alloc(JavaThread* thread, oopDesc* o, size_t size) {
1100 assert(DTraceAllocProbes, "wrong call");
1101 Klass* klass = o->klass();
1102 Symbol* name = klass->name();
1103 HOTSPOT_OBJECT_ALLOC(
1104 get_java_tid(thread),
1105 (char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
1106 return 0;
1107 }
1108
1109 JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
1110 JavaThread* current, Method* method))
1111 assert(current == JavaThread::current(), "pre-condition");
1112
1113 assert(DTraceMethodProbes, "wrong call");
1114 Symbol* kname = method->klass_name();
1115 Symbol* name = method->name();
1116 Symbol* sig = method->signature();
1117 HOTSPOT_METHOD_ENTRY(
1118 get_java_tid(current),
1119 (char *) kname->bytes(), kname->utf8_length(),
1120 (char *) name->bytes(), name->utf8_length(),
1121 (char *) sig->bytes(), sig->utf8_length());
1122 return 0;
1123 JRT_END
1124
1125 JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
1126 JavaThread* current, Method* method))
1127 assert(current == JavaThread::current(), "pre-condition");
1128 assert(DTraceMethodProbes, "wrong call");
1129 Symbol* kname = method->klass_name();
1130 Symbol* name = method->name();
1131 Symbol* sig = method->signature();
1132 HOTSPOT_METHOD_RETURN(
1133 get_java_tid(current),
1134 (char *) kname->bytes(), kname->utf8_length(),
1135 (char *) name->bytes(), name->utf8_length(),
1136 (char *) sig->bytes(), sig->utf8_length());
1137 return 0;
1138 JRT_END
1139
1140
1141 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
1142 // for a call current in progress, i.e., arguments has been pushed on stack
1143 // put callee has not been invoked yet. Used by: resolve virtual/static,
1144 // vtable updates, etc. Caller frame must be compiled.
1145 Handle SharedRuntime::find_callee_info(Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
1146 JavaThread* current = THREAD;
1147 ResourceMark rm(current);
1148
1149 // last java frame on stack (which includes native call frames)
1150 vframeStream vfst(current, true); // Do not skip and javaCalls
1151
1152 return find_callee_info_helper(vfst, bc, callinfo, THREAD);
1153 }
1154
1155 Method* SharedRuntime::extract_attached_method(vframeStream& vfst) {
1156 nmethod* caller = vfst.nm();
1157
1158 address pc = vfst.frame_pc();
1159 { // Get call instruction under lock because another thread may be busy patching it.
1160 CompiledICLocker ic_locker(caller);
1161 return caller->attached_method_before_pc(pc);
1162 }
1163 return nullptr;
1164 }
1165
1166 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1167 // for a call current in progress, i.e., arguments has been pushed on stack
1168 // but callee has not been invoked yet. Caller frame must be compiled.
1169 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1170 CallInfo& callinfo, TRAPS) {
1171 Handle receiver;
1172 Handle nullHandle; // create a handy null handle for exception returns
1173 JavaThread* current = THREAD;
1174
1175 assert(!vfst.at_end(), "Java frame must exist");
1176
1177 // Find caller and bci from vframe
1178 methodHandle caller(current, vfst.method());
1179 int bci = vfst.bci();
1180
1181 if (caller->is_continuation_enter_intrinsic()) {
1182 bc = Bytecodes::_invokestatic;
1183 LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1184 return receiver;
1185 }
1186
1187 Bytecode_invoke bytecode(caller, bci);
1188 int bytecode_index = bytecode.index();
1189 bc = bytecode.invoke_code();
1190
1191 methodHandle attached_method(current, extract_attached_method(vfst));
1192 if (attached_method.not_null()) {
1193 Method* callee = bytecode.static_target(CHECK_NH);
1194 vmIntrinsics::ID id = callee->intrinsic_id();
1195 // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1196 // it attaches statically resolved method to the call site.
1197 if (MethodHandles::is_signature_polymorphic(id) &&
1198 MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1199 bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1200
1201 // Adjust invocation mode according to the attached method.
1202 switch (bc) {
1203 case Bytecodes::_invokevirtual:
1204 if (attached_method->method_holder()->is_interface()) {
1205 bc = Bytecodes::_invokeinterface;
1206 }
1207 break;
1208 case Bytecodes::_invokeinterface:
1209 if (!attached_method->method_holder()->is_interface()) {
1210 bc = Bytecodes::_invokevirtual;
1211 }
1212 break;
1213 case Bytecodes::_invokehandle:
1214 if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1215 bc = attached_method->is_static() ? Bytecodes::_invokestatic
1216 : Bytecodes::_invokevirtual;
1217 }
1218 break;
1219 default:
1220 break;
1221 }
1222 }
1223 }
1224
1225 assert(bc != Bytecodes::_illegal, "not initialized");
1226
1227 bool has_receiver = bc != Bytecodes::_invokestatic &&
1228 bc != Bytecodes::_invokedynamic &&
1229 bc != Bytecodes::_invokehandle;
1230
1231 // Find receiver for non-static call
1232 if (has_receiver) {
1233 // This register map must be update since we need to find the receiver for
1234 // compiled frames. The receiver might be in a register.
1235 RegisterMap reg_map2(current,
1236 RegisterMap::UpdateMap::include,
1237 RegisterMap::ProcessFrames::include,
1238 RegisterMap::WalkContinuation::skip);
1239 frame stubFrame = current->last_frame();
1240 // Caller-frame is a compiled frame
1241 frame callerFrame = stubFrame.sender(®_map2);
1242
1243 if (attached_method.is_null()) {
1244 Method* callee = bytecode.static_target(CHECK_NH);
1245 if (callee == nullptr) {
1246 THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1247 }
1248 }
1249
1250 // Retrieve from a compiled argument list
1251 receiver = Handle(current, callerFrame.retrieve_receiver(®_map2));
1252 assert(oopDesc::is_oop_or_null(receiver()), "");
1253
1254 if (receiver.is_null()) {
1255 THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1256 }
1257 }
1258
1259 // Resolve method
1260 if (attached_method.not_null()) {
1261 // Parameterized by attached method.
1262 LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1263 } else {
1264 // Parameterized by bytecode.
1265 constantPoolHandle constants(current, caller->constants());
1266 LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1267 }
1268
1269 #ifdef ASSERT
1270 // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1271 if (has_receiver) {
1272 assert(receiver.not_null(), "should have thrown exception");
1273 Klass* receiver_klass = receiver->klass();
1274 Klass* rk = nullptr;
1275 if (attached_method.not_null()) {
1276 // In case there's resolved method attached, use its holder during the check.
1277 rk = attached_method->method_holder();
1278 } else {
1279 // Klass is already loaded.
1280 constantPoolHandle constants(current, caller->constants());
1281 rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1282 }
1283 Klass* static_receiver_klass = rk;
1284 assert(receiver_klass->is_subtype_of(static_receiver_klass),
1285 "actual receiver must be subclass of static receiver klass");
1286 if (receiver_klass->is_instance_klass()) {
1287 if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1288 tty->print_cr("ERROR: Klass not yet initialized!!");
1289 receiver_klass->print();
1290 }
1291 assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1292 }
1293 }
1294 #endif
1295
1296 return receiver;
1297 }
1298
1299 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1300 JavaThread* current = THREAD;
1301 ResourceMark rm(current);
1302 // We need first to check if any Java activations (compiled, interpreted)
1303 // exist on the stack since last JavaCall. If not, we need
1304 // to get the target method from the JavaCall wrapper.
1305 vframeStream vfst(current, true); // Do not skip any javaCalls
1306 methodHandle callee_method;
1307 if (vfst.at_end()) {
1308 // No Java frames were found on stack since we did the JavaCall.
1309 // Hence the stack can only contain an entry_frame. We need to
1310 // find the target method from the stub frame.
1311 RegisterMap reg_map(current,
1312 RegisterMap::UpdateMap::skip,
1313 RegisterMap::ProcessFrames::include,
1314 RegisterMap::WalkContinuation::skip);
1315 frame fr = current->last_frame();
1316 assert(fr.is_runtime_frame(), "must be a runtimeStub");
1317 fr = fr.sender(®_map);
1318 assert(fr.is_entry_frame(), "must be");
1319 // fr is now pointing to the entry frame.
1320 callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1321 } else {
1322 Bytecodes::Code bc;
1323 CallInfo callinfo;
1324 find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1325 callee_method = methodHandle(current, callinfo.selected_method());
1326 }
1327 assert(callee_method()->is_method(), "must be");
1328 return callee_method;
1329 }
1330
1331 // Resolves a call.
1332 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1333 JavaThread* current = THREAD;
1334 ResourceMark rm(current);
1335 RegisterMap cbl_map(current,
1336 RegisterMap::UpdateMap::skip,
1337 RegisterMap::ProcessFrames::include,
1338 RegisterMap::WalkContinuation::skip);
1339 frame caller_frame = current->last_frame().sender(&cbl_map);
1340
1341 CodeBlob* caller_cb = caller_frame.cb();
1342 guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1343 nmethod* caller_nm = caller_cb->as_nmethod();
1344
1345 // determine call info & receiver
1346 // note: a) receiver is null for static calls
1347 // b) an exception is thrown if receiver is null for non-static calls
1348 CallInfo call_info;
1349 Bytecodes::Code invoke_code = Bytecodes::_illegal;
1350 Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1351
1352 NoSafepointVerifier nsv;
1353
1354 methodHandle callee_method(current, call_info.selected_method());
1355
1356 assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1357 (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1358 (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1359 (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1360 ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1361
1362 assert(!caller_nm->is_unloading(), "It should not be unloading");
1363
1364 #ifndef PRODUCT
1365 // tracing/debugging/statistics
1366 uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1367 (is_virtual) ? (&_resolve_virtual_ctr) :
1368 (&_resolve_static_ctr);
1369 AtomicAccess::inc(addr);
1370
1371 if (TraceCallFixup) {
1372 ResourceMark rm(current);
1373 tty->print("resolving %s%s (%s) call to",
1374 (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1375 Bytecodes::name(invoke_code));
1376 callee_method->print_short_name(tty);
1377 tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1378 p2i(caller_frame.pc()), p2i(callee_method->code()));
1379 }
1380 #endif
1381
1382 if (invoke_code == Bytecodes::_invokestatic) {
1383 assert(callee_method->method_holder()->is_initialized() ||
1384 callee_method->method_holder()->is_reentrant_initialization(current),
1385 "invalid class initialization state for invoke_static");
1386 if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1387 // In order to keep class initialization check, do not patch call
1388 // site for static call when the class is not fully initialized.
1389 // Proper check is enforced by call site re-resolution on every invocation.
1390 //
1391 // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1392 // explicit class initialization check is put in nmethod entry (VEP).
1393 assert(callee_method->method_holder()->is_linked(), "must be");
1394 return callee_method;
1395 }
1396 }
1397
1398
1399 // JSR 292 key invariant:
1400 // If the resolved method is a MethodHandle invoke target, the call
1401 // site must be a MethodHandle call site, because the lambda form might tail-call
1402 // leaving the stack in a state unknown to either caller or callee
1403
1404 // Compute entry points. The computation of the entry points is independent of
1405 // patching the call.
1406
1407 // Make sure the callee nmethod does not get deoptimized and removed before
1408 // we are done patching the code.
1409
1410
1411 CompiledICLocker ml(caller_nm);
1412 if (is_virtual && !is_optimized) {
1413 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1414 inline_cache->update(&call_info, receiver->klass());
1415 } else {
1416 // Callsite is a direct call - set it to the destination method
1417 CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1418 callsite->set(callee_method);
1419 }
1420
1421 return callee_method;
1422 }
1423
1424 // Inline caches exist only in compiled code
1425 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1426 #ifdef ASSERT
1427 RegisterMap reg_map(current,
1428 RegisterMap::UpdateMap::skip,
1429 RegisterMap::ProcessFrames::include,
1430 RegisterMap::WalkContinuation::skip);
1431 frame stub_frame = current->last_frame();
1432 assert(stub_frame.is_runtime_frame(), "sanity check");
1433 frame caller_frame = stub_frame.sender(®_map);
1434 assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1435 #endif /* ASSERT */
1436
1437 methodHandle callee_method;
1438 JRT_BLOCK
1439 callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1440 // Return Method* through TLS
1441 current->set_vm_result_metadata(callee_method());
1442 JRT_BLOCK_END
1443 // return compiled code entry point after potential safepoints
1444 return get_resolved_entry(current, callee_method);
1445 JRT_END
1446
1447
1448 // Handle call site that has been made non-entrant
1449 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1450 // 6243940 We might end up in here if the callee is deoptimized
1451 // as we race to call it. We don't want to take a safepoint if
1452 // the caller was interpreted because the caller frame will look
1453 // interpreted to the stack walkers and arguments are now
1454 // "compiled" so it is much better to make this transition
1455 // invisible to the stack walking code. The i2c path will
1456 // place the callee method in the callee_target. It is stashed
1457 // there because if we try and find the callee by normal means a
1458 // safepoint is possible and have trouble gc'ing the compiled args.
1459 RegisterMap reg_map(current,
1460 RegisterMap::UpdateMap::skip,
1461 RegisterMap::ProcessFrames::include,
1462 RegisterMap::WalkContinuation::skip);
1463 frame stub_frame = current->last_frame();
1464 assert(stub_frame.is_runtime_frame(), "sanity check");
1465 frame caller_frame = stub_frame.sender(®_map);
1466
1467 if (caller_frame.is_interpreted_frame() ||
1468 caller_frame.is_entry_frame() ||
1469 caller_frame.is_upcall_stub_frame()) {
1470 Method* callee = current->callee_target();
1471 guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1472 current->set_vm_result_metadata(callee);
1473 current->set_callee_target(nullptr);
1474 if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1475 // Bypass class initialization checks in c2i when caller is in native.
1476 // JNI calls to static methods don't have class initialization checks.
1477 // Fast class initialization checks are present in c2i adapters and call into
1478 // SharedRuntime::handle_wrong_method() on the slow path.
1479 //
1480 // JVM upcalls may land here as well, but there's a proper check present in
1481 // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1482 // so bypassing it in c2i adapter is benign.
1483 return callee->get_c2i_no_clinit_check_entry();
1484 } else {
1485 return callee->get_c2i_entry();
1486 }
1487 }
1488
1489 // Must be compiled to compiled path which is safe to stackwalk
1490 methodHandle callee_method;
1491 JRT_BLOCK
1492 // Force resolving of caller (if we called from compiled frame)
1493 callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1494 current->set_vm_result_metadata(callee_method());
1495 JRT_BLOCK_END
1496 // return compiled code entry point after potential safepoints
1497 return get_resolved_entry(current, callee_method);
1498 JRT_END
1499
1500 // Handle abstract method call
1501 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1502 // Verbose error message for AbstractMethodError.
1503 // Get the called method from the invoke bytecode.
1504 vframeStream vfst(current, true);
1505 assert(!vfst.at_end(), "Java frame must exist");
1506 methodHandle caller(current, vfst.method());
1507 Bytecode_invoke invoke(caller, vfst.bci());
1508 DEBUG_ONLY( invoke.verify(); )
1509
1510 // Find the compiled caller frame.
1511 RegisterMap reg_map(current,
1512 RegisterMap::UpdateMap::include,
1513 RegisterMap::ProcessFrames::include,
1514 RegisterMap::WalkContinuation::skip);
1515 frame stubFrame = current->last_frame();
1516 assert(stubFrame.is_runtime_frame(), "must be");
1517 frame callerFrame = stubFrame.sender(®_map);
1518 assert(callerFrame.is_compiled_frame(), "must be");
1519
1520 // Install exception and return forward entry.
1521 address res = SharedRuntime::throw_AbstractMethodError_entry();
1522 JRT_BLOCK
1523 methodHandle callee(current, invoke.static_target(current));
1524 if (!callee.is_null()) {
1525 oop recv = callerFrame.retrieve_receiver(®_map);
1526 Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1527 res = StubRoutines::forward_exception_entry();
1528 LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1529 }
1530 JRT_BLOCK_END
1531 return res;
1532 JRT_END
1533
1534 // return verified_code_entry if interp_only_mode is not set for the current thread;
1535 // otherwise return c2i entry.
1536 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1537 if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1538 // In interp_only_mode we need to go to the interpreted entry
1539 // The c2i won't patch in this mode -- see fixup_callers_callsite
1540 return callee_method->get_c2i_entry();
1541 }
1542 assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1543 return callee_method->verified_code_entry();
1544 }
1545
1546 // resolve a static call and patch code
1547 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1548 methodHandle callee_method;
1549 bool enter_special = false;
1550 JRT_BLOCK
1551 callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1552 current->set_vm_result_metadata(callee_method());
1553 JRT_BLOCK_END
1554 // return compiled code entry point after potential safepoints
1555 return get_resolved_entry(current, callee_method);
1556 JRT_END
1557
1558 // resolve virtual call and update inline cache to monomorphic
1559 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1560 methodHandle callee_method;
1561 JRT_BLOCK
1562 callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1563 current->set_vm_result_metadata(callee_method());
1564 JRT_BLOCK_END
1565 // return compiled code entry point after potential safepoints
1566 return get_resolved_entry(current, callee_method);
1567 JRT_END
1568
1569
1570 // Resolve a virtual call that can be statically bound (e.g., always
1571 // monomorphic, so it has no inline cache). Patch code to resolved target.
1572 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1573 methodHandle callee_method;
1574 JRT_BLOCK
1575 callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1576 current->set_vm_result_metadata(callee_method());
1577 JRT_BLOCK_END
1578 // return compiled code entry point after potential safepoints
1579 return get_resolved_entry(current, callee_method);
1580 JRT_END
1581
1582 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1583 JavaThread* current = THREAD;
1584 ResourceMark rm(current);
1585 CallInfo call_info;
1586 Bytecodes::Code bc;
1587
1588 // receiver is null for static calls. An exception is thrown for null
1589 // receivers for non-static calls
1590 Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1591
1592 methodHandle callee_method(current, call_info.selected_method());
1593
1594 #ifndef PRODUCT
1595 AtomicAccess::inc(&_ic_miss_ctr);
1596
1597 // Statistics & Tracing
1598 if (TraceCallFixup) {
1599 ResourceMark rm(current);
1600 tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1601 callee_method->print_short_name(tty);
1602 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1603 }
1604
1605 if (ICMissHistogram) {
1606 MutexLocker m(VMStatistic_lock);
1607 RegisterMap reg_map(current,
1608 RegisterMap::UpdateMap::skip,
1609 RegisterMap::ProcessFrames::include,
1610 RegisterMap::WalkContinuation::skip);
1611 frame f = current->last_frame().real_sender(®_map);// skip runtime stub
1612 // produce statistics under the lock
1613 trace_ic_miss(f.pc());
1614 }
1615 #endif
1616
1617 // install an event collector so that when a vtable stub is created the
1618 // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1619 // event can't be posted when the stub is created as locks are held
1620 // - instead the event will be deferred until the event collector goes
1621 // out of scope.
1622 JvmtiDynamicCodeEventCollector event_collector;
1623
1624 // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1625 RegisterMap reg_map(current,
1626 RegisterMap::UpdateMap::skip,
1627 RegisterMap::ProcessFrames::include,
1628 RegisterMap::WalkContinuation::skip);
1629 frame caller_frame = current->last_frame().sender(®_map);
1630 CodeBlob* cb = caller_frame.cb();
1631 nmethod* caller_nm = cb->as_nmethod();
1632
1633 CompiledICLocker ml(caller_nm);
1634 CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1635 inline_cache->update(&call_info, receiver()->klass());
1636
1637 return callee_method;
1638 }
1639
1640 //
1641 // Resets a call-site in compiled code so it will get resolved again.
1642 // This routines handles both virtual call sites, optimized virtual call
1643 // sites, and static call sites. Typically used to change a call sites
1644 // destination from compiled to interpreted.
1645 //
1646 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1647 JavaThread* current = THREAD;
1648 ResourceMark rm(current);
1649 RegisterMap reg_map(current,
1650 RegisterMap::UpdateMap::skip,
1651 RegisterMap::ProcessFrames::include,
1652 RegisterMap::WalkContinuation::skip);
1653 frame stub_frame = current->last_frame();
1654 assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1655 frame caller = stub_frame.sender(®_map);
1656
1657 // Do nothing if the frame isn't a live compiled frame.
1658 // nmethod could be deoptimized by the time we get here
1659 // so no update to the caller is needed.
1660
1661 if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1662 (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1663
1664 address pc = caller.pc();
1665
1666 nmethod* caller_nm = CodeCache::find_nmethod(pc);
1667 assert(caller_nm != nullptr, "did not find caller nmethod");
1668
1669 // Default call_addr is the location of the "basic" call.
1670 // Determine the address of the call we a reresolving. With
1671 // Inline Caches we will always find a recognizable call.
1672 // With Inline Caches disabled we may or may not find a
1673 // recognizable call. We will always find a call for static
1674 // calls and for optimized virtual calls. For vanilla virtual
1675 // calls it depends on the state of the UseInlineCaches switch.
1676 //
1677 // With Inline Caches disabled we can get here for a virtual call
1678 // for two reasons:
1679 // 1 - calling an abstract method. The vtable for abstract methods
1680 // will run us thru handle_wrong_method and we will eventually
1681 // end up in the interpreter to throw the ame.
1682 // 2 - a racing deoptimization. We could be doing a vanilla vtable
1683 // call and between the time we fetch the entry address and
1684 // we jump to it the target gets deoptimized. Similar to 1
1685 // we will wind up in the interprter (thru a c2i with c2).
1686 //
1687 CompiledICLocker ml(caller_nm);
1688 address call_addr = caller_nm->call_instruction_address(pc);
1689
1690 if (call_addr != nullptr) {
1691 // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1692 // bytes back in the instruction stream so we must also check for reloc info.
1693 RelocIterator iter(caller_nm, call_addr, call_addr+1);
1694 bool ret = iter.next(); // Get item
1695 if (ret) {
1696 switch (iter.type()) {
1697 case relocInfo::static_call_type:
1698 case relocInfo::opt_virtual_call_type: {
1699 CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1700 cdc->set_to_clean();
1701 break;
1702 }
1703
1704 case relocInfo::virtual_call_type: {
1705 // compiled, dispatched call (which used to call an interpreted method)
1706 CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1707 inline_cache->set_to_clean();
1708 break;
1709 }
1710 default:
1711 break;
1712 }
1713 }
1714 }
1715 }
1716
1717 methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1718
1719
1720 #ifndef PRODUCT
1721 AtomicAccess::inc(&_wrong_method_ctr);
1722
1723 if (TraceCallFixup) {
1724 ResourceMark rm(current);
1725 tty->print("handle_wrong_method reresolving call to");
1726 callee_method->print_short_name(tty);
1727 tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1728 }
1729 #endif
1730
1731 return callee_method;
1732 }
1733
1734 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1735 // The faulting unsafe accesses should be changed to throw the error
1736 // synchronously instead. Meanwhile the faulting instruction will be
1737 // skipped over (effectively turning it into a no-op) and an
1738 // asynchronous exception will be raised which the thread will
1739 // handle at a later point. If the instruction is a load it will
1740 // return garbage.
1741
1742 // Request an async exception.
1743 thread->set_pending_unsafe_access_error();
1744
1745 // Return address of next instruction to execute.
1746 return next_pc;
1747 }
1748
1749 #ifdef ASSERT
1750 void SharedRuntime::check_member_name_argument_is_last_argument(const methodHandle& method,
1751 const BasicType* sig_bt,
1752 const VMRegPair* regs) {
1753 ResourceMark rm;
1754 const int total_args_passed = method->size_of_parameters();
1755 const VMRegPair* regs_with_member_name = regs;
1756 VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
1757
1758 const int member_arg_pos = total_args_passed - 1;
1759 assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
1760 assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
1761
1762 java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1);
1763
1764 for (int i = 0; i < member_arg_pos; i++) {
1765 VMReg a = regs_with_member_name[i].first();
1766 VMReg b = regs_without_member_name[i].first();
1767 assert(a->value() == b->value(), "register allocation mismatch: a= %d, b= %d", a->value(), b->value());
1768 }
1769 assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
1770 }
1771 #endif
1772
1773 // ---------------------------------------------------------------------------
1774 // We are calling the interpreter via a c2i. Normally this would mean that
1775 // we were called by a compiled method. However we could have lost a race
1776 // where we went int -> i2c -> c2i and so the caller could in fact be
1777 // interpreted. If the caller is compiled we attempt to patch the caller
1778 // so he no longer calls into the interpreter.
1779 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1780 AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
1781
1782 // It's possible that deoptimization can occur at a call site which hasn't
1783 // been resolved yet, in which case this function will be called from
1784 // an nmethod that has been patched for deopt and we can ignore the
1785 // request for a fixup.
1786 // Also it is possible that we lost a race in that from_compiled_entry
1787 // is now back to the i2c in that case we don't need to patch and if
1788 // we did we'd leap into space because the callsite needs to use
1789 // "to interpreter" stub in order to load up the Method*. Don't
1790 // ask me how I know this...
1791
1792 // Result from nmethod::is_unloading is not stable across safepoints.
1793 NoSafepointVerifier nsv;
1794
1795 nmethod* callee = method->code();
1796 if (callee == nullptr) {
1797 return;
1798 }
1799
1800 // write lock needed because we might patch call site by set_to_clean()
1801 // and is_unloading() can modify nmethod's state
1802 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, JavaThread::current()));
1803
1804 CodeBlob* cb = CodeCache::find_blob(caller_pc);
1805 if (cb == nullptr || !cb->is_nmethod() || !callee->is_in_use() || callee->is_unloading()) {
1806 return;
1807 }
1808
1809 // The check above makes sure this is an nmethod.
1810 nmethod* caller = cb->as_nmethod();
1811
1812 // Get the return PC for the passed caller PC.
1813 address return_pc = caller_pc + frame::pc_return_offset;
1814
1815 if (!caller->is_in_use() || !NativeCall::is_call_before(return_pc)) {
1816 return;
1817 }
1818
1819 // Expect to find a native call there (unless it was no-inline cache vtable dispatch)
1820 CompiledICLocker ic_locker(caller);
1821 ResourceMark rm;
1822
1823 // If we got here through a static call or opt_virtual call, then we know where the
1824 // call address would be; let's peek at it
1825 address callsite_addr = (address)nativeCall_before(return_pc);
1826 RelocIterator iter(caller, callsite_addr, callsite_addr + 1);
1827 if (!iter.next()) {
1828 // No reloc entry found; not a static or optimized virtual call
1829 return;
1830 }
1831
1832 relocInfo::relocType type = iter.reloc()->type();
1833 if (type != relocInfo::static_call_type &&
1834 type != relocInfo::opt_virtual_call_type) {
1835 return;
1836 }
1837
1838 CompiledDirectCall* callsite = CompiledDirectCall::before(return_pc);
1839 callsite->set_to_clean();
1840 JRT_END
1841
1842
1843 // same as JVM_Arraycopy, but called directly from compiled code
1844 JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos,
1845 oopDesc* dest, jint dest_pos,
1846 jint length,
1847 JavaThread* current)) {
1848 #ifndef PRODUCT
1849 _slow_array_copy_ctr++;
1850 #endif
1851 // Check if we have null pointers
1852 if (src == nullptr || dest == nullptr) {
1853 THROW(vmSymbols::java_lang_NullPointerException());
1854 }
1855 // Do the copy. The casts to arrayOop are necessary to the copy_array API,
1856 // even though the copy_array API also performs dynamic checks to ensure
1857 // that src and dest are truly arrays (and are conformable).
1858 // The copy_array mechanism is awkward and could be removed, but
1859 // the compilers don't call this function except as a last resort,
1860 // so it probably doesn't matter.
1861 src->klass()->copy_array((arrayOopDesc*)src, src_pos,
1862 (arrayOopDesc*)dest, dest_pos,
1863 length, current);
1864 }
1865 JRT_END
1866
1867 // The caller of generate_class_cast_message() (or one of its callers)
1868 // must use a ResourceMark in order to correctly free the result.
1869 char* SharedRuntime::generate_class_cast_message(
1870 JavaThread* thread, Klass* caster_klass) {
1871
1872 // Get target class name from the checkcast instruction
1873 vframeStream vfst(thread, true);
1874 assert(!vfst.at_end(), "Java frame must exist");
1875 Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
1876 constantPoolHandle cpool(thread, vfst.method()->constants());
1877 Klass* target_klass = ConstantPool::klass_at_if_loaded(cpool, cc.index());
1878 Symbol* target_klass_name = nullptr;
1879 if (target_klass == nullptr) {
1880 // This klass should be resolved, but just in case, get the name in the klass slot.
1881 target_klass_name = cpool->klass_name_at(cc.index());
1882 }
1883 return generate_class_cast_message(caster_klass, target_klass, target_klass_name);
1884 }
1885
1886
1887 // The caller of generate_class_cast_message() (or one of its callers)
1888 // must use a ResourceMark in order to correctly free the result.
1889 char* SharedRuntime::generate_class_cast_message(
1890 Klass* caster_klass, Klass* target_klass, Symbol* target_klass_name) {
1891 const char* caster_name = caster_klass->external_name();
1892
1893 assert(target_klass != nullptr || target_klass_name != nullptr, "one must be provided");
1894 const char* target_name = target_klass == nullptr ? target_klass_name->as_klass_external_name() :
1895 target_klass->external_name();
1896
1897 size_t msglen = strlen(caster_name) + strlen("class ") + strlen(" cannot be cast to class ") + strlen(target_name) + 1;
1898
1899 const char* caster_klass_description = "";
1900 const char* target_klass_description = "";
1901 const char* klass_separator = "";
1902 if (target_klass != nullptr && caster_klass->module() == target_klass->module()) {
1903 caster_klass_description = caster_klass->joint_in_module_of_loader(target_klass);
1904 } else {
1905 caster_klass_description = caster_klass->class_in_module_of_loader();
1906 target_klass_description = (target_klass != nullptr) ? target_klass->class_in_module_of_loader() : "";
1907 klass_separator = (target_klass != nullptr) ? "; " : "";
1908 }
1909
1910 // add 3 for parenthesis and preceding space
1911 msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
1912
1913 char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
1914 if (message == nullptr) {
1915 // Shouldn't happen, but don't cause even more problems if it does
1916 message = const_cast<char*>(caster_klass->external_name());
1917 } else {
1918 jio_snprintf(message,
1919 msglen,
1920 "class %s cannot be cast to class %s (%s%s%s)",
1921 caster_name,
1922 target_name,
1923 caster_klass_description,
1924 klass_separator,
1925 target_klass_description
1926 );
1927 }
1928 return message;
1929 }
1930
1931 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1932 (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
1933 JRT_END
1934
1935 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1936 if (!SafepointSynchronize::is_synchronizing()) {
1937 // Only try quick_enter() if we're not trying to reach a safepoint
1938 // so that the calling thread reaches the safepoint more quickly.
1939 if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
1940 return;
1941 }
1942 }
1943 // NO_ASYNC required because an async exception on the state transition destructor
1944 // would leave you with the lock held and it would never be released.
1945 // The normal monitorenter NullPointerException is thrown without acquiring a lock
1946 // and the model is that an exception implies the method failed.
1947 JRT_BLOCK_NO_ASYNC
1948 Handle h_obj(THREAD, obj);
1949 ObjectSynchronizer::enter(h_obj, lock, current);
1950 assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
1951 JRT_BLOCK_END
1952 }
1953
1954 // Handles the uncommon case in locking, i.e., contention or an inflated lock.
1955 JRT_BLOCK_ENTRY(void, SharedRuntime::complete_monitor_locking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
1956 SharedRuntime::monitor_enter_helper(obj, lock, current);
1957 JRT_END
1958
1959 void SharedRuntime::monitor_exit_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1960 assert(JavaThread::current() == current, "invariant");
1961 // Exit must be non-blocking, and therefore no exceptions can be thrown.
1962 ExceptionMark em(current);
1963
1964 // Check if C2_MacroAssembler::fast_unlock() or
1965 // C2_MacroAssembler::fast_unlock() unlocked an inflated
1966 // monitor before going slow path. Since there is no safepoint
1967 // polling when calling into the VM, we can be sure that the monitor
1968 // hasn't been deallocated.
1969 ObjectMonitor* m = current->unlocked_inflated_monitor();
1970 if (m != nullptr) {
1971 assert(!m->has_owner(current), "must be");
1972 current->clear_unlocked_inflated_monitor();
1973
1974 // We need to reacquire the lock before we can call ObjectSynchronizer::exit().
1975 if (!m->try_enter(current, /*check_for_recursion*/ false)) {
1976 // Some other thread acquired the lock (or the monitor was
1977 // deflated). Either way we are done.
1978 return;
1979 }
1980 }
1981
1982 // The object could become unlocked through a JNI call, which we have no other checks for.
1983 // Give a fatal message if CheckJNICalls. Otherwise we ignore it.
1984 if (obj->is_unlocked()) {
1985 if (CheckJNICalls) {
1986 fatal("Object has been unlocked by JNI");
1987 }
1988 return;
1989 }
1990 ObjectSynchronizer::exit(obj, lock, current);
1991 }
1992
1993 // Handles the uncommon cases of monitor unlocking in compiled code
1994 JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* obj, BasicLock* lock, JavaThread* current))
1995 assert(current == JavaThread::current(), "pre-condition");
1996 SharedRuntime::monitor_exit_helper(obj, lock, current);
1997 JRT_END
1998
1999 #ifndef PRODUCT
2000
2001 void SharedRuntime::print_statistics() {
2002 ttyLocker ttyl;
2003 if (xtty != nullptr) xtty->head("statistics type='SharedRuntime'");
2004
2005 SharedRuntime::print_ic_miss_histogram();
2006
2007 // Dump the JRT_ENTRY counters
2008 if (_new_instance_ctr) tty->print_cr("%5u new instance requires GC", _new_instance_ctr);
2009 if (_new_array_ctr) tty->print_cr("%5u new array requires GC", _new_array_ctr);
2010 if (_multi2_ctr) tty->print_cr("%5u multianewarray 2 dim", _multi2_ctr);
2011 if (_multi3_ctr) tty->print_cr("%5u multianewarray 3 dim", _multi3_ctr);
2012 if (_multi4_ctr) tty->print_cr("%5u multianewarray 4 dim", _multi4_ctr);
2013 if (_multi5_ctr) tty->print_cr("%5u multianewarray 5 dim", _multi5_ctr);
2014
2015 tty->print_cr("%5u inline cache miss in compiled", _ic_miss_ctr);
2016 tty->print_cr("%5u wrong method", _wrong_method_ctr);
2017 tty->print_cr("%5u unresolved static call site", _resolve_static_ctr);
2018 tty->print_cr("%5u unresolved virtual call site", _resolve_virtual_ctr);
2019 tty->print_cr("%5u unresolved opt virtual call site", _resolve_opt_virtual_ctr);
2020
2021 if (_mon_enter_stub_ctr) tty->print_cr("%5u monitor enter stub", _mon_enter_stub_ctr);
2022 if (_mon_exit_stub_ctr) tty->print_cr("%5u monitor exit stub", _mon_exit_stub_ctr);
2023 if (_mon_enter_ctr) tty->print_cr("%5u monitor enter slow", _mon_enter_ctr);
2024 if (_mon_exit_ctr) tty->print_cr("%5u monitor exit slow", _mon_exit_ctr);
2025 if (_partial_subtype_ctr) tty->print_cr("%5u slow partial subtype", _partial_subtype_ctr);
2026 if (_jbyte_array_copy_ctr) tty->print_cr("%5u byte array copies", _jbyte_array_copy_ctr);
2027 if (_jshort_array_copy_ctr) tty->print_cr("%5u short array copies", _jshort_array_copy_ctr);
2028 if (_jint_array_copy_ctr) tty->print_cr("%5u int array copies", _jint_array_copy_ctr);
2029 if (_jlong_array_copy_ctr) tty->print_cr("%5u long array copies", _jlong_array_copy_ctr);
2030 if (_oop_array_copy_ctr) tty->print_cr("%5u oop array copies", _oop_array_copy_ctr);
2031 if (_checkcast_array_copy_ctr) tty->print_cr("%5u checkcast array copies", _checkcast_array_copy_ctr);
2032 if (_unsafe_array_copy_ctr) tty->print_cr("%5u unsafe array copies", _unsafe_array_copy_ctr);
2033 if (_generic_array_copy_ctr) tty->print_cr("%5u generic array copies", _generic_array_copy_ctr);
2034 if (_slow_array_copy_ctr) tty->print_cr("%5u slow array copies", _slow_array_copy_ctr);
2035 if (_find_handler_ctr) tty->print_cr("%5u find exception handler", _find_handler_ctr);
2036 if (_rethrow_ctr) tty->print_cr("%5u rethrow handler", _rethrow_ctr);
2037 if (_unsafe_set_memory_ctr) tty->print_cr("%5u unsafe set memorys", _unsafe_set_memory_ctr);
2038
2039 AdapterHandlerLibrary::print_statistics();
2040
2041 if (xtty != nullptr) xtty->tail("statistics");
2042 }
2043
2044 inline double percent(int64_t x, int64_t y) {
2045 return 100.0 * (double)x / (double)MAX2(y, (int64_t)1);
2046 }
2047
2048 class MethodArityHistogram {
2049 public:
2050 enum { MAX_ARITY = 256 };
2051 private:
2052 static uint64_t _arity_histogram[MAX_ARITY]; // histogram of #args
2053 static uint64_t _size_histogram[MAX_ARITY]; // histogram of arg size in words
2054 static uint64_t _total_compiled_calls;
2055 static uint64_t _max_compiled_calls_per_method;
2056 static int _max_arity; // max. arity seen
2057 static int _max_size; // max. arg size seen
2058
2059 static void add_method_to_histogram(nmethod* nm) {
2060 Method* method = (nm == nullptr) ? nullptr : nm->method();
2061 if (method != nullptr) {
2062 ArgumentCount args(method->signature());
2063 int arity = args.size() + (method->is_static() ? 0 : 1);
2064 int argsize = method->size_of_parameters();
2065 arity = MIN2(arity, MAX_ARITY-1);
2066 argsize = MIN2(argsize, MAX_ARITY-1);
2067 uint64_t count = (uint64_t)method->compiled_invocation_count();
2068 _max_compiled_calls_per_method = count > _max_compiled_calls_per_method ? count : _max_compiled_calls_per_method;
2069 _total_compiled_calls += count;
2070 _arity_histogram[arity] += count;
2071 _size_histogram[argsize] += count;
2072 _max_arity = MAX2(_max_arity, arity);
2073 _max_size = MAX2(_max_size, argsize);
2074 }
2075 }
2076
2077 void print_histogram_helper(int n, uint64_t* histo, const char* name) {
2078 const int N = MIN2(9, n);
2079 double sum = 0;
2080 double weighted_sum = 0;
2081 for (int i = 0; i <= n; i++) { sum += (double)histo[i]; weighted_sum += (double)(i*histo[i]); }
2082 if (sum >= 1) { // prevent divide by zero or divide overflow
2083 double rest = sum;
2084 double percent = sum / 100;
2085 for (int i = 0; i <= N; i++) {
2086 rest -= (double)histo[i];
2087 tty->print_cr("%4d: " UINT64_FORMAT_W(12) " (%5.1f%%)", i, histo[i], (double)histo[i] / percent);
2088 }
2089 tty->print_cr("rest: " INT64_FORMAT_W(12) " (%5.1f%%)", (int64_t)rest, rest / percent);
2090 tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
2091 tty->print_cr("(total # of compiled calls = " INT64_FORMAT_W(14) ")", _total_compiled_calls);
2092 tty->print_cr("(max # of compiled calls = " INT64_FORMAT_W(14) ")", _max_compiled_calls_per_method);
2093 } else {
2094 tty->print_cr("Histogram generation failed for %s. n = %d, sum = %7.5f", name, n, sum);
2095 }
2096 }
2097
2098 void print_histogram() {
2099 tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
2100 print_histogram_helper(_max_arity, _arity_histogram, "arity");
2101 tty->print_cr("\nHistogram of parameter block size (in words, incl. rcvr):");
2102 print_histogram_helper(_max_size, _size_histogram, "size");
2103 tty->cr();
2104 }
2105
2106 public:
2107 MethodArityHistogram() {
2108 // Take the Compile_lock to protect against changes in the CodeBlob structures
2109 MutexLocker mu1(Compile_lock, Mutex::_safepoint_check_flag);
2110 // Take the CodeCache_lock to protect against changes in the CodeHeap structure
2111 MutexLocker mu2(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2112 _max_arity = _max_size = 0;
2113 _total_compiled_calls = 0;
2114 _max_compiled_calls_per_method = 0;
2115 for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0;
2116 CodeCache::nmethods_do(add_method_to_histogram);
2117 print_histogram();
2118 }
2119 };
2120
2121 uint64_t MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
2122 uint64_t MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
2123 uint64_t MethodArityHistogram::_total_compiled_calls;
2124 uint64_t MethodArityHistogram::_max_compiled_calls_per_method;
2125 int MethodArityHistogram::_max_arity;
2126 int MethodArityHistogram::_max_size;
2127
2128 void SharedRuntime::print_call_statistics(uint64_t comp_total) {
2129 tty->print_cr("Calls from compiled code:");
2130 int64_t total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
2131 int64_t mono_c = _nof_normal_calls - _nof_megamorphic_calls;
2132 int64_t mono_i = _nof_interface_calls;
2133 tty->print_cr("\t" INT64_FORMAT_W(12) " (100%%) total non-inlined ", total);
2134 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total));
2135 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
2136 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_c, percent(mono_c, _nof_normal_calls));
2137 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
2138 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total));
2139 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
2140 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- monomorphic ", mono_i, percent(mono_i, _nof_interface_calls));
2141 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.1f%%) |- static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
2142 tty->print_cr("\t" INT64_FORMAT_W(12) " (%4.0f%%) | |- inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
2143 tty->cr();
2144 tty->print_cr("Note 1: counter updates are not MT-safe.");
2145 tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2146 tty->print_cr(" %% in nested categories are relative to their category");
2147 tty->print_cr(" (and thus add up to more than 100%% with inlining)");
2148 tty->cr();
2149
2150 MethodArityHistogram h;
2151 }
2152 #endif
2153
2154 #ifndef PRODUCT
2155 static int _lookups; // number of calls to lookup
2156 static int _equals; // number of buckets checked with matching hash
2157 static int _archived_hits; // number of successful lookups in archived table
2158 static int _runtime_hits; // number of successful lookups in runtime table
2159 #endif
2160
2161 // A simple wrapper class around the calling convention information
2162 // that allows sharing of adapters for the same calling convention.
2163 class AdapterFingerPrint : public MetaspaceObj {
2164 private:
2165 enum {
2166 _basic_type_bits = 4,
2167 _basic_type_mask = right_n_bits(_basic_type_bits),
2168 _basic_types_per_int = BitsPerInt / _basic_type_bits,
2169 };
2170 // TO DO: Consider integrating this with a more global scheme for compressing signatures.
2171 // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2172
2173 int _length;
2174
2175 static int data_offset() { return sizeof(AdapterFingerPrint); }
2176 int* data_pointer() {
2177 return (int*)((address)this + data_offset());
2178 }
2179
2180 // Private construtor. Use allocate() to get an instance.
2181 AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) {
2182 int* data = data_pointer();
2183 // Pack the BasicTypes with 8 per int
2184 assert(len == length(total_args_passed), "sanity");
2185 _length = len;
2186 int sig_index = 0;
2187 for (int index = 0; index < _length; index++) {
2188 int value = 0;
2189 for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2190 int bt = adapter_encoding(sig_bt[sig_index++]);
2191 assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2192 value = (value << _basic_type_bits) | bt;
2193 }
2194 data[index] = value;
2195 }
2196 }
2197
2198 // Call deallocate instead
2199 ~AdapterFingerPrint() {
2200 ShouldNotCallThis();
2201 }
2202
2203 static int length(int total_args) {
2204 return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int;
2205 }
2206
2207 static int compute_size_in_words(int len) {
2208 return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int)));
2209 }
2210
2211 // Remap BasicTypes that are handled equivalently by the adapters.
2212 // These are correct for the current system but someday it might be
2213 // necessary to make this mapping platform dependent.
2214 static int adapter_encoding(BasicType in) {
2215 switch (in) {
2216 case T_BOOLEAN:
2217 case T_BYTE:
2218 case T_SHORT:
2219 case T_CHAR:
2220 // There are all promoted to T_INT in the calling convention
2221 return T_INT;
2222
2223 case T_OBJECT:
2224 case T_ARRAY:
2225 // In other words, we assume that any register good enough for
2226 // an int or long is good enough for a managed pointer.
2227 #ifdef _LP64
2228 return T_LONG;
2229 #else
2230 return T_INT;
2231 #endif
2232
2233 case T_INT:
2234 case T_LONG:
2235 case T_FLOAT:
2236 case T_DOUBLE:
2237 case T_VOID:
2238 return in;
2239
2240 default:
2241 ShouldNotReachHere();
2242 return T_CONFLICT;
2243 }
2244 }
2245
2246 void* operator new(size_t size, size_t fp_size) throw() {
2247 assert(fp_size >= size, "sanity check");
2248 void* p = AllocateHeap(fp_size, mtCode);
2249 memset(p, 0, fp_size);
2250 return p;
2251 }
2252
2253 template<typename Function>
2254 void iterate_args(Function function) {
2255 for (int i = 0; i < length(); i++) {
2256 unsigned val = (unsigned)value(i);
2257 // args are packed so that first/lower arguments are in the highest
2258 // bits of each int value, so iterate from highest to the lowest
2259 for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2260 unsigned v = (val >> j) & _basic_type_mask;
2261 if (v == 0) {
2262 continue;
2263 }
2264 function(v);
2265 }
2266 }
2267 }
2268
2269 public:
2270 static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2271 int len = length(total_args_passed);
2272 int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2273 AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len);
2274 assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2275 return afp;
2276 }
2277
2278 static void deallocate(AdapterFingerPrint* fp) {
2279 FreeHeap(fp);
2280 }
2281
2282 int value(int index) {
2283 int* data = data_pointer();
2284 return data[index];
2285 }
2286
2287 int length() {
2288 return _length;
2289 }
2290
2291 unsigned int compute_hash() {
2292 int hash = 0;
2293 for (int i = 0; i < length(); i++) {
2294 int v = value(i);
2295 //Add arithmetic operation to the hash, like +3 to improve hashing
2296 hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2297 }
2298 return (unsigned int)hash;
2299 }
2300
2301 const char* as_string() {
2302 stringStream st;
2303 st.print("0x");
2304 for (int i = 0; i < length(); i++) {
2305 st.print("%x", value(i));
2306 }
2307 return st.as_string();
2308 }
2309
2310 const char* as_basic_args_string() {
2311 stringStream st;
2312 bool long_prev = false;
2313 iterate_args([&] (int arg) {
2314 if (long_prev) {
2315 long_prev = false;
2316 if (arg == T_VOID) {
2317 st.print("J");
2318 } else {
2319 st.print("L");
2320 }
2321 }
2322 switch (arg) {
2323 case T_INT: st.print("I"); break;
2324 case T_LONG: long_prev = true; break;
2325 case T_FLOAT: st.print("F"); break;
2326 case T_DOUBLE: st.print("D"); break;
2327 case T_VOID: break;
2328 default: ShouldNotReachHere();
2329 }
2330 });
2331 if (long_prev) {
2332 st.print("L");
2333 }
2334 return st.as_string();
2335 }
2336
2337 BasicType* as_basic_type(int& nargs) {
2338 nargs = 0;
2339 GrowableArray<BasicType> btarray;
2340 bool long_prev = false;
2341
2342 iterate_args([&] (int arg) {
2343 if (long_prev) {
2344 long_prev = false;
2345 if (arg == T_VOID) {
2346 btarray.append(T_LONG);
2347 } else {
2348 btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2349 }
2350 }
2351 switch (arg) {
2352 case T_INT: // fallthrough
2353 case T_FLOAT: // fallthrough
2354 case T_DOUBLE:
2355 case T_VOID:
2356 btarray.append((BasicType)arg);
2357 break;
2358 case T_LONG:
2359 long_prev = true;
2360 break;
2361 default: ShouldNotReachHere();
2362 }
2363 });
2364
2365 if (long_prev) {
2366 btarray.append(T_OBJECT);
2367 }
2368
2369 nargs = btarray.length();
2370 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2371 int index = 0;
2372 GrowableArrayIterator<BasicType> iter = btarray.begin();
2373 while (iter != btarray.end()) {
2374 sig_bt[index++] = *iter;
2375 ++iter;
2376 }
2377 assert(index == btarray.length(), "sanity check");
2378 #ifdef ASSERT
2379 {
2380 AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2381 assert(this->equals(compare_fp), "sanity check");
2382 AdapterFingerPrint::deallocate(compare_fp);
2383 }
2384 #endif
2385 return sig_bt;
2386 }
2387
2388 bool equals(AdapterFingerPrint* other) {
2389 if (other->_length != _length) {
2390 return false;
2391 } else {
2392 for (int i = 0; i < _length; i++) {
2393 if (value(i) != other->value(i)) {
2394 return false;
2395 }
2396 }
2397 }
2398 return true;
2399 }
2400
2401 // methods required by virtue of being a MetaspaceObj
2402 void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2403 int size() const { return compute_size_in_words(_length); }
2404 MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2405
2406 static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2407 NOT_PRODUCT(_equals++);
2408 return fp1->equals(fp2);
2409 }
2410
2411 static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2412 return fp->compute_hash();
2413 }
2414 };
2415
2416 #if INCLUDE_CDS
2417 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2418 return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2419 }
2420
2421 class ArchivedAdapterTable : public OffsetCompactHashtable<
2422 AdapterFingerPrint*,
2423 AdapterHandlerEntry*,
2424 adapter_fp_equals_compact_hashtable_entry> {};
2425 #endif // INCLUDE_CDS
2426
2427 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2428 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2429 AnyObj::C_HEAP, mtCode,
2430 AdapterFingerPrint::compute_hash,
2431 AdapterFingerPrint::equals>;
2432 static AdapterHandlerTable* _adapter_handler_table;
2433 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2434
2435 // Find a entry with the same fingerprint if it exists
2436 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2437 NOT_PRODUCT(_lookups++);
2438 assert_lock_strong(AdapterHandlerLibrary_lock);
2439 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2440 AdapterHandlerEntry* entry = nullptr;
2441 #if INCLUDE_CDS
2442 // if we are building the archive then the archived adapter table is
2443 // not valid and we need to use the ones added to the runtime table
2444 if (AOTCodeCache::is_using_adapter()) {
2445 // Search archived table first. It is read-only table so can be searched without lock
2446 entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2447 #ifndef PRODUCT
2448 if (entry != nullptr) {
2449 _archived_hits++;
2450 }
2451 #endif
2452 }
2453 #endif // INCLUDE_CDS
2454 if (entry == nullptr) {
2455 assert_lock_strong(AdapterHandlerLibrary_lock);
2456 AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2457 if (entry_p != nullptr) {
2458 entry = *entry_p;
2459 assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",
2460 entry->fingerprint()->as_basic_args_string(), entry->fingerprint()->as_string(), entry->fingerprint()->compute_hash(),
2461 fp->as_basic_args_string(), fp->as_string(), fp->compute_hash());
2462 #ifndef PRODUCT
2463 _runtime_hits++;
2464 #endif
2465 }
2466 }
2467 AdapterFingerPrint::deallocate(fp);
2468 return entry;
2469 }
2470
2471 #ifndef PRODUCT
2472 static void print_table_statistics() {
2473 auto size = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* a) {
2474 return sizeof(*key) + sizeof(*a);
2475 };
2476 TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2477 ts.print(tty, "AdapterHandlerTable");
2478 tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2479 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2480 int total_hits = _archived_hits + _runtime_hits;
2481 tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2482 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2483 }
2484 #endif
2485
2486 // ---------------------------------------------------------------------------
2487 // Implementation of AdapterHandlerLibrary
2488 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2489 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2490 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2491 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2492 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2493 #if INCLUDE_CDS
2494 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2495 #endif // INCLUDE_CDS
2496 static const int AdapterHandlerLibrary_size = 16*K;
2497 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2498 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2499
2500 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2501 assert(_buffer != nullptr, "should be initialized");
2502 return _buffer;
2503 }
2504
2505 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2506 if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2507 AdapterBlob* adapter_blob = entry->adapter_blob();
2508 char blob_id[256];
2509 jio_snprintf(blob_id,
2510 sizeof(blob_id),
2511 "%s(%s)",
2512 adapter_blob->name(),
2513 entry->fingerprint()->as_string());
2514 if (Forte::is_enabled()) {
2515 Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2516 }
2517
2518 if (JvmtiExport::should_post_dynamic_code_generated()) {
2519 JvmtiExport::post_dynamic_code_generated(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2520 }
2521 }
2522 }
2523
2524 void AdapterHandlerLibrary::initialize() {
2525 {
2526 ResourceMark rm;
2527 _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2528 _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2529 }
2530
2531 #if INCLUDE_CDS
2532 // Link adapters in AOT Cache to their code in AOT Code Cache
2533 if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2534 link_aot_adapters();
2535 lookup_simple_adapters();
2536 return;
2537 }
2538 #endif // INCLUDE_CDS
2539
2540 ResourceMark rm;
2541 {
2542 MutexLocker mu(AdapterHandlerLibrary_lock);
2543
2544 _no_arg_handler = create_adapter(0, nullptr);
2545
2546 BasicType obj_args[] = { T_OBJECT };
2547 _obj_arg_handler = create_adapter(1, obj_args);
2548
2549 BasicType int_args[] = { T_INT };
2550 _int_arg_handler = create_adapter(1, int_args);
2551
2552 BasicType obj_int_args[] = { T_OBJECT, T_INT };
2553 _obj_int_arg_handler = create_adapter(2, obj_int_args);
2554
2555 BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2556 _obj_obj_arg_handler = create_adapter(2, obj_obj_args);
2557
2558 // we should always get an entry back but we don't have any
2559 // associated blob on Zero
2560 assert(_no_arg_handler != nullptr &&
2561 _obj_arg_handler != nullptr &&
2562 _int_arg_handler != nullptr &&
2563 _obj_int_arg_handler != nullptr &&
2564 _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2565 }
2566
2567 // Outside of the lock
2568 #ifndef ZERO
2569 // no blobs to register when we are on Zero
2570 post_adapter_creation(_no_arg_handler);
2571 post_adapter_creation(_obj_arg_handler);
2572 post_adapter_creation(_int_arg_handler);
2573 post_adapter_creation(_obj_int_arg_handler);
2574 post_adapter_creation(_obj_obj_arg_handler);
2575 #endif // ZERO
2576 }
2577
2578 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2579 uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2580 assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2581 return AdapterHandlerEntry::allocate(id, fingerprint);
2582 }
2583
2584 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2585 int total_args_passed = method->size_of_parameters(); // All args on stack
2586 if (total_args_passed == 0) {
2587 return _no_arg_handler;
2588 } else if (total_args_passed == 1) {
2589 if (!method->is_static()) {
2590 return _obj_arg_handler;
2591 }
2592 switch (method->signature()->char_at(1)) {
2593 case JVM_SIGNATURE_CLASS:
2594 case JVM_SIGNATURE_ARRAY:
2595 return _obj_arg_handler;
2596 case JVM_SIGNATURE_INT:
2597 case JVM_SIGNATURE_BOOLEAN:
2598 case JVM_SIGNATURE_CHAR:
2599 case JVM_SIGNATURE_BYTE:
2600 case JVM_SIGNATURE_SHORT:
2601 return _int_arg_handler;
2602 }
2603 } else if (total_args_passed == 2 &&
2604 !method->is_static()) {
2605 switch (method->signature()->char_at(1)) {
2606 case JVM_SIGNATURE_CLASS:
2607 case JVM_SIGNATURE_ARRAY:
2608 return _obj_obj_arg_handler;
2609 case JVM_SIGNATURE_INT:
2610 case JVM_SIGNATURE_BOOLEAN:
2611 case JVM_SIGNATURE_CHAR:
2612 case JVM_SIGNATURE_BYTE:
2613 case JVM_SIGNATURE_SHORT:
2614 return _obj_int_arg_handler;
2615 }
2616 }
2617 return nullptr;
2618 }
2619
2620 class AdapterSignatureIterator : public SignatureIterator {
2621 private:
2622 BasicType stack_sig_bt[16];
2623 BasicType* sig_bt;
2624 int index;
2625
2626 public:
2627 AdapterSignatureIterator(Symbol* signature,
2628 fingerprint_t fingerprint,
2629 bool is_static,
2630 int total_args_passed) :
2631 SignatureIterator(signature, fingerprint),
2632 index(0)
2633 {
2634 sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2635 if (!is_static) { // Pass in receiver first
2636 sig_bt[index++] = T_OBJECT;
2637 }
2638 do_parameters_on(this);
2639 }
2640
2641 BasicType* basic_types() {
2642 return sig_bt;
2643 }
2644
2645 #ifdef ASSERT
2646 int slots() {
2647 return index;
2648 }
2649 #endif
2650
2651 private:
2652
2653 friend class SignatureIterator; // so do_parameters_on can call do_type
2654 void do_type(BasicType type) {
2655 sig_bt[index++] = type;
2656 if (type == T_LONG || type == T_DOUBLE) {
2657 sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots
2658 }
2659 }
2660 };
2661
2662
2663 const char* AdapterHandlerEntry::_entry_names[] = {
2664 "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2665 };
2666
2667 #ifdef ASSERT
2668 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2669 // we can only check for the same code if there is any
2670 #ifndef ZERO
2671 AdapterHandlerEntry* comparison_entry = create_adapter(total_args_passed, sig_bt, true);
2672 assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
2673 assert(comparison_entry->compare_code(cached_entry), "code must match");
2674 // Release the one just created
2675 AdapterHandlerEntry::deallocate(comparison_entry);
2676 # endif // ZERO
2677 }
2678 #endif /* ASSERT*/
2679
2680 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2681 assert(!method->is_abstract(), "abstract methods do not have adapters");
2682 // Use customized signature handler. Need to lock around updates to
2683 // the _adapter_handler_table (it is not safe for concurrent readers
2684 // and a single writer: this could be fixed if it becomes a
2685 // problem).
2686
2687 // Fast-path for trivial adapters
2688 AdapterHandlerEntry* entry = get_simple_adapter(method);
2689 if (entry != nullptr) {
2690 return entry;
2691 }
2692
2693 ResourceMark rm;
2694 bool new_entry = false;
2695
2696 // Fill in the signature array, for the calling-convention call.
2697 int total_args_passed = method->size_of_parameters(); // All args on stack
2698
2699 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2700 method->is_static(), total_args_passed);
2701 assert(si.slots() == total_args_passed, "");
2702 BasicType* sig_bt = si.basic_types();
2703 {
2704 MutexLocker mu(AdapterHandlerLibrary_lock);
2705
2706 // Lookup method signature's fingerprint
2707 entry = lookup(total_args_passed, sig_bt);
2708
2709 if (entry != nullptr) {
2710 #ifndef ZERO
2711 assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2712 #endif
2713 #ifdef ASSERT
2714 if (!entry->in_aot_cache() && VerifyAdapterSharing) {
2715 verify_adapter_sharing(total_args_passed, sig_bt, entry);
2716 }
2717 #endif
2718 } else {
2719 entry = create_adapter(total_args_passed, sig_bt);
2720 if (entry != nullptr) {
2721 new_entry = true;
2722 }
2723 }
2724 }
2725
2726 // Outside of the lock
2727 if (new_entry) {
2728 post_adapter_creation(entry);
2729 }
2730 return entry;
2731 }
2732
2733 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2734 ResourceMark rm;
2735 const char* name = AdapterHandlerLibrary::name(handler);
2736 const uint32_t id = AdapterHandlerLibrary::id(handler);
2737
2738 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
2739 if (blob != nullptr) {
2740 handler->set_adapter_blob(blob->as_adapter_blob());
2741 }
2742 }
2743
2744 #ifndef PRODUCT
2745 void AdapterHandlerLibrary::print_adapter_handler_info(outputStream* st, AdapterHandlerEntry* handler) {
2746 ttyLocker ttyl;
2747 ResourceMark rm;
2748 int insts_size;
2749 // on Zero the blob may be null
2750 handler->print_adapter_on(tty);
2751 AdapterBlob* adapter_blob = handler->adapter_blob();
2752 if (adapter_blob == nullptr) {
2753 return;
2754 }
2755 insts_size = adapter_blob->code_size();
2756 st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2757 handler->fingerprint()->as_basic_args_string(),
2758 handler->fingerprint()->as_string(), insts_size);
2759 st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2760 if (Verbose || PrintStubCode) {
2761 address first_pc = adapter_blob->content_begin();
2762 if (first_pc != nullptr) {
2763 Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2764 st->cr();
2765 }
2766 }
2767 }
2768 #endif // PRODUCT
2769
2770 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
2771 int entry_offset[AdapterBlob::ENTRY_COUNT]) {
2772 entry_offset[AdapterBlob::I2C] = 0;
2773 entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];
2774 entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];
2775 if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
2776 entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
2777 } else {
2778 entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
2779 }
2780 }
2781
2782 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
2783 int total_args_passed,
2784 BasicType* sig_bt,
2785 bool is_transient) {
2786 if (log_is_enabled(Info, perf, class, link)) {
2787 ClassLoader::perf_method_adapters_count()->inc();
2788 }
2789
2790 #ifndef ZERO
2791 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2792 CodeBuffer buffer(buf);
2793 short buffer_locs[20];
2794 buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2795 sizeof(buffer_locs)/sizeof(relocInfo));
2796 MacroAssembler masm(&buffer);
2797 VMRegPair stack_regs[16];
2798 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2799
2800 // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2801 int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2802 address entry_address[AdapterBlob::ENTRY_COUNT];
2803 SharedRuntime::generate_i2c2i_adapters(&masm,
2804 total_args_passed,
2805 comp_args_on_stack,
2806 sig_bt,
2807 regs,
2808 entry_address);
2809 // On zero there is no code to save and no need to create a blob and
2810 // or relocate the handler.
2811 int entry_offset[AdapterBlob::ENTRY_COUNT];
2812 address_to_offset(entry_address, entry_offset);
2813 #ifdef ASSERT
2814 if (VerifyAdapterSharing) {
2815 handler->save_code(buf->code_begin(), buffer.insts_size());
2816 if (is_transient) {
2817 return true;
2818 }
2819 }
2820 #endif
2821 AdapterBlob* adapter_blob = AdapterBlob::create(&buffer, entry_offset);
2822 if (adapter_blob == nullptr) {
2823 // CodeCache is full, disable compilation
2824 // Ought to log this but compile log is only per compile thread
2825 // and we're some non descript Java thread.
2826 return false;
2827 }
2828 handler->set_adapter_blob(adapter_blob);
2829 if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
2830 // try to save generated code
2831 const char* name = AdapterHandlerLibrary::name(handler);
2832 const uint32_t id = AdapterHandlerLibrary::id(handler);
2833 bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
2834 assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
2835 }
2836 #endif // ZERO
2837
2838 #ifndef PRODUCT
2839 // debugging support
2840 if (PrintAdapterHandlers || PrintStubCode) {
2841 print_adapter_handler_info(tty, handler);
2842 }
2843 #endif
2844
2845 return true;
2846 }
2847
2848 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(int total_args_passed,
2849 BasicType* sig_bt,
2850 bool is_transient) {
2851 AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2852 AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2853 if (!generate_adapter_code(handler, total_args_passed, sig_bt, is_transient)) {
2854 AdapterHandlerEntry::deallocate(handler);
2855 return nullptr;
2856 }
2857 if (!is_transient) {
2858 assert_lock_strong(AdapterHandlerLibrary_lock);
2859 _adapter_handler_table->put(fp, handler);
2860 }
2861 return handler;
2862 }
2863
2864 #if INCLUDE_CDS
2865 void AdapterHandlerEntry::remove_unshareable_info() {
2866 #ifdef ASSERT
2867 _saved_code = nullptr;
2868 _saved_code_length = 0;
2869 #endif // ASSERT
2870 _adapter_blob = nullptr;
2871 _linked = false;
2872 }
2873
2874 class CopyAdapterTableToArchive : StackObj {
2875 private:
2876 CompactHashtableWriter* _writer;
2877 ArchiveBuilder* _builder;
2878 public:
2879 CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
2880 _builder(ArchiveBuilder::current())
2881 {}
2882
2883 bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
2884 LogStreamHandle(Trace, aot) lsh;
2885 if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
2886 assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
2887 AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
2888 assert(buffered_fp != nullptr,"sanity check");
2889 AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
2890 assert(buffered_entry != nullptr,"sanity check");
2891
2892 uint hash = fp->compute_hash();
2893 _writer->add(hash, AOTCompressedPointers::encode_not_null(buffered_entry));
2894 if (lsh.is_enabled()) {
2895 address fp_runtime_addr = (address)buffered_fp + ArchiveBuilder::current()->buffer_to_requested_delta();
2896 address entry_runtime_addr = (address)buffered_entry + ArchiveBuilder::current()->buffer_to_requested_delta();
2897 log_trace(aot)("Added fp=%p (%s), entry=%p to the archived adater table", buffered_fp, buffered_fp->as_basic_args_string(), buffered_entry);
2898 }
2899 } else {
2900 if (lsh.is_enabled()) {
2901 log_trace(aot)("Skipping adapter handler %p (fp=%s) as it is not archived", entry, fp->as_basic_args_string());
2902 }
2903 }
2904 return true;
2905 }
2906 };
2907
2908 void AdapterHandlerLibrary::dump_aot_adapter_table() {
2909 CompactHashtableStats stats;
2910 CompactHashtableWriter writer(_adapter_handler_table->number_of_entries(), &stats);
2911 CopyAdapterTableToArchive copy(&writer);
2912 _adapter_handler_table->iterate(©);
2913 writer.dump(&_aot_adapter_handler_table, "archived adapter table");
2914 }
2915
2916 void AdapterHandlerLibrary::serialize_shared_table_header(SerializeClosure* soc) {
2917 _aot_adapter_handler_table.serialize_header(soc);
2918 }
2919
2920 void AdapterHandlerLibrary::link_aot_adapter_handler(AdapterHandlerEntry* handler) {
2921 #ifdef ASSERT
2922 if (TestAOTAdapterLinkFailure) {
2923 return;
2924 }
2925 #endif
2926 lookup_aot_cache(handler);
2927 #ifndef PRODUCT
2928 // debugging support
2929 if (PrintAdapterHandlers || PrintStubCode) {
2930 print_adapter_handler_info(tty, handler);
2931 }
2932 #endif
2933 }
2934
2935 // This method is used during production run to link archived adapters (stored in AOT Cache)
2936 // to their code in AOT Code Cache
2937 void AdapterHandlerEntry::link() {
2938 ResourceMark rm;
2939 assert(_fingerprint != nullptr, "_fingerprint must not be null");
2940 bool generate_code = false;
2941 // Generate code only if AOTCodeCache is not available, or
2942 // caching adapters is disabled, or we fail to link
2943 // the AdapterHandlerEntry to its code in the AOTCodeCache
2944 if (AOTCodeCache::is_using_adapter()) {
2945 AdapterHandlerLibrary::link_aot_adapter_handler(this);
2946 // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
2947 if (_adapter_blob == nullptr) {
2948 log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
2949 generate_code = true;
2950 }
2951 } else {
2952 generate_code = true;
2953 }
2954 if (generate_code) {
2955 int nargs;
2956 BasicType* bt = _fingerprint->as_basic_type(nargs);
2957 if (!AdapterHandlerLibrary::generate_adapter_code(this, nargs, bt, /* is_transient */ false)) {
2958 // Don't throw exceptions during VM initialization because java.lang.* classes
2959 // might not have been initialized, causing problems when constructing the
2960 // Java exception object.
2961 vm_exit_during_initialization("Out of space in CodeCache for adapters");
2962 }
2963 }
2964 if (_adapter_blob != nullptr) {
2965 post_adapter_creation(this);
2966 }
2967 assert(_linked, "AdapterHandlerEntry must now be linked");
2968 }
2969
2970 void AdapterHandlerLibrary::link_aot_adapters() {
2971 uint max_id = 0;
2972 assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
2973 /* It is possible that some adapters generated in assembly phase are not stored in the cache.
2974 * That implies adapter ids of the adapters in the cache may not be contiguous.
2975 * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
2976 * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
2977 * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
2978 */
2979 _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
2980 assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
2981 entry->link();
2982 max_id = MAX2(max_id, entry->id());
2983 });
2984 // Set adapter id to the maximum id found in the AOTCache
2985 assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
2986 _id_counter = max_id;
2987 }
2988
2989 // This method is called during production run to lookup simple adapters
2990 // in the archived adapter handler table
2991 void AdapterHandlerLibrary::lookup_simple_adapters() {
2992 assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
2993
2994 MutexLocker mu(AdapterHandlerLibrary_lock);
2995 _no_arg_handler = lookup(0, nullptr);
2996
2997 BasicType obj_args[] = { T_OBJECT };
2998 _obj_arg_handler = lookup(1, obj_args);
2999
3000 BasicType int_args[] = { T_INT };
3001 _int_arg_handler = lookup(1, int_args);
3002
3003 BasicType obj_int_args[] = { T_OBJECT, T_INT };
3004 _obj_int_arg_handler = lookup(2, obj_int_args);
3005
3006 BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3007 _obj_obj_arg_handler = lookup(2, obj_obj_args);
3008
3009 assert(_no_arg_handler != nullptr &&
3010 _obj_arg_handler != nullptr &&
3011 _int_arg_handler != nullptr &&
3012 _obj_int_arg_handler != nullptr &&
3013 _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3014 assert(_no_arg_handler->is_linked() &&
3015 _obj_arg_handler->is_linked() &&
3016 _int_arg_handler->is_linked() &&
3017 _obj_int_arg_handler->is_linked() &&
3018 _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3019 }
3020 #endif // INCLUDE_CDS
3021
3022 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3023 LogStreamHandle(Trace, aot) lsh;
3024 if (lsh.is_enabled()) {
3025 lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3026 lsh.cr();
3027 }
3028 it->push(&_fingerprint);
3029 }
3030
3031 AdapterHandlerEntry::~AdapterHandlerEntry() {
3032 if (_fingerprint != nullptr) {
3033 AdapterFingerPrint::deallocate(_fingerprint);
3034 _fingerprint = nullptr;
3035 }
3036 #ifdef ASSERT
3037 FREE_C_HEAP_ARRAY(_saved_code);
3038 #endif
3039 FreeHeap(this);
3040 }
3041
3042
3043 #ifdef ASSERT
3044 // Capture the code before relocation so that it can be compared
3045 // against other versions. If the code is captured after relocation
3046 // then relative instructions won't be equivalent.
3047 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3048 _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3049 _saved_code_length = length;
3050 memcpy(_saved_code, buffer, length);
3051 }
3052
3053
3054 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3055 assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");
3056
3057 if (other->_saved_code_length != _saved_code_length) {
3058 return false;
3059 }
3060
3061 return memcmp(other->_saved_code, _saved_code, _saved_code_length) == 0;
3062 }
3063 #endif
3064
3065
3066 /**
3067 * Create a native wrapper for this native method. The wrapper converts the
3068 * Java-compiled calling convention to the native convention, handles
3069 * arguments, and transitions to native. On return from the native we transition
3070 * back to java blocking if a safepoint is in progress.
3071 */
3072 void AdapterHandlerLibrary::create_native_wrapper(const methodHandle& method) {
3073 ResourceMark rm;
3074 nmethod* nm = nullptr;
3075
3076 // Check if memory should be freed before allocation
3077 CodeCache::gc_on_allocation();
3078
3079 assert(method->is_native(), "must be native");
3080 assert(method->is_special_native_intrinsic() ||
3081 method->has_native_function(), "must have something valid to call!");
3082
3083 {
3084 // Perform the work while holding the lock, but perform any printing outside the lock
3085 MutexLocker mu(AdapterHandlerLibrary_lock);
3086 // See if somebody beat us to it
3087 if (method->code() != nullptr) {
3088 return;
3089 }
3090
3091 const int compile_id = CompileBroker::assign_compile_id(method, CompileBroker::standard_entry_bci);
3092 assert(compile_id > 0, "Must generate native wrapper");
3093
3094
3095 ResourceMark rm;
3096 BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3097 if (buf != nullptr) {
3098 CodeBuffer buffer(buf);
3099
3100 if (method->is_continuation_enter_intrinsic()) {
3101 buffer.initialize_stubs_size(192);
3102 }
3103
3104 struct { double data[20]; } locs_buf;
3105 struct { double data[20]; } stubs_locs_buf;
3106 buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3107 #if defined(AARCH64) || defined(PPC64)
3108 // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3109 // in the constant pool to ensure ordering between the barrier and oops
3110 // accesses. For native_wrappers we need a constant.
3111 // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3112 // static java call that is resolved in the runtime.
3113 if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3114 buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3115 }
3116 #endif
3117 buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3118 MacroAssembler _masm(&buffer);
3119
3120 // Fill in the signature array, for the calling-convention call.
3121 const int total_args_passed = method->size_of_parameters();
3122
3123 VMRegPair stack_regs[16];
3124 VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3125
3126 AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3127 method->is_static(), total_args_passed);
3128 BasicType* sig_bt = si.basic_types();
3129 assert(si.slots() == total_args_passed, "");
3130 BasicType ret_type = si.return_type();
3131
3132 // Now get the compiled-Java arguments layout.
3133 SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3134
3135 // Generate the compiled-to-native wrapper code
3136 nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3137
3138 if (nm != nullptr) {
3139 {
3140 MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3141 if (nm->make_in_use()) {
3142 method->set_code(method, nm);
3143 }
3144 }
3145
3146 CompilerDirectiveMatcher matcher(method, CompLevel_simple);
3147 if (matcher.directive_set()->PrintAssemblyOption) {
3148 nm->print_code();
3149 }
3150 }
3151 }
3152 } // Unlock AdapterHandlerLibrary_lock
3153
3154
3155 // Install the generated code.
3156 if (nm != nullptr) {
3157 const char *msg = method->is_static() ? "(static)" : "";
3158 CompileTask::print_ul(nm, msg);
3159 if (PrintCompilation) {
3160 ttyLocker ttyl;
3161 CompileTask::print(tty, nm, msg);
3162 }
3163 nm->post_compiled_method_load_event();
3164 }
3165 }
3166
3167 // -------------------------------------------------------------------------
3168 // Java-Java calling convention
3169 // (what you use when Java calls Java)
3170
3171 //------------------------------name_for_receiver----------------------------------
3172 // For a given signature, return the VMReg for parameter 0.
3173 VMReg SharedRuntime::name_for_receiver() {
3174 VMRegPair regs;
3175 BasicType sig_bt = T_OBJECT;
3176 (void) java_calling_convention(&sig_bt, ®s, 1);
3177 // Return argument 0 register. In the LP64 build pointers
3178 // take 2 registers, but the VM wants only the 'main' name.
3179 return regs.first();
3180 }
3181
3182 VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, bool has_appendix, int* arg_size) {
3183 // This method is returning a data structure allocating as a
3184 // ResourceObject, so do not put any ResourceMarks in here.
3185
3186 BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256);
3187 VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256);
3188 int cnt = 0;
3189 if (has_receiver) {
3190 sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
3191 }
3192
3193 for (SignatureStream ss(sig); !ss.at_return_type(); ss.next()) {
3194 BasicType type = ss.type();
3195 sig_bt[cnt++] = type;
3196 if (is_double_word_type(type))
3197 sig_bt[cnt++] = T_VOID;
3198 }
3199
3200 if (has_appendix) {
3201 sig_bt[cnt++] = T_OBJECT;
3202 }
3203
3204 assert(cnt < 256, "grow table size");
3205
3206 int comp_args_on_stack;
3207 comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt);
3208
3209 // the calling convention doesn't count out_preserve_stack_slots so
3210 // we must add that in to get "true" stack offsets.
3211
3212 if (comp_args_on_stack) {
3213 for (int i = 0; i < cnt; i++) {
3214 VMReg reg1 = regs[i].first();
3215 if (reg1->is_stack()) {
3216 // Yuck
3217 reg1 = reg1->bias(out_preserve_stack_slots());
3218 }
3219 VMReg reg2 = regs[i].second();
3220 if (reg2->is_stack()) {
3221 // Yuck
3222 reg2 = reg2->bias(out_preserve_stack_slots());
3223 }
3224 regs[i].set_pair(reg2, reg1);
3225 }
3226 }
3227
3228 // results
3229 *arg_size = cnt;
3230 return regs;
3231 }
3232
3233 // OSR Migration Code
3234 //
3235 // This code is used convert interpreter frames into compiled frames. It is
3236 // called from very start of a compiled OSR nmethod. A temp array is
3237 // allocated to hold the interesting bits of the interpreter frame. All
3238 // active locks are inflated to allow them to move. The displaced headers and
3239 // active interpreter locals are copied into the temp buffer. Then we return
3240 // back to the compiled code. The compiled code then pops the current
3241 // interpreter frame off the stack and pushes a new compiled frame. Then it
3242 // copies the interpreter locals and displaced headers where it wants.
3243 // Finally it calls back to free the temp buffer.
3244 //
3245 // All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
3246
3247 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *current) )
3248 assert(current == JavaThread::current(), "pre-condition");
3249 JFR_ONLY(Jfr::check_and_process_sample_request(current);)
3250 // During OSR migration, we unwind the interpreted frame and replace it with a compiled
3251 // frame. The stack watermark code below ensures that the interpreted frame is processed
3252 // before it gets unwound. This is helpful as the size of the compiled frame could be
3253 // larger than the interpreted frame, which could result in the new frame not being
3254 // processed correctly.
3255 StackWatermarkSet::before_unwind(current);
3256
3257 //
3258 // This code is dependent on the memory layout of the interpreter local
3259 // array and the monitors. On all of our platforms the layout is identical
3260 // so this code is shared. If some platform lays the their arrays out
3261 // differently then this code could move to platform specific code or
3262 // the code here could be modified to copy items one at a time using
3263 // frame accessor methods and be platform independent.
3264
3265 frame fr = current->last_frame();
3266 assert(fr.is_interpreted_frame(), "");
3267 assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks");
3268
3269 // Figure out how many monitors are active.
3270 int active_monitor_count = 0;
3271 for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
3272 kptr < fr.interpreter_frame_monitor_begin();
3273 kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
3274 if (kptr->obj() != nullptr) active_monitor_count++;
3275 }
3276
3277 // QQQ we could place number of active monitors in the array so that compiled code
3278 // could double check it.
3279
3280 Method* moop = fr.interpreter_frame_method();
3281 int max_locals = moop->max_locals();
3282 // Allocate temp buffer, 1 word per local & 2 per active monitor
3283 int buf_size_words = max_locals + active_monitor_count * BasicObjectLock::size();
3284 intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
3285
3286 // Copy the locals. Order is preserved so that loading of longs works.
3287 // Since there's no GC I can copy the oops blindly.
3288 assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
3289 Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
3290 (HeapWord*)&buf[0],
3291 max_locals);
3292
3293 // Inflate locks. Copy the displaced headers. Be careful, there can be holes.
3294 int i = max_locals;
3295 for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
3296 kptr2 < fr.interpreter_frame_monitor_begin();
3297 kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
3298 if (kptr2->obj() != nullptr) { // Avoid 'holes' in the monitor array
3299 BasicLock *lock = kptr2->lock();
3300 if (UseObjectMonitorTable) {
3301 buf[i] = (intptr_t)lock->object_monitor_cache();
3302 }
3303 #ifdef ASSERT
3304 else {
3305 buf[i] = badDispHeaderOSR;
3306 }
3307 #endif
3308 i++;
3309 buf[i++] = cast_from_oop<intptr_t>(kptr2->obj());
3310 }
3311 }
3312 assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors");
3313
3314 RegisterMap map(current,
3315 RegisterMap::UpdateMap::skip,
3316 RegisterMap::ProcessFrames::include,
3317 RegisterMap::WalkContinuation::skip);
3318 frame sender = fr.sender(&map);
3319 if (sender.is_interpreted_frame()) {
3320 current->push_cont_fastpath(sender.unextended_sp());
3321 }
3322
3323 return buf;
3324 JRT_END
3325
3326 JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
3327 FREE_C_HEAP_ARRAY(buf);
3328 JRT_END
3329
3330 const char* AdapterHandlerLibrary::name(AdapterHandlerEntry* handler) {
3331 return handler->fingerprint()->as_basic_args_string();
3332 }
3333
3334 uint32_t AdapterHandlerLibrary::id(AdapterHandlerEntry* handler) {
3335 return handler->id();
3336 }
3337
3338 void AdapterHandlerLibrary::print_handler_on(outputStream* st, const CodeBlob* b) {
3339 bool found = false;
3340 #if INCLUDE_CDS
3341 if (AOTCodeCache::is_using_adapter()) {
3342 auto findblob_archived_table = [&] (AdapterHandlerEntry* handler) {
3343 if (b == handler->adapter_blob()) {
3344 found = true;
3345 st->print("Adapter for signature: ");
3346 handler->print_adapter_on(st);
3347 return false; // abort iteration
3348 } else {
3349 return true; // keep looking
3350 }
3351 };
3352 _aot_adapter_handler_table.iterate(findblob_archived_table);
3353 }
3354 #endif // INCLUDE_CDS
3355 if (!found) {
3356 auto findblob_runtime_table = [&] (AdapterFingerPrint* key, AdapterHandlerEntry* handler) {
3357 if (b == handler->adapter_blob()) {
3358 found = true;
3359 st->print("Adapter for signature: ");
3360 handler->print_adapter_on(st);
3361 return false; // abort iteration
3362 } else {
3363 return true; // keep looking
3364 }
3365 };
3366 assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3367 _adapter_handler_table->iterate(findblob_runtime_table);
3368 }
3369 assert(found, "Should have found handler");
3370 }
3371
3372 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3373 st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3374 if (adapter_blob() != nullptr) {
3375 st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3376 st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3377 st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3378 if (get_c2i_no_clinit_check_entry() != nullptr) {
3379 st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3380 }
3381 }
3382 st->cr();
3383 }
3384
3385 #ifndef PRODUCT
3386
3387 void AdapterHandlerLibrary::print_statistics() {
3388 print_table_statistics();
3389 }
3390
3391 #endif /* PRODUCT */
3392
3393 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3394 assert(current == JavaThread::current(), "pre-condition");
3395 StackOverflow* overflow_state = current->stack_overflow_state();
3396 overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3397 overflow_state->set_reserved_stack_activation(current->stack_base());
3398 JRT_END
3399
3400 frame SharedRuntime::look_for_reserved_stack_annotated_method(JavaThread* current, frame fr) {
3401 ResourceMark rm(current);
3402 frame activation;
3403 nmethod* nm = nullptr;
3404 int count = 1;
3405
3406 assert(fr.is_java_frame(), "Must start on Java frame");
3407
3408 RegisterMap map(JavaThread::current(),
3409 RegisterMap::UpdateMap::skip,
3410 RegisterMap::ProcessFrames::skip,
3411 RegisterMap::WalkContinuation::skip); // don't walk continuations
3412 for (; !fr.is_first_frame(); fr = fr.sender(&map)) {
3413 if (!fr.is_java_frame()) {
3414 continue;
3415 }
3416
3417 Method* method = nullptr;
3418 bool found = false;
3419 if (fr.is_interpreted_frame()) {
3420 method = fr.interpreter_frame_method();
3421 if (method != nullptr && method->has_reserved_stack_access()) {
3422 found = true;
3423 }
3424 } else {
3425 CodeBlob* cb = fr.cb();
3426 if (cb != nullptr && cb->is_nmethod()) {
3427 nm = cb->as_nmethod();
3428 method = nm->method();
3429 for (ScopeDesc *sd = nm->scope_desc_near(fr.pc()); sd != nullptr; sd = sd->sender()) {
3430 method = sd->method();
3431 if (method != nullptr && method->has_reserved_stack_access()) {
3432 found = true;
3433 }
3434 }
3435 }
3436 }
3437 if (found) {
3438 activation = fr;
3439 warning("Potentially dangerous stack overflow in "
3440 "ReservedStackAccess annotated method %s [%d]",
3441 method->name_and_sig_as_C_string(), count++);
3442 EventReservedStackActivation event;
3443 if (event.should_commit()) {
3444 event.set_method(method);
3445 event.commit();
3446 }
3447 }
3448 }
3449 return activation;
3450 }
3451
3452 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3453 // After any safepoint, just before going back to compiled code,
3454 // we inform the GC that we will be doing initializing writes to
3455 // this object in the future without emitting card-marks, so
3456 // GC may take any compensating steps.
3457
3458 oop new_obj = current->vm_result_oop();
3459 if (new_obj == nullptr) return;
3460
3461 BarrierSet *bs = BarrierSet::barrier_set();
3462 bs->on_slowpath_allocation_exit(current, new_obj);
3463 }