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