1 /*
2 * Copyright (c) 1999, 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 "asm/codeBuffer.hpp"
26 #include "c1/c1_CodeStubs.hpp"
27 #include "c1/c1_Defs.hpp"
28 #include "c1/c1_LIRAssembler.hpp"
29 #include "c1/c1_MacroAssembler.hpp"
30 #include "c1/c1_Runtime1.hpp"
31 #include "classfile/javaClasses.inline.hpp"
32 #include "classfile/vmClasses.hpp"
33 #include "classfile/vmSymbols.hpp"
34 #include "code/aotCodeCache.hpp"
35 #include "code/codeBlob.hpp"
36 #include "code/compiledIC.hpp"
37 #include "code/scopeDesc.hpp"
38 #include "code/vtableStubs.hpp"
39 #include "compiler/compilationPolicy.hpp"
40 #include "compiler/disassembler.hpp"
41 #include "compiler/oopMap.hpp"
42 #include "gc/shared/barrierSet.hpp"
43 #include "gc/shared/c1/barrierSetC1.hpp"
44 #include "gc/shared/collectedHeap.hpp"
45 #include "interpreter/bytecode.hpp"
46 #include "interpreter/interpreter.hpp"
47 #include "jfr/support/jfrIntrinsics.hpp"
48 #include "logging/log.hpp"
49 #include "memory/oopFactory.hpp"
50 #include "memory/resourceArea.hpp"
51 #include "memory/universe.hpp"
52 #include "oops/access.inline.hpp"
53 #include "oops/objArrayKlass.hpp"
54 #include "oops/objArrayOop.inline.hpp"
55 #include "oops/oop.inline.hpp"
56 #include "prims/jvmtiExport.hpp"
57 #include "runtime/atomicAccess.hpp"
58 #include "runtime/fieldDescriptor.inline.hpp"
59 #include "runtime/frame.inline.hpp"
60 #include "runtime/handles.inline.hpp"
61 #include "runtime/interfaceSupport.inline.hpp"
62 #include "runtime/javaCalls.hpp"
63 #include "runtime/sharedRuntime.hpp"
64 #include "runtime/stackWatermarkSet.hpp"
65 #include "runtime/stubInfo.hpp"
66 #include "runtime/stubRoutines.hpp"
67 #include "runtime/vframe.inline.hpp"
68 #include "runtime/vframeArray.hpp"
69 #include "runtime/vm_version.hpp"
70 #include "utilities/copy.hpp"
71 #include "utilities/events.hpp"
72
73
74 // Implementation of StubAssembler
75
76 StubAssembler::StubAssembler(CodeBuffer* code, const char * name, int stub_id) : C1_MacroAssembler(code) {
77 _name = name;
78 _must_gc_arguments = false;
79 _frame_size = no_frame_size;
80 _num_rt_args = 0;
81 _stub_id = stub_id;
82 }
83
84
85 void StubAssembler::set_info(const char* name, bool must_gc_arguments) {
86 _name = name;
87 _must_gc_arguments = must_gc_arguments;
88 }
89
90
91 void StubAssembler::set_frame_size(int size) {
92 if (_frame_size == no_frame_size) {
93 _frame_size = size;
94 }
95 assert(_frame_size == size, "can't change the frame size");
96 }
97
98
99 void StubAssembler::set_num_rt_args(int args) {
100 if (_num_rt_args == 0) {
101 _num_rt_args = args;
102 }
103 assert(_num_rt_args == args, "can't change the number of args");
104 }
105
106 // Implementation of Runtime1
107 CodeBlob* Runtime1::_blobs[StubInfo::C1_STUB_COUNT];
108
109 #ifndef PRODUCT
110 // statistics
111 uint Runtime1::_generic_arraycopystub_cnt = 0;
112 uint Runtime1::_arraycopy_slowcase_cnt = 0;
113 uint Runtime1::_arraycopy_checkcast_cnt = 0;
114 uint Runtime1::_arraycopy_checkcast_attempt_cnt = 0;
115 uint Runtime1::_new_type_array_slowcase_cnt = 0;
116 uint Runtime1::_new_object_array_slowcase_cnt = 0;
117 uint Runtime1::_new_instance_slowcase_cnt = 0;
118 uint Runtime1::_new_multi_array_slowcase_cnt = 0;
119 uint Runtime1::_monitorenter_slowcase_cnt = 0;
120 uint Runtime1::_monitorexit_slowcase_cnt = 0;
121 uint Runtime1::_patch_code_slowcase_cnt = 0;
122 uint Runtime1::_throw_range_check_exception_count = 0;
123 uint Runtime1::_throw_index_exception_count = 0;
124 uint Runtime1::_throw_div0_exception_count = 0;
125 uint Runtime1::_throw_null_pointer_exception_count = 0;
126 uint Runtime1::_throw_class_cast_exception_count = 0;
127 uint Runtime1::_throw_incompatible_class_change_error_count = 0;
128 uint Runtime1::_throw_count = 0;
129
130 static uint _byte_arraycopy_stub_cnt = 0;
131 static uint _short_arraycopy_stub_cnt = 0;
132 static uint _int_arraycopy_stub_cnt = 0;
133 static uint _long_arraycopy_stub_cnt = 0;
134 static uint _oop_arraycopy_stub_cnt = 0;
135
136 address Runtime1::arraycopy_count_address(BasicType type) {
137 switch (type) {
138 case T_BOOLEAN:
139 case T_BYTE: return (address)&_byte_arraycopy_stub_cnt;
140 case T_CHAR:
141 case T_SHORT: return (address)&_short_arraycopy_stub_cnt;
142 case T_FLOAT:
143 case T_INT: return (address)&_int_arraycopy_stub_cnt;
144 case T_DOUBLE:
145 case T_LONG: return (address)&_long_arraycopy_stub_cnt;
146 case T_ARRAY:
147 case T_OBJECT: return (address)&_oop_arraycopy_stub_cnt;
148 default:
149 ShouldNotReachHere();
150 return nullptr;
151 }
152 }
153
154
155 #endif
156
157 // Simple helper to see if the caller of a runtime stub which
158 // entered the VM has been deoptimized
159
160 static bool caller_is_deopted(JavaThread* current) {
161 RegisterMap reg_map(current,
162 RegisterMap::UpdateMap::skip,
163 RegisterMap::ProcessFrames::include,
164 RegisterMap::WalkContinuation::skip);
165 frame runtime_frame = current->last_frame();
166 frame caller_frame = runtime_frame.sender(®_map);
167 assert(caller_frame.is_compiled_frame(), "must be compiled");
168 return caller_frame.is_deoptimized_frame();
169 }
170
171 // Stress deoptimization
172 static void deopt_caller(JavaThread* current) {
173 if (!caller_is_deopted(current)) {
174 RegisterMap reg_map(current,
175 RegisterMap::UpdateMap::skip,
176 RegisterMap::ProcessFrames::include,
177 RegisterMap::WalkContinuation::skip);
178 frame runtime_frame = current->last_frame();
179 frame caller_frame = runtime_frame.sender(®_map);
180 Deoptimization::deoptimize_frame(current, caller_frame.id());
181 assert(caller_is_deopted(current), "Must be deoptimized");
182 }
183 }
184
185 class C1StubAssemblerCodeGenClosure: public StubAssemblerCodeGenClosure {
186 private:
187 StubId _id;
188 public:
189 C1StubAssemblerCodeGenClosure(StubId id) : _id(id) {
190 assert(StubInfo::is_c1(_id), "not a c1 stub id %s", StubInfo::name(_id));
191 }
192 virtual OopMapSet* generate_code(StubAssembler* sasm) {
193 return Runtime1::generate_code_for(_id, sasm);
194 }
195 };
196
197 CodeBlob* Runtime1::generate_blob(BufferBlob* buffer_blob, StubId id, const char* name, bool expect_oop_map, StubAssemblerCodeGenClosure* cl) {
198 if (id != StubId::NO_STUBID) {
199 CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::C1Blob, StubInfo::blob(id));
200 if (blob != nullptr) {
201 return blob;
202 }
203 }
204
205 ResourceMark rm;
206 // create code buffer for code storage
207 CodeBuffer code(buffer_blob);
208
209 OopMapSet* oop_maps;
210 int frame_size;
211 bool must_gc_arguments;
212
213 Compilation::setup_code_buffer(&code, 0);
214
215 // create assembler for code generation
216 StubAssembler* sasm = new StubAssembler(&code, name, (int)id);
217 // generate code for runtime stub
218 oop_maps = cl->generate_code(sasm);
219 assert(oop_maps == nullptr || sasm->frame_size() != no_frame_size,
220 "if stub has an oop map it must have a valid frame size");
221 assert(!expect_oop_map || oop_maps != nullptr, "must have an oopmap");
222
223 // align so printing shows nop's instead of random code at the end (SimpleStubs are aligned)
224 sasm->align(BytesPerWord);
225 // make sure all code is in code buffer
226 sasm->flush();
227
228 frame_size = sasm->frame_size();
229 must_gc_arguments = sasm->must_gc_arguments();
230 // create blob - distinguish a few special cases
231 CodeBlob* blob = RuntimeStub::new_runtime_stub(name,
232 &code,
233 CodeOffsets::frame_never_safe,
234 frame_size,
235 oop_maps,
236 must_gc_arguments,
237 false /* alloc_fail_is_fatal */ );
238 if (blob != nullptr && (int)id >= 0) {
239 AOTCodeCache::store_code_blob(*blob, AOTCodeEntry::C1Blob, StubInfo::blob(id));
240 }
241 return blob;
242 }
243
244 bool Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubId id) {
245 assert(StubInfo::is_c1(id), "not a c1 stub %s", StubInfo::name(id));
246 bool expect_oop_map = true;
247 #ifdef ASSERT
248 // Make sure that stubs that need oopmaps have them
249 switch (id) {
250 // These stubs don't need to have an oopmap
251 case StubId::c1_dtrace_object_alloc_id:
252 case StubId::c1_slow_subtype_check_id:
253 case StubId::c1_fpu2long_stub_id:
254 case StubId::c1_unwind_exception_id:
255 case StubId::c1_counter_overflow_id:
256 case StubId::c1_is_instance_of_id:
257 expect_oop_map = false;
258 break;
259 default:
260 break;
261 }
262 #endif
263 C1StubAssemblerCodeGenClosure cl(id);
264 CodeBlob* blob = generate_blob(buffer_blob, id, name_for(id), expect_oop_map, &cl);
265 // install blob
266 int idx = StubInfo::c1_offset(id); // will assert on non-c1 id
267 _blobs[idx] = blob;
268 return blob != nullptr;
269 }
270
271 bool Runtime1::initialize(BufferBlob* blob) {
272 // platform-dependent initialization
273 initialize_pd();
274 // iterate blobs in C1 group and generate a single stub per blob
275 StubId id = StubInfo::stub_base(StubGroup::C1);
276 StubId limit = StubInfo::next(StubInfo::stub_max(StubGroup::C1));
277 for (; id != limit; id = StubInfo::next(id)) {
278 if (!generate_blob_for(blob, id)) {
279 return false;
280 }
281 }
282 // disallow any further c1 stub generation
283 AOTCodeCache::set_c1_stubs_complete();
284 // printing
285 #ifndef PRODUCT
286 if (PrintSimpleStubs) {
287 ResourceMark rm;
288 id = StubInfo::stub_base(StubGroup::C1);
289 for (; id != limit; id = StubInfo::next(id)) {
290 CodeBlob* blob = blob_for(id);
291 blob->print();
292 if (blob->oop_maps() != nullptr) {
293 blob->oop_maps()->print();
294 }
295 }
296 }
297 #endif
298 BarrierSetC1* bs = BarrierSet::barrier_set()->barrier_set_c1();
299 return bs->generate_c1_runtime_stubs(blob);
300 }
301
302 CodeBlob* Runtime1::blob_for(StubId id) {
303 int idx = StubInfo::c1_offset(id); // will assert on non-c1 id
304 return _blobs[idx];
305 }
306
307
308 const char* Runtime1::name_for(StubId id) {
309 return StubInfo::name(id);
310 }
311
312 const char* Runtime1::name_for_address(address entry) {
313 // iterate stubs starting from C1 group base
314 StubId id = StubInfo::stub_base(StubGroup::C1);
315 StubId limit = StubInfo::next(StubInfo::stub_max(StubGroup::C1));
316 for (; id != limit; id = StubInfo::next(id)) {
317 if (entry == entry_for(id)) return StubInfo::name(id);
318 }
319
320 #define FUNCTION_CASE(a, f) \
321 if ((intptr_t)a == CAST_FROM_FN_PTR(intptr_t, f)) return #f
322
323 FUNCTION_CASE(entry, os::javaTimeMillis);
324 FUNCTION_CASE(entry, os::javaTimeNanos);
325 FUNCTION_CASE(entry, SharedRuntime::OSR_migration_end);
326 FUNCTION_CASE(entry, SharedRuntime::d2f);
327 FUNCTION_CASE(entry, SharedRuntime::d2i);
328 FUNCTION_CASE(entry, SharedRuntime::d2l);
329 FUNCTION_CASE(entry, SharedRuntime::dcos);
330 FUNCTION_CASE(entry, SharedRuntime::dexp);
331 FUNCTION_CASE(entry, SharedRuntime::dlog);
332 FUNCTION_CASE(entry, SharedRuntime::dlog10);
333 FUNCTION_CASE(entry, SharedRuntime::dpow);
334 FUNCTION_CASE(entry, SharedRuntime::drem);
335 FUNCTION_CASE(entry, SharedRuntime::dsin);
336 FUNCTION_CASE(entry, SharedRuntime::dtan);
337 FUNCTION_CASE(entry, SharedRuntime::f2i);
338 FUNCTION_CASE(entry, SharedRuntime::f2l);
339 FUNCTION_CASE(entry, SharedRuntime::frem);
340 FUNCTION_CASE(entry, SharedRuntime::l2d);
341 FUNCTION_CASE(entry, SharedRuntime::l2f);
342 FUNCTION_CASE(entry, SharedRuntime::ldiv);
343 FUNCTION_CASE(entry, SharedRuntime::lmul);
344 FUNCTION_CASE(entry, SharedRuntime::lrem);
345 FUNCTION_CASE(entry, SharedRuntime::lrem);
346 FUNCTION_CASE(entry, SharedRuntime::dtrace_method_entry);
347 FUNCTION_CASE(entry, SharedRuntime::dtrace_method_exit);
348 FUNCTION_CASE(entry, is_instance_of);
349 FUNCTION_CASE(entry, trace_block_entry);
350 #ifdef JFR_HAVE_INTRINSICS
351 FUNCTION_CASE(entry, JfrTime::time_function());
352 #endif
353 FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32());
354 FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32C());
355 FUNCTION_CASE(entry, StubRoutines::vectorizedMismatch());
356 FUNCTION_CASE(entry, StubRoutines::dexp());
357 FUNCTION_CASE(entry, StubRoutines::dlog());
358 FUNCTION_CASE(entry, StubRoutines::dlog10());
359 FUNCTION_CASE(entry, StubRoutines::dpow());
360 FUNCTION_CASE(entry, StubRoutines::dsin());
361 FUNCTION_CASE(entry, StubRoutines::dcos());
362 FUNCTION_CASE(entry, StubRoutines::dtan());
363 FUNCTION_CASE(entry, StubRoutines::dsinh());
364 FUNCTION_CASE(entry, StubRoutines::dtanh());
365 FUNCTION_CASE(entry, StubRoutines::dcbrt());
366
367 #undef FUNCTION_CASE
368
369 // Soft float adds more runtime names.
370 return pd_name_for_address(entry);
371 }
372
373
374 JRT_ENTRY(void, Runtime1::new_instance(JavaThread* current, Klass* klass))
375 #ifndef PRODUCT
376 if (PrintC1Statistics) {
377 _new_instance_slowcase_cnt++;
378 }
379 #endif
380 assert(klass->is_klass(), "not a class");
381 Handle holder(current, klass->klass_holder()); // keep the klass alive
382 InstanceKlass* h = InstanceKlass::cast(klass);
383 h->check_valid_for_instantiation(true, CHECK);
384 // make sure klass is initialized
385 h->initialize(CHECK);
386 // allocate instance and return via TLS
387 oop obj = h->allocate_instance(CHECK);
388 current->set_vm_result_oop(obj);
389 JRT_END
390
391
392 JRT_ENTRY(void, Runtime1::new_type_array(JavaThread* current, Klass* klass, jint length))
393 #ifndef PRODUCT
394 if (PrintC1Statistics) {
395 _new_type_array_slowcase_cnt++;
396 }
397 #endif
398 // Note: no handle for klass needed since they are not used
399 // anymore after new_typeArray() and no GC can happen before.
400 // (This may have to change if this code changes!)
401 assert(klass->is_klass(), "not a class");
402 BasicType elt_type = TypeArrayKlass::cast(klass)->element_type();
403 oop obj = oopFactory::new_typeArray(elt_type, length, CHECK);
404 current->set_vm_result_oop(obj);
405 // This is pretty rare but this runtime patch is stressful to deoptimization
406 // if we deoptimize here so force a deopt to stress the path.
407 if (DeoptimizeALot) {
408 deopt_caller(current);
409 }
410
411 JRT_END
412
413
414 JRT_ENTRY(void, Runtime1::new_object_array(JavaThread* current, Klass* array_klass, jint length))
415 #ifndef PRODUCT
416 if (PrintC1Statistics) {
417 _new_object_array_slowcase_cnt++;
418 }
419 #endif
420 // Note: no handle for klass needed since they are not used
421 // anymore after new_objArray() and no GC can happen before.
422 // (This may have to change if this code changes!)
423 assert(array_klass->is_klass(), "not a class");
424 Handle holder(current, array_klass->klass_holder()); // keep the klass alive
425 Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
426 objArrayOop obj = oopFactory::new_objArray(elem_klass, length, CHECK);
427 current->set_vm_result_oop(obj);
428 // This is pretty rare but this runtime patch is stressful to deoptimization
429 // if we deoptimize here so force a deopt to stress the path.
430 if (DeoptimizeALot) {
431 deopt_caller(current);
432 }
433 JRT_END
434
435
436 JRT_ENTRY(void, Runtime1::new_multi_array(JavaThread* current, Klass* klass, int rank, jint* dims))
437 #ifndef PRODUCT
438 if (PrintC1Statistics) {
439 _new_multi_array_slowcase_cnt++;
440 }
441 #endif
442 assert(klass->is_klass(), "not a class");
443 assert(rank >= 1, "rank must be nonzero");
444 Handle holder(current, klass->klass_holder()); // keep the klass alive
445 oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
446 current->set_vm_result_oop(obj);
447 JRT_END
448
449
450 JRT_ENTRY(void, Runtime1::unimplemented_entry(JavaThread* current, StubId id))
451 tty->print_cr("Runtime1::entry_for(%d) returned unimplemented entry point", (int)id);
452 JRT_END
453
454
455 JRT_ENTRY(void, Runtime1::throw_array_store_exception(JavaThread* current, oopDesc* obj))
456 ResourceMark rm(current);
457 const char* klass_name = obj->klass()->external_name();
458 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayStoreException(), klass_name);
459 JRT_END
460
461
462 // counter_overflow() is called from within C1-compiled methods. The enclosing method is the method
463 // associated with the top activation record. The inlinee (that is possibly included in the enclosing
464 // method) method is passed as an argument. In order to do that it is embedded in the code as
465 // a constant.
466 static nmethod* counter_overflow_helper(JavaThread* current, int branch_bci, Method* m) {
467 nmethod* osr_nm = nullptr;
468 methodHandle method(current, m);
469
470 RegisterMap map(current,
471 RegisterMap::UpdateMap::skip,
472 RegisterMap::ProcessFrames::include,
473 RegisterMap::WalkContinuation::skip);
474 frame fr = current->last_frame().sender(&map);
475 nmethod* nm = (nmethod*) fr.cb();
476 assert(nm!= nullptr && nm->is_nmethod(), "Sanity check");
477 methodHandle enclosing_method(current, nm->method());
478
479 CompLevel level = (CompLevel)nm->comp_level();
480 int bci = InvocationEntryBci;
481 if (branch_bci != InvocationEntryBci) {
482 // Compute destination bci
483 address pc = method()->code_base() + branch_bci;
484 Bytecodes::Code branch = Bytecodes::code_at(method(), pc);
485 int offset = 0;
486 switch (branch) {
487 case Bytecodes::_if_icmplt: case Bytecodes::_iflt:
488 case Bytecodes::_if_icmpgt: case Bytecodes::_ifgt:
489 case Bytecodes::_if_icmple: case Bytecodes::_ifle:
490 case Bytecodes::_if_icmpge: case Bytecodes::_ifge:
491 case Bytecodes::_if_icmpeq: case Bytecodes::_if_acmpeq: case Bytecodes::_ifeq:
492 case Bytecodes::_if_icmpne: case Bytecodes::_if_acmpne: case Bytecodes::_ifne:
493 case Bytecodes::_ifnull: case Bytecodes::_ifnonnull: case Bytecodes::_goto:
494 offset = (int16_t)Bytes::get_Java_u2(pc + 1);
495 break;
496 case Bytecodes::_goto_w:
497 offset = Bytes::get_Java_u4(pc + 1);
498 break;
499 default: ;
500 }
501 bci = branch_bci + offset;
502 }
503 osr_nm = CompilationPolicy::event(enclosing_method, method, branch_bci, bci, level, nm, current);
504 return osr_nm;
505 }
506
507 JRT_BLOCK_ENTRY(address, Runtime1::counter_overflow(JavaThread* current, int bci, Method* method))
508 nmethod* osr_nm;
509 JRT_BLOCK_NO_ASYNC
510 osr_nm = counter_overflow_helper(current, bci, method);
511 if (osr_nm != nullptr) {
512 RegisterMap map(current,
513 RegisterMap::UpdateMap::skip,
514 RegisterMap::ProcessFrames::include,
515 RegisterMap::WalkContinuation::skip);
516 frame fr = current->last_frame().sender(&map);
517 Deoptimization::deoptimize_frame(current, fr.id());
518 }
519 JRT_BLOCK_END
520 return nullptr;
521 JRT_END
522
523 extern void vm_exit(int code);
524
525 // Enter this method from compiled code handler below. This is where we transition
526 // to VM mode. This is done as a helper routine so that the method called directly
527 // from compiled code does not have to transition to VM. This allows the entry
528 // method to see if the nmethod that we have just looked up a handler for has
529 // been deoptimized while we were in the vm. This simplifies the assembly code
530 // cpu directories.
531 //
532 // We are entering here from exception stub (via the entry method below)
533 // If there is a compiled exception handler in this method, we will continue there;
534 // otherwise we will unwind the stack and continue at the caller of top frame method
535 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
536 // control the area where we can allow a safepoint. After we exit the safepoint area we can
537 // check to see if the handler we are going to return is now in a nmethod that has
538 // been deoptimized. If that is the case we return the deopt blob
539 // unpack_with_exception entry instead. This makes life for the exception blob easier
540 // because making that same check and diverting is painful from assembly language.
541 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* current, oopDesc* ex, address pc, nmethod*& nm))
542 MACOS_AARCH64_ONLY(current->wx_enable_write());
543 Handle exception(current, ex);
544
545 // This function is called when we are about to throw an exception. Therefore,
546 // we have to poll the stack watermark barrier to make sure that not yet safe
547 // stack frames are made safe before returning into them.
548 if (current->last_frame().cb() == Runtime1::blob_for(StubId::c1_handle_exception_from_callee_id)) {
549 // The StubId::c1_handle_exception_from_callee_id handler is invoked after the
550 // frame has been unwound. It instead builds its own stub frame, to call the
551 // runtime. But the throwing frame has already been unwound here.
552 StackWatermarkSet::after_unwind(current);
553 }
554
555 nm = CodeCache::find_nmethod(pc);
556 assert(nm != nullptr, "this is not an nmethod");
557 // Adjust the pc as needed/
558 if (nm->is_deopt_pc(pc)) {
559 RegisterMap map(current,
560 RegisterMap::UpdateMap::skip,
561 RegisterMap::ProcessFrames::include,
562 RegisterMap::WalkContinuation::skip);
563 frame exception_frame = current->last_frame().sender(&map);
564 // if the frame isn't deopted then pc must not correspond to the caller of last_frame
565 assert(exception_frame.is_deoptimized_frame(), "must be deopted");
566 pc = exception_frame.pc();
567 }
568 assert(exception.not_null(), "null exceptions should be handled by throw_exception");
569 // Check that exception is a subclass of Throwable
570 assert(exception->is_a(vmClasses::Throwable_klass()),
571 "Exception not subclass of Throwable");
572
573 // debugging support
574 // tracing
575 if (log_is_enabled(Info, exceptions)) {
576 ResourceMark rm; // print_value_string
577 stringStream tempst;
578 assert(nm->method() != nullptr, "Unexpected null method()");
579 tempst.print("C1 compiled method <%s>\n"
580 " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
581 nm->method()->print_value_string(), p2i(pc), p2i(current));
582 Exceptions::log_exception(exception, tempst.freeze());
583 }
584 // for AbortVMOnException flag
585 Exceptions::debug_check_abort(exception);
586
587 // Check the stack guard pages and re-enable them if necessary and there is
588 // enough space on the stack to do so. Use fast exceptions only if the guard
589 // pages are enabled.
590 bool guard_pages_enabled = current->stack_overflow_state()->reguard_stack_if_needed();
591
592 if (JvmtiExport::can_post_on_exceptions()) {
593 // To ensure correct notification of exception catches and throws
594 // we have to deoptimize here. If we attempted to notify the
595 // catches and throws during this exception lookup it's possible
596 // we could deoptimize on the way out of the VM and end back in
597 // the interpreter at the throw site. This would result in double
598 // notifications since the interpreter would also notify about
599 // these same catches and throws as it unwound the frame.
600
601 RegisterMap reg_map(current,
602 RegisterMap::UpdateMap::include,
603 RegisterMap::ProcessFrames::include,
604 RegisterMap::WalkContinuation::skip);
605 frame stub_frame = current->last_frame();
606 frame caller_frame = stub_frame.sender(®_map);
607
608 // We don't really want to deoptimize the nmethod itself since we
609 // can actually continue in the exception handler ourselves but I
610 // don't see an easy way to have the desired effect.
611 Deoptimization::deoptimize_frame(current, caller_frame.id());
612 assert(caller_is_deopted(current), "Must be deoptimized");
613
614 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
615 }
616
617 // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
618 if (guard_pages_enabled) {
619 address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
620 if (fast_continuation != nullptr) {
621 return fast_continuation;
622 }
623 }
624
625 // If the stack guard pages are enabled, check whether there is a handler in
626 // the current method. Otherwise (guard pages disabled), force an unwind and
627 // skip the exception cache update (i.e., just leave continuation as null).
628 address continuation = nullptr;
629 if (guard_pages_enabled) {
630
631 // New exception handling mechanism can support inlined methods
632 // with exception handlers since the mappings are from PC to PC
633
634 // Clear out the exception oop and pc since looking up an
635 // exception handler can cause class loading, which might throw an
636 // exception and those fields are expected to be clear during
637 // normal bytecode execution.
638 current->clear_exception_oop_and_pc();
639
640 bool recursive_exception = false;
641 continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false, recursive_exception);
642 // If an exception was thrown during exception dispatch, the exception oop may have changed
643 current->set_exception_oop(exception());
644 current->set_exception_pc(pc);
645
646 // the exception cache is used only by non-implicit exceptions
647 // Update the exception cache only when there didn't happen
648 // another exception during the computation of the compiled
649 // exception handler. Checking for exception oop equality is not
650 // sufficient because some exceptions are pre-allocated and reused.
651 if (continuation != nullptr && !recursive_exception) {
652 nm->add_handler_for_exception_and_pc(exception, pc, continuation);
653 }
654 }
655
656 current->set_vm_result_oop(exception());
657
658 if (log_is_enabled(Info, exceptions)) {
659 ResourceMark rm;
660 log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
661 " for exception thrown at PC " PTR_FORMAT,
662 p2i(current), p2i(continuation), p2i(pc));
663 }
664
665 return continuation;
666 JRT_END
667
668 // Enter this method from compiled code only if there is a Java exception handler
669 // in the method handling the exception.
670 // We are entering here from exception stub. We don't do a normal VM transition here.
671 // We do it in a helper. This is so we can check to see if the nmethod we have just
672 // searched for an exception handler has been deoptimized in the meantime.
673 address Runtime1::exception_handler_for_pc(JavaThread* current) {
674 oop exception = current->exception_oop();
675 address pc = current->exception_pc();
676 // Still in Java mode
677 DEBUG_ONLY(NoHandleMark nhm);
678 nmethod* nm = nullptr;
679 address continuation = nullptr;
680 {
681 // Enter VM mode by calling the helper
682 ResetNoHandleMark rnhm;
683 continuation = exception_handler_for_pc_helper(current, exception, pc, nm);
684 }
685 // Back in JAVA, use no oops DON'T safepoint
686
687 // Now check to see if the nmethod we were called from is now deoptimized.
688 // If so we must return to the deopt blob and deoptimize the nmethod
689 if (nm != nullptr && caller_is_deopted(current)) {
690 continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
691 }
692
693 assert(continuation != nullptr, "no handler found");
694 return continuation;
695 }
696
697
698 JRT_ENTRY(void, Runtime1::throw_range_check_exception(JavaThread* current, int index, arrayOopDesc* a))
699 #ifndef PRODUCT
700 if (PrintC1Statistics) {
701 _throw_range_check_exception_count++;
702 }
703 #endif
704 const int len = 35;
705 assert(len < strlen("Index %d out of bounds for length %d"), "Must allocate more space for message.");
706 char message[2 * jintAsStringSize + len];
707 os::snprintf_checked(message, sizeof(message), "Index %d out of bounds for length %d", index, a->length());
708 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
709 JRT_END
710
711
712 JRT_ENTRY(void, Runtime1::throw_index_exception(JavaThread* current, int index))
713 #ifndef PRODUCT
714 if (PrintC1Statistics) {
715 _throw_index_exception_count++;
716 }
717 #endif
718 char message[16];
719 os::snprintf_checked(message, sizeof(message), "%d", index);
720 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IndexOutOfBoundsException(), message);
721 JRT_END
722
723
724 JRT_ENTRY(void, Runtime1::throw_div0_exception(JavaThread* current))
725 #ifndef PRODUCT
726 if (PrintC1Statistics) {
727 _throw_div0_exception_count++;
728 }
729 #endif
730 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
731 JRT_END
732
733
734 JRT_ENTRY(void, Runtime1::throw_null_pointer_exception(JavaThread* current))
735 #ifndef PRODUCT
736 if (PrintC1Statistics) {
737 _throw_null_pointer_exception_count++;
738 }
739 #endif
740 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_NullPointerException());
741 JRT_END
742
743
744 JRT_ENTRY(void, Runtime1::throw_class_cast_exception(JavaThread* current, oopDesc* object))
745 #ifndef PRODUCT
746 if (PrintC1Statistics) {
747 _throw_class_cast_exception_count++;
748 }
749 #endif
750 ResourceMark rm(current);
751 char* message = SharedRuntime::generate_class_cast_message(current, object->klass());
752 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_ClassCastException(), message);
753 JRT_END
754
755
756 JRT_ENTRY(void, Runtime1::throw_incompatible_class_change_error(JavaThread* current))
757 #ifndef PRODUCT
758 if (PrintC1Statistics) {
759 _throw_incompatible_class_change_error_count++;
760 }
761 #endif
762 ResourceMark rm(current);
763 SharedRuntime::throw_and_post_jvmti_exception(current, vmSymbols::java_lang_IncompatibleClassChangeError());
764 JRT_END
765
766
767 JRT_BLOCK_ENTRY(void, Runtime1::monitorenter(JavaThread* current, oopDesc* obj, BasicObjectLock* lock))
768 #ifndef PRODUCT
769 if (PrintC1Statistics) {
770 _monitorenter_slowcase_cnt++;
771 }
772 #endif
773 assert(obj == lock->obj(), "must match");
774 SharedRuntime::monitor_enter_helper(obj, lock->lock(), current);
775 JRT_END
776
777
778 JRT_LEAF(void, Runtime1::monitorexit(JavaThread* current, BasicObjectLock* lock))
779 assert(current == JavaThread::current(), "pre-condition");
780 #ifndef PRODUCT
781 if (PrintC1Statistics) {
782 _monitorexit_slowcase_cnt++;
783 }
784 #endif
785 assert(current->last_Java_sp(), "last_Java_sp must be set");
786 oop obj = lock->obj();
787 assert(oopDesc::is_oop(obj), "must be null or an object");
788 SharedRuntime::monitor_exit_helper(obj, lock->lock(), current);
789 JRT_END
790
791 // Cf. OptoRuntime::deoptimize_caller_frame
792 JRT_ENTRY(void, Runtime1::deoptimize(JavaThread* current, jint trap_request))
793 // Called from within the owner thread, so no need for safepoint
794 RegisterMap reg_map(current,
795 RegisterMap::UpdateMap::skip,
796 RegisterMap::ProcessFrames::include,
797 RegisterMap::WalkContinuation::skip);
798 frame stub_frame = current->last_frame();
799 assert(stub_frame.is_runtime_frame(), "Sanity check");
800 frame caller_frame = stub_frame.sender(®_map);
801 nmethod* nm = caller_frame.cb()->as_nmethod_or_null();
802 assert(nm != nullptr, "Sanity check");
803 methodHandle method(current, nm->method());
804 assert(nm == CodeCache::find_nmethod(caller_frame.pc()), "Should be the same");
805 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
806 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
807
808 if (action == Deoptimization::Action_make_not_entrant) {
809 if (nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE)) {
810 if (reason == Deoptimization::Reason_tenured) {
811 MethodData* trap_mdo = Deoptimization::get_method_data(current, method, true /*create_if_missing*/);
812 if (trap_mdo != nullptr) {
813 trap_mdo->inc_tenure_traps();
814 }
815 }
816 }
817 }
818
819 // Deoptimize the caller frame.
820 Deoptimization::deoptimize_frame(current, caller_frame.id());
821 // Return to the now deoptimized frame.
822 JRT_END
823
824
825 #ifndef DEOPTIMIZE_WHEN_PATCHING
826
827 static Klass* resolve_field_return_klass(const methodHandle& caller, int bci, TRAPS) {
828 Bytecode_field field_access(caller, bci);
829 // This can be static or non-static field access
830 Bytecodes::Code code = field_access.code();
831
832 // We must load class, initialize class and resolve the field
833 fieldDescriptor result; // initialize class if needed
834 constantPoolHandle constants(THREAD, caller->constants());
835 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller, Bytecodes::java_code(code), CHECK_NULL);
836 return result.field_holder();
837 }
838
839
840 //
841 // This routine patches sites where a class wasn't loaded or
842 // initialized at the time the code was generated. It handles
843 // references to classes, fields and forcing of initialization. Most
844 // of the cases are straightforward and involving simply forcing
845 // resolution of a class, rewriting the instruction stream with the
846 // needed constant and replacing the call in this function with the
847 // patched code. The case for static field is more complicated since
848 // the thread which is in the process of initializing a class can
849 // access it's static fields but other threads can't so the code
850 // either has to deoptimize when this case is detected or execute a
851 // check that the current thread is the initializing thread. The
852 // current
853 //
854 // Patches basically look like this:
855 //
856 //
857 // patch_site: jmp patch stub ;; will be patched
858 // continue: ...
859 // ...
860 // ...
861 // ...
862 //
863 // They have a stub which looks like this:
864 //
865 // ;; patch body
866 // movl <const>, reg (for class constants)
867 // <or> movl [reg1 + <const>], reg (for field offsets)
868 // <or> movl reg, [reg1 + <const>] (for field offsets)
869 // <being_init offset> <bytes to copy> <bytes to skip>
870 // patch_stub: call Runtime1::patch_code (through a runtime stub)
871 // jmp patch_site
872 //
873 //
874 // A normal patch is done by rewriting the patch body, usually a move,
875 // and then copying it into place over top of the jmp instruction
876 // being careful to flush caches and doing it in an MP-safe way. The
877 // constants following the patch body are used to find various pieces
878 // of the patch relative to the call site for Runtime1::patch_code.
879 // The case for getstatic and putstatic is more complicated because
880 // getstatic and putstatic have special semantics when executing while
881 // the class is being initialized. getstatic/putstatic on a class
882 // which is being_initialized may be executed by the initializing
883 // thread but other threads have to block when they execute it. This
884 // is accomplished in compiled code by executing a test of the current
885 // thread against the initializing thread of the class. It's emitted
886 // as boilerplate in their stub which allows the patched code to be
887 // executed before it's copied back into the main body of the nmethod.
888 //
889 // being_init: get_thread(<tmp reg>
890 // cmpl [reg1 + <init_thread_offset>], <tmp reg>
891 // jne patch_stub
892 // movl [reg1 + <const>], reg (for field offsets) <or>
893 // movl reg, [reg1 + <const>] (for field offsets)
894 // jmp continue
895 // <being_init offset> <bytes to copy> <bytes to skip>
896 // patch_stub: jmp Runtime1::patch_code (through a runtime stub)
897 // jmp patch_site
898 //
899 // If the class is being initialized the patch body is rewritten and
900 // the patch site is rewritten to jump to being_init, instead of
901 // patch_stub. Whenever this code is executed it checks the current
902 // thread against the initializing thread so other threads will enter
903 // the runtime and end up blocked waiting the class to finish
904 // initializing inside the calls to resolve_field below. The
905 // initializing class will continue on it's way. Once the class is
906 // fully_initialized, the intializing_thread of the class becomes
907 // null, so the next thread to execute this code will fail the test,
908 // call into patch_code and complete the patching process by copying
909 // the patch body back into the main part of the nmethod and resume
910 // executing.
911
912 // NB:
913 //
914 // Patchable instruction sequences inherently exhibit race conditions,
915 // where thread A is patching an instruction at the same time thread B
916 // is executing it. The algorithms we use ensure that any observation
917 // that B can make on any intermediate states during A's patching will
918 // always end up with a correct outcome. This is easiest if there are
919 // few or no intermediate states. (Some inline caches have two
920 // related instructions that must be patched in tandem. For those,
921 // intermediate states seem to be unavoidable, but we will get the
922 // right answer from all possible observation orders.)
923 //
924 // When patching the entry instruction at the head of a method, or a
925 // linkable call instruction inside of a method, we try very hard to
926 // use a patch sequence which executes as a single memory transaction.
927 // This means, in practice, that when thread A patches an instruction,
928 // it should patch a 32-bit or 64-bit word that somehow overlaps the
929 // instruction or is contained in it. We believe that memory hardware
930 // will never break up such a word write, if it is naturally aligned
931 // for the word being written. We also know that some CPUs work very
932 // hard to create atomic updates even of naturally unaligned words,
933 // but we don't want to bet the farm on this always working.
934 //
935 // Therefore, if there is any chance of a race condition, we try to
936 // patch only naturally aligned words, as single, full-word writes.
937
938 JRT_ENTRY(void, Runtime1::patch_code(JavaThread* current, StubId stub_id ))
939 #ifndef PRODUCT
940 if (PrintC1Statistics) {
941 _patch_code_slowcase_cnt++;
942 }
943 #endif
944
945 ResourceMark rm(current);
946 RegisterMap reg_map(current,
947 RegisterMap::UpdateMap::skip,
948 RegisterMap::ProcessFrames::include,
949 RegisterMap::WalkContinuation::skip);
950 frame runtime_frame = current->last_frame();
951 frame caller_frame = runtime_frame.sender(®_map);
952
953 // last java frame on stack
954 vframeStream vfst(current, true);
955 assert(!vfst.at_end(), "Java frame must exist");
956
957 methodHandle caller_method(current, vfst.method());
958 // Note that caller_method->code() may not be same as caller_code because of OSR's
959 // Note also that in the presence of inlining it is not guaranteed
960 // that caller_method() == caller_code->method()
961
962 int bci = vfst.bci();
963 Bytecodes::Code code = caller_method()->java_code_at(bci);
964
965 // this is used by assertions in the access_field_patching_id
966 BasicType patch_field_type = T_ILLEGAL;
967 bool deoptimize_for_volatile = false;
968 bool deoptimize_for_atomic = false;
969 int patch_field_offset = -1;
970 Klass* init_klass = nullptr; // klass needed by load_klass_patching code
971 Klass* load_klass = nullptr; // klass needed by load_klass_patching code
972 Handle mirror(current, nullptr); // oop needed by load_mirror_patching code
973 Handle appendix(current, nullptr); // oop needed by appendix_patching code
974 bool load_klass_or_mirror_patch_id =
975 (stub_id == StubId::c1_load_klass_patching_id || stub_id == StubId::c1_load_mirror_patching_id);
976
977 if (stub_id == StubId::c1_access_field_patching_id) {
978
979 Bytecode_field field_access(caller_method, bci);
980 fieldDescriptor result; // initialize class if needed
981 Bytecodes::Code code = field_access.code();
982 constantPoolHandle constants(current, caller_method->constants());
983 LinkResolver::resolve_field_access(result, constants, field_access.index(), caller_method, Bytecodes::java_code(code), CHECK);
984 patch_field_offset = result.offset();
985 patch_field_type = result.field_type();
986
987 // If we're patching a field which is volatile then at compile it
988 // must not have been know to be volatile, so the generated code
989 // isn't correct for a volatile reference. The nmethod has to be
990 // deoptimized so that the code can be regenerated correctly.
991 // This check is only needed for access_field_patching since this
992 // is the path for patching field offsets. load_klass is only
993 // used for patching references to oops which don't need special
994 // handling in the volatile case.
995
996 deoptimize_for_volatile = result.access_flags().is_volatile();
997 } else if (load_klass_or_mirror_patch_id) {
998 Klass* k = nullptr;
999 switch (code) {
1000 case Bytecodes::_putstatic:
1001 case Bytecodes::_getstatic:
1002 { Klass* klass = resolve_field_return_klass(caller_method, bci, CHECK);
1003 init_klass = klass;
1004 mirror = Handle(current, klass->java_mirror());
1005 }
1006 break;
1007 case Bytecodes::_new:
1008 { Bytecode_new bnew(caller_method(), caller_method->bcp_from(bci));
1009 k = caller_method->constants()->klass_at(bnew.index(), CHECK);
1010 }
1011 break;
1012 case Bytecodes::_multianewarray:
1013 { Bytecode_multianewarray mna(caller_method(), caller_method->bcp_from(bci));
1014 k = caller_method->constants()->klass_at(mna.index(), CHECK);
1015 }
1016 break;
1017 case Bytecodes::_instanceof:
1018 { Bytecode_instanceof io(caller_method(), caller_method->bcp_from(bci));
1019 k = caller_method->constants()->klass_at(io.index(), CHECK);
1020 }
1021 break;
1022 case Bytecodes::_checkcast:
1023 { Bytecode_checkcast cc(caller_method(), caller_method->bcp_from(bci));
1024 k = caller_method->constants()->klass_at(cc.index(), CHECK);
1025 }
1026 break;
1027 case Bytecodes::_anewarray:
1028 { Bytecode_anewarray anew(caller_method(), caller_method->bcp_from(bci));
1029 Klass* ek = caller_method->constants()->klass_at(anew.index(), CHECK);
1030 k = ek->array_klass(CHECK);
1031 }
1032 break;
1033 case Bytecodes::_ldc:
1034 case Bytecodes::_ldc_w:
1035 case Bytecodes::_ldc2_w:
1036 {
1037 Bytecode_loadconstant cc(caller_method, bci);
1038 oop m = cc.resolve_constant(CHECK);
1039 mirror = Handle(current, m);
1040 }
1041 break;
1042 default: fatal("unexpected bytecode for load_klass_or_mirror_patch_id");
1043 }
1044 load_klass = k;
1045 } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1046 Bytecode_invoke bytecode(caller_method, bci);
1047 Bytecodes::Code bc = bytecode.invoke_code();
1048
1049 CallInfo info;
1050 constantPoolHandle pool(current, caller_method->constants());
1051 int index = bytecode.index();
1052 LinkResolver::resolve_invoke(info, Handle(), pool, index, bc, CHECK);
1053 switch (bc) {
1054 case Bytecodes::_invokehandle: {
1055 ResolvedMethodEntry* entry = pool->cache()->set_method_handle(index, info);
1056 appendix = Handle(current, pool->cache()->appendix_if_resolved(entry));
1057 break;
1058 }
1059 case Bytecodes::_invokedynamic: {
1060 appendix = Handle(current, pool->cache()->set_dynamic_call(info, index));
1061 break;
1062 }
1063 default: fatal("unexpected bytecode for load_appendix_patching_id");
1064 }
1065 } else {
1066 ShouldNotReachHere();
1067 }
1068
1069 if (deoptimize_for_volatile) {
1070 // At compile time we assumed the field wasn't volatile but after
1071 // loading it turns out it was volatile so we have to throw the
1072 // compiled code out and let it be regenerated.
1073 if (TracePatching) {
1074 tty->print_cr("Deoptimizing for patching volatile field reference");
1075 }
1076
1077 // It's possible the nmethod was invalidated in the last
1078 // safepoint, but if it's still alive then make it not_entrant.
1079 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1080 if (nm != nullptr) {
1081 nm->make_not_entrant(nmethod::InvalidationReason::C1_CODEPATCH);
1082 }
1083
1084 Deoptimization::deoptimize_frame(current, caller_frame.id());
1085
1086 // Return to the now deoptimized frame.
1087 }
1088
1089 // Now copy code back
1090
1091 {
1092 MutexLocker ml_code (current, CodeCache_lock, Mutex::_no_safepoint_check_flag);
1093 //
1094 // Deoptimization may have happened while we waited for the lock.
1095 // In that case we don't bother to do any patching we just return
1096 // and let the deopt happen
1097 if (!caller_is_deopted(current)) {
1098 NativeGeneralJump* jump = nativeGeneralJump_at(caller_frame.pc());
1099 address instr_pc = jump->jump_destination();
1100 NativeInstruction* ni = nativeInstruction_at(instr_pc);
1101 if (ni->is_jump() ) {
1102 // the jump has not been patched yet
1103 // The jump destination is slow case and therefore not part of the stubs
1104 // (stubs are only for StaticCalls)
1105
1106 // format of buffer
1107 // ....
1108 // instr byte 0 <-- copy_buff
1109 // instr byte 1
1110 // ..
1111 // instr byte n-1
1112 // n
1113 // .... <-- call destination
1114
1115 address stub_location = caller_frame.pc() + PatchingStub::patch_info_offset();
1116 unsigned char* byte_count = (unsigned char*) (stub_location - 1);
1117 unsigned char* byte_skip = (unsigned char*) (stub_location - 2);
1118 unsigned char* being_initialized_entry_offset = (unsigned char*) (stub_location - 3);
1119 address copy_buff = stub_location - *byte_skip - *byte_count;
1120 address being_initialized_entry = stub_location - *being_initialized_entry_offset;
1121 if (TracePatching) {
1122 ttyLocker ttyl;
1123 tty->print_cr(" Patching %s at bci %d at address " INTPTR_FORMAT " (%s)", Bytecodes::name(code), bci,
1124 p2i(instr_pc), (stub_id == StubId::c1_access_field_patching_id) ? "field" : "klass");
1125 nmethod* caller_code = CodeCache::find_nmethod(caller_frame.pc());
1126 assert(caller_code != nullptr, "nmethod not found");
1127
1128 // NOTE we use pc() not original_pc() because we already know they are
1129 // identical otherwise we'd have never entered this block of code
1130
1131 const ImmutableOopMap* map = caller_code->oop_map_for_return_address(caller_frame.pc());
1132 assert(map != nullptr, "null check");
1133 map->print();
1134 tty->cr();
1135
1136 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1137 }
1138 // depending on the code below, do_patch says whether to copy the patch body back into the nmethod
1139 bool do_patch = true;
1140 if (stub_id == StubId::c1_access_field_patching_id) {
1141 // The offset may not be correct if the class was not loaded at code generation time.
1142 // Set it now.
1143 NativeMovRegMem* n_move = nativeMovRegMem_at(copy_buff);
1144 assert(n_move->offset() == 0 || (n_move->offset() == 4 && (patch_field_type == T_DOUBLE || patch_field_type == T_LONG)), "illegal offset for type");
1145 assert(patch_field_offset >= 0, "illegal offset");
1146 n_move->add_offset_in_bytes(patch_field_offset);
1147 } else if (load_klass_or_mirror_patch_id) {
1148 // If a getstatic or putstatic is referencing a klass which
1149 // isn't fully initialized, the patch body isn't copied into
1150 // place until initialization is complete. In this case the
1151 // patch site is setup so that any threads besides the
1152 // initializing thread are forced to come into the VM and
1153 // block.
1154 do_patch = (code != Bytecodes::_getstatic && code != Bytecodes::_putstatic) ||
1155 InstanceKlass::cast(init_klass)->is_initialized();
1156 NativeGeneralJump* jump = nativeGeneralJump_at(instr_pc);
1157 if (jump->jump_destination() == being_initialized_entry) {
1158 assert(do_patch == true, "initialization must be complete at this point");
1159 } else {
1160 // patch the instruction <move reg, klass>
1161 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1162
1163 assert(n_copy->data() == 0 ||
1164 n_copy->data() == (intptr_t)Universe::non_oop_word(),
1165 "illegal init value");
1166 if (stub_id == StubId::c1_load_klass_patching_id) {
1167 assert(load_klass != nullptr, "klass not set");
1168 n_copy->set_data((intx) (load_klass));
1169 } else {
1170 // Don't need a G1 pre-barrier here since we assert above that data isn't an oop.
1171 n_copy->set_data(cast_from_oop<intx>(mirror()));
1172 }
1173
1174 if (TracePatching) {
1175 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1176 }
1177 }
1178 } else if (stub_id == StubId::c1_load_appendix_patching_id) {
1179 NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff);
1180 assert(n_copy->data() == 0 ||
1181 n_copy->data() == (intptr_t)Universe::non_oop_word(),
1182 "illegal init value");
1183 n_copy->set_data(cast_from_oop<intx>(appendix()));
1184
1185 if (TracePatching) {
1186 Disassembler::decode(copy_buff, copy_buff + *byte_count, tty);
1187 }
1188 } else {
1189 ShouldNotReachHere();
1190 }
1191
1192 if (do_patch) {
1193 // replace instructions
1194 // first replace the tail, then the call
1195 #ifdef ARM
1196 if((load_klass_or_mirror_patch_id ||
1197 stub_id == StubId::c1_load_appendix_patching_id) &&
1198 nativeMovConstReg_at(copy_buff)->is_pc_relative()) {
1199 nmethod* nm = CodeCache::find_nmethod(instr_pc);
1200 address addr = nullptr;
1201 assert(nm != nullptr, "invalid nmethod_pc");
1202 RelocIterator mds(nm, copy_buff, copy_buff + 1);
1203 while (mds.next()) {
1204 if (mds.type() == relocInfo::oop_type) {
1205 assert(stub_id == StubId::c1_load_mirror_patching_id ||
1206 stub_id == StubId::c1_load_appendix_patching_id, "wrong stub id");
1207 oop_Relocation* r = mds.oop_reloc();
1208 addr = (address)r->oop_addr();
1209 break;
1210 } else if (mds.type() == relocInfo::metadata_type) {
1211 assert(stub_id == StubId::c1_load_klass_patching_id, "wrong stub id");
1212 metadata_Relocation* r = mds.metadata_reloc();
1213 addr = (address)r->metadata_addr();
1214 break;
1215 }
1216 }
1217 assert(addr != nullptr, "metadata relocation must exist");
1218 copy_buff -= *byte_count;
1219 NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff);
1220 n_copy2->set_pc_relative_offset(addr, instr_pc);
1221 }
1222 #endif
1223
1224 for (int i = NativeGeneralJump::instruction_size; i < *byte_count; i++) {
1225 address ptr = copy_buff + i;
1226 int a_byte = (*ptr) & 0xFF;
1227 address dst = instr_pc + i;
1228 *(unsigned char*)dst = (unsigned char) a_byte;
1229 }
1230 ICache::invalidate_range(instr_pc, *byte_count);
1231 NativeGeneralJump::replace_mt_safe(instr_pc, copy_buff);
1232
1233 if (load_klass_or_mirror_patch_id ||
1234 stub_id == StubId::c1_load_appendix_patching_id) {
1235 relocInfo::relocType rtype =
1236 (stub_id == StubId::c1_load_klass_patching_id) ?
1237 relocInfo::metadata_type :
1238 relocInfo::oop_type;
1239 // update relocInfo to metadata
1240 nmethod* nm = CodeCache::find_nmethod(instr_pc);
1241 assert(nm != nullptr, "invalid nmethod_pc");
1242
1243 // The old patch site is now a move instruction so update
1244 // the reloc info so that it will get updated during
1245 // future GCs.
1246 RelocIterator iter(nm, (address)instr_pc, (address)(instr_pc + 1));
1247 relocInfo::change_reloc_info_for_address(&iter, (address) instr_pc,
1248 relocInfo::none, rtype);
1249 }
1250
1251 } else {
1252 ICache::invalidate_range(copy_buff, *byte_count);
1253 NativeGeneralJump::insert_unconditional(instr_pc, being_initialized_entry);
1254 }
1255 }
1256 }
1257 // If we are patching in a non-perm oop, make sure the nmethod
1258 // is on the right list.
1259 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1260 guarantee(nm != nullptr, "only nmethods can contain non-perm oops");
1261
1262 // Since we've patched some oops in the nmethod,
1263 // (re)register it with the heap.
1264 Universe::heap()->register_nmethod(nm);
1265 }
1266 JRT_END
1267
1268 #else // DEOPTIMIZE_WHEN_PATCHING
1269
1270 static bool is_patching_needed(JavaThread* current, StubId stub_id) {
1271 if (stub_id == StubId::c1_load_klass_patching_id ||
1272 stub_id == StubId::c1_load_mirror_patching_id) {
1273 // last java frame on stack
1274 vframeStream vfst(current, true);
1275 assert(!vfst.at_end(), "Java frame must exist");
1276
1277 methodHandle caller_method(current, vfst.method());
1278 int bci = vfst.bci();
1279 Bytecodes::Code code = caller_method()->java_code_at(bci);
1280
1281 switch (code) {
1282 case Bytecodes::_new:
1283 case Bytecodes::_anewarray:
1284 case Bytecodes::_multianewarray:
1285 case Bytecodes::_instanceof:
1286 case Bytecodes::_checkcast: {
1287 Bytecode bc(caller_method(), caller_method->bcp_from(bci));
1288 constantTag tag = caller_method->constants()->tag_at(bc.get_index_u2(code));
1289 if (tag.is_unresolved_klass_in_error()) {
1290 return false; // throws resolution error
1291 }
1292 break;
1293 }
1294
1295 default: break;
1296 }
1297 }
1298 return true;
1299 }
1300
1301 void Runtime1::patch_code(JavaThread* current, StubId stub_id) {
1302 #ifndef PRODUCT
1303 if (PrintC1Statistics) {
1304 _patch_code_slowcase_cnt++;
1305 }
1306 #endif
1307
1308 // Enable WXWrite: the function is called by c1 stub as a runtime function
1309 // (see another implementation above).
1310 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
1311
1312 if (TracePatching) {
1313 tty->print_cr("Deoptimizing because patch is needed");
1314 }
1315
1316 RegisterMap reg_map(current,
1317 RegisterMap::UpdateMap::skip,
1318 RegisterMap::ProcessFrames::include,
1319 RegisterMap::WalkContinuation::skip);
1320
1321 frame runtime_frame = current->last_frame();
1322 frame caller_frame = runtime_frame.sender(®_map);
1323 assert(caller_frame.is_compiled_frame(), "Wrong frame type");
1324
1325 if (is_patching_needed(current, stub_id)) {
1326 // Make sure the nmethod is invalidated, i.e. made not entrant.
1327 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1328 if (nm != nullptr) {
1329 nm->make_not_entrant(nmethod::InvalidationReason::C1_DEOPTIMIZE_FOR_PATCHING);
1330 }
1331 }
1332
1333 Deoptimization::deoptimize_frame(current, caller_frame.id());
1334 // Return to the now deoptimized frame.
1335 postcond(caller_is_deopted(current));
1336 }
1337
1338 #endif // DEOPTIMIZE_WHEN_PATCHING
1339
1340 // Entry point for compiled code. We want to patch a nmethod.
1341 // We don't do a normal VM transition here because we want to
1342 // know after the patching is complete and any safepoint(s) are taken
1343 // if the calling nmethod was deoptimized. We do this by calling a
1344 // helper method which does the normal VM transition and when it
1345 // completes we can check for deoptimization. This simplifies the
1346 // assembly code in the cpu directories.
1347 //
1348 int Runtime1::move_klass_patching(JavaThread* current) {
1349 //
1350 // NOTE: we are still in Java
1351 //
1352 DEBUG_ONLY(NoHandleMark nhm;)
1353 {
1354 // Enter VM mode
1355 ResetNoHandleMark rnhm;
1356 patch_code(current, StubId::c1_load_klass_patching_id);
1357 }
1358 // Back in JAVA, use no oops DON'T safepoint
1359
1360 // Return true if calling code is deoptimized
1361
1362 return caller_is_deopted(current);
1363 }
1364
1365 int Runtime1::move_mirror_patching(JavaThread* current) {
1366 //
1367 // NOTE: we are still in Java
1368 //
1369 DEBUG_ONLY(NoHandleMark nhm;)
1370 {
1371 // Enter VM mode
1372 ResetNoHandleMark rnhm;
1373 patch_code(current, StubId::c1_load_mirror_patching_id);
1374 }
1375 // Back in JAVA, use no oops DON'T safepoint
1376
1377 // Return true if calling code is deoptimized
1378
1379 return caller_is_deopted(current);
1380 }
1381
1382 int Runtime1::move_appendix_patching(JavaThread* current) {
1383 //
1384 // NOTE: we are still in Java
1385 //
1386 DEBUG_ONLY(NoHandleMark nhm;)
1387 {
1388 // Enter VM mode
1389 ResetNoHandleMark rnhm;
1390 patch_code(current, StubId::c1_load_appendix_patching_id);
1391 }
1392 // Back in JAVA, use no oops DON'T safepoint
1393
1394 // Return true if calling code is deoptimized
1395
1396 return caller_is_deopted(current);
1397 }
1398
1399 // Entry point for compiled code. We want to patch a nmethod.
1400 // We don't do a normal VM transition here because we want to
1401 // know after the patching is complete and any safepoint(s) are taken
1402 // if the calling nmethod was deoptimized. We do this by calling a
1403 // helper method which does the normal VM transition and when it
1404 // completes we can check for deoptimization. This simplifies the
1405 // assembly code in the cpu directories.
1406 //
1407 int Runtime1::access_field_patching(JavaThread* current) {
1408 //
1409 // NOTE: we are still in Java
1410 //
1411 // Handles created in this function will be deleted by the
1412 // HandleMarkCleaner in the transition to the VM.
1413 NoHandleMark nhm;
1414 {
1415 // Enter VM mode
1416 ResetNoHandleMark rnhm;
1417 patch_code(current, StubId::c1_access_field_patching_id);
1418 }
1419 // Back in JAVA, use no oops DON'T safepoint
1420
1421 // Return true if calling code is deoptimized
1422
1423 return caller_is_deopted(current);
1424 }
1425
1426
1427 JRT_LEAF(void, Runtime1::trace_block_entry(jint block_id))
1428 // for now we just print out the block id
1429 tty->print("%d ", block_id);
1430 JRT_END
1431
1432
1433 JRT_LEAF(int, Runtime1::is_instance_of(oopDesc* mirror, oopDesc* obj))
1434 // had to return int instead of bool, otherwise there may be a mismatch
1435 // between the C calling convention and the Java one.
1436 // e.g., on x86, GCC may clear only %al when returning a bool false, but
1437 // JVM takes the whole %eax as the return value, which may misinterpret
1438 // the return value as a boolean true.
1439
1440 assert(mirror != nullptr, "should null-check on mirror before calling");
1441 Klass* k = java_lang_Class::as_Klass(mirror);
1442 return (k != nullptr && obj != nullptr && obj->is_a(k)) ? 1 : 0;
1443 JRT_END
1444
1445 JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* current))
1446 ResourceMark rm;
1447
1448 RegisterMap reg_map(current,
1449 RegisterMap::UpdateMap::skip,
1450 RegisterMap::ProcessFrames::include,
1451 RegisterMap::WalkContinuation::skip);
1452 frame runtime_frame = current->last_frame();
1453 frame caller_frame = runtime_frame.sender(®_map);
1454
1455 nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
1456 assert (nm != nullptr, "no more nmethod?");
1457 nm->make_not_entrant(nmethod::InvalidationReason::C1_PREDICATE_FAILED_TRAP);
1458
1459 methodHandle m(current, nm->method());
1460 MethodData* mdo = m->method_data();
1461
1462 if (mdo == nullptr && !HAS_PENDING_EXCEPTION) {
1463 // Build an MDO. Ignore errors like OutOfMemory;
1464 // that simply means we won't have an MDO to update.
1465 Method::build_profiling_method_data(m, THREAD);
1466 if (HAS_PENDING_EXCEPTION) {
1467 // Only metaspace OOM is expected. No Java code executed.
1468 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1469 CLEAR_PENDING_EXCEPTION;
1470 }
1471 mdo = m->method_data();
1472 }
1473
1474 if (mdo != nullptr) {
1475 mdo->inc_trap_count(Deoptimization::Reason_none);
1476 }
1477
1478 if (TracePredicateFailedTraps) {
1479 stringStream ss1, ss2;
1480 vframeStream vfst(current);
1481 Method* inlinee = vfst.method();
1482 inlinee->print_short_name(&ss1);
1483 m->print_short_name(&ss2);
1484 tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc " INTPTR_FORMAT, ss1.freeze(), vfst.bci(), ss2.freeze(), p2i(caller_frame.pc()));
1485 }
1486
1487
1488 Deoptimization::deoptimize_frame(current, caller_frame.id());
1489
1490 JRT_END
1491
1492 // Check exception if AbortVMOnException flag set
1493 JRT_LEAF(void, Runtime1::check_abort_on_vm_exception(oopDesc* ex))
1494 ResourceMark rm;
1495 const char* message = nullptr;
1496 if (ex->is_a(vmClasses::Throwable_klass())) {
1497 oop msg = java_lang_Throwable::message(ex);
1498 if (msg != nullptr) {
1499 message = java_lang_String::as_utf8_string(msg);
1500 }
1501 }
1502 Exceptions::debug_check_abort(ex->klass()->external_name(), message);
1503 JRT_END
1504
1505 #ifndef PRODUCT
1506 void Runtime1::print_statistics() {
1507 tty->print_cr("C1 Runtime statistics:");
1508 tty->print_cr(" _resolve_invoke_virtual_cnt: %u", SharedRuntime::_resolve_virtual_ctr);
1509 tty->print_cr(" _resolve_invoke_opt_virtual_cnt: %u", SharedRuntime::_resolve_opt_virtual_ctr);
1510 tty->print_cr(" _resolve_invoke_static_cnt: %u", SharedRuntime::_resolve_static_ctr);
1511 tty->print_cr(" _handle_wrong_method_cnt: %u", SharedRuntime::_wrong_method_ctr);
1512 tty->print_cr(" _ic_miss_cnt: %u", SharedRuntime::_ic_miss_ctr);
1513 tty->print_cr(" _generic_arraycopystub_cnt: %u", _generic_arraycopystub_cnt);
1514 tty->print_cr(" _byte_arraycopy_cnt: %u", _byte_arraycopy_stub_cnt);
1515 tty->print_cr(" _short_arraycopy_cnt: %u", _short_arraycopy_stub_cnt);
1516 tty->print_cr(" _int_arraycopy_cnt: %u", _int_arraycopy_stub_cnt);
1517 tty->print_cr(" _long_arraycopy_cnt: %u", _long_arraycopy_stub_cnt);
1518 tty->print_cr(" _oop_arraycopy_cnt: %u", _oop_arraycopy_stub_cnt);
1519 tty->print_cr(" _arraycopy_slowcase_cnt: %u", _arraycopy_slowcase_cnt);
1520 tty->print_cr(" _arraycopy_checkcast_cnt: %u", _arraycopy_checkcast_cnt);
1521 tty->print_cr(" _arraycopy_checkcast_attempt_cnt:%u", _arraycopy_checkcast_attempt_cnt);
1522
1523 tty->print_cr(" _new_type_array_slowcase_cnt: %u", _new_type_array_slowcase_cnt);
1524 tty->print_cr(" _new_object_array_slowcase_cnt: %u", _new_object_array_slowcase_cnt);
1525 tty->print_cr(" _new_instance_slowcase_cnt: %u", _new_instance_slowcase_cnt);
1526 tty->print_cr(" _new_multi_array_slowcase_cnt: %u", _new_multi_array_slowcase_cnt);
1527 tty->print_cr(" _monitorenter_slowcase_cnt: %u", _monitorenter_slowcase_cnt);
1528 tty->print_cr(" _monitorexit_slowcase_cnt: %u", _monitorexit_slowcase_cnt);
1529 tty->print_cr(" _patch_code_slowcase_cnt: %u", _patch_code_slowcase_cnt);
1530
1531 tty->print_cr(" _throw_range_check_exception_count: %u:", _throw_range_check_exception_count);
1532 tty->print_cr(" _throw_index_exception_count: %u:", _throw_index_exception_count);
1533 tty->print_cr(" _throw_div0_exception_count: %u:", _throw_div0_exception_count);
1534 tty->print_cr(" _throw_null_pointer_exception_count: %u:", _throw_null_pointer_exception_count);
1535 tty->print_cr(" _throw_class_cast_exception_count: %u:", _throw_class_cast_exception_count);
1536 tty->print_cr(" _throw_incompatible_class_change_error_count: %u:", _throw_incompatible_class_change_error_count);
1537 tty->print_cr(" _throw_count: %u:", _throw_count);
1538
1539 SharedRuntime::print_ic_miss_histogram();
1540 tty->cr();
1541 }
1542 #endif // PRODUCT