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 "asm/assembler.inline.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "code/codeCache.hpp"
28 #include "code/compiledIC.hpp"
29 #include "code/dependencies.hpp"
30 #include "code/nativeInst.hpp"
31 #include "code/nmethod.inline.hpp"
32 #include "code/scopeDesc.hpp"
33 #include "compiler/abstractCompiler.hpp"
34 #include "compiler/compilationLog.hpp"
35 #include "compiler/compileBroker.hpp"
36 #include "compiler/compileLog.hpp"
37 #include "compiler/compilerDirectives.hpp"
38 #include "compiler/compilerOracle.hpp"
39 #include "compiler/compileTask.hpp"
40 #include "compiler/directivesParser.hpp"
41 #include "compiler/disassembler.hpp"
42 #include "compiler/oopMap.inline.hpp"
43 #include "gc/shared/barrierSet.hpp"
44 #include "gc/shared/barrierSetNMethod.hpp"
45 #include "gc/shared/classUnloadingContext.hpp"
46 #include "gc/shared/collectedHeap.hpp"
47 #include "interpreter/bytecode.inline.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "logging/logStream.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "memory/universe.hpp"
54 #include "oops/access.inline.hpp"
55 #include "oops/klass.inline.hpp"
56 #include "oops/method.inline.hpp"
57 #include "oops/methodData.hpp"
58 #include "oops/oop.inline.hpp"
59 #include "oops/weakHandle.inline.hpp"
60 #include "prims/jvmtiImpl.hpp"
61 #include "prims/jvmtiThreadState.hpp"
62 #include "prims/methodHandles.hpp"
63 #include "runtime/atomicAccess.hpp"
64 #include "runtime/continuation.hpp"
65 #include "runtime/deoptimization.hpp"
66 #include "runtime/flags/flagSetting.hpp"
67 #include "runtime/frame.inline.hpp"
68 #include "runtime/handles.inline.hpp"
69 #ifdef COMPILER2
70 #include "runtime/hotCodeCollector.hpp"
71 #endif // COMPILER2
72 #include "runtime/icache.hpp"
73 #include "runtime/jniHandles.inline.hpp"
74 #include "runtime/orderAccess.hpp"
75 #include "runtime/os.hpp"
76 #include "runtime/safepointVerifiers.hpp"
77 #include "runtime/serviceThread.hpp"
78 #include "runtime/sharedRuntime.hpp"
79 #include "runtime/signature.hpp"
80 #include "runtime/threadWXSetters.inline.hpp"
81 #include "runtime/vmThread.hpp"
82 #include "utilities/align.hpp"
83 #include "utilities/copy.hpp"
84 #include "utilities/dtrace.hpp"
85 #include "utilities/events.hpp"
86 #include "utilities/globalDefinitions.hpp"
87 #include "utilities/hashTable.hpp"
88 #include "utilities/xmlstream.hpp"
89 #if INCLUDE_JVMCI
90 #include "jvmci/jvmciRuntime.hpp"
91 #endif
92
93 #ifdef DTRACE_ENABLED
94
95 // Only bother with this argument setup if dtrace is available
96
97 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
98 { \
99 Method* m = (method); \
100 if (m != nullptr) { \
101 Symbol* klass_name = m->klass_name(); \
102 Symbol* name = m->name(); \
103 Symbol* signature = m->signature(); \
104 HOTSPOT_COMPILED_METHOD_UNLOAD( \
105 (char *) klass_name->bytes(), klass_name->utf8_length(), \
106 (char *) name->bytes(), name->utf8_length(), \
107 (char *) signature->bytes(), signature->utf8_length()); \
108 } \
109 }
110
111 #else // ndef DTRACE_ENABLED
112
113 #define DTRACE_METHOD_UNLOAD_PROBE(method)
114
115 #endif
116
117 // Cast from int value to narrow type
118 #define CHECKED_CAST(result, T, thing) \
119 result = static_cast<T>(thing); \
120 guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing);
121
122 //---------------------------------------------------------------------------------
123 // NMethod statistics
124 // They are printed under various flags, including:
125 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
126 // (In the latter two cases, they like other stats are printed to the log only.)
127
128 #ifndef PRODUCT
129 // These variables are put into one block to reduce relocations
130 // and make it simpler to print from the debugger.
131 struct java_nmethod_stats_struct {
132 uint nmethod_count;
133 uint total_nm_size;
134 uint total_immut_size;
135 uint total_mut_size;
136 uint relocation_size;
137 uint consts_size;
138 uint insts_size;
139 uint stub_size;
140 uint oops_size;
141 uint metadata_size;
142 uint dependencies_size;
143 uint nul_chk_table_size;
144 uint handler_table_size;
145 uint scopes_pcs_size;
146 uint scopes_data_size;
147 #if INCLUDE_JVMCI
148 uint speculations_size;
149 uint jvmci_data_size;
150 #endif
151
152 void note_nmethod(nmethod* nm) {
153 nmethod_count += 1;
154 total_nm_size += nm->size();
155 total_immut_size += nm->immutable_data_size();
156 total_mut_size += nm->mutable_data_size();
157 relocation_size += nm->relocation_size();
158 consts_size += nm->consts_size();
159 insts_size += nm->insts_size();
160 stub_size += nm->stub_size();
161 oops_size += nm->oops_size();
162 metadata_size += nm->metadata_size();
163 scopes_data_size += nm->scopes_data_size();
164 scopes_pcs_size += nm->scopes_pcs_size();
165 dependencies_size += nm->dependencies_size();
166 handler_table_size += nm->handler_table_size();
167 nul_chk_table_size += nm->nul_chk_table_size();
168 #if INCLUDE_JVMCI
169 speculations_size += nm->speculations_size();
170 jvmci_data_size += nm->jvmci_data_size();
171 #endif
172 }
173 void print_nmethod_stats(const char* name) {
174 if (nmethod_count == 0) return;
175 tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name);
176 uint total_size = total_nm_size + total_immut_size + total_mut_size;
177 if (total_nm_size != 0) {
178 tty->print_cr(" total size = %u (100%%)", total_size);
179 tty->print_cr(" in CodeCache = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size);
180 }
181 uint header_size = (uint)(nmethod_count * sizeof(nmethod));
182 if (nmethod_count != 0) {
183 tty->print_cr(" header = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size);
184 }
185 if (consts_size != 0) {
186 tty->print_cr(" constants = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size);
187 }
188 if (insts_size != 0) {
189 tty->print_cr(" main code = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size);
190 }
191 if (stub_size != 0) {
192 tty->print_cr(" stub code = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size);
193 }
194 if (oops_size != 0) {
195 tty->print_cr(" oops = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size);
196 }
197 if (total_mut_size != 0) {
198 tty->print_cr(" mutable data = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size);
199 }
200 if (relocation_size != 0) {
201 tty->print_cr(" relocation = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size);
202 }
203 if (metadata_size != 0) {
204 tty->print_cr(" metadata = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size);
205 }
206 #if INCLUDE_JVMCI
207 if (jvmci_data_size != 0) {
208 tty->print_cr(" JVMCI data = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size);
209 }
210 #endif
211 if (total_immut_size != 0) {
212 tty->print_cr(" immutable data = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size);
213 }
214 if (dependencies_size != 0) {
215 tty->print_cr(" dependencies = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size);
216 }
217 if (nul_chk_table_size != 0) {
218 tty->print_cr(" nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size);
219 }
220 if (handler_table_size != 0) {
221 tty->print_cr(" handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size);
222 }
223 if (scopes_pcs_size != 0) {
224 tty->print_cr(" scopes pcs = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size);
225 }
226 if (scopes_data_size != 0) {
227 tty->print_cr(" scopes data = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size);
228 }
229 #if INCLUDE_JVMCI
230 if (speculations_size != 0) {
231 tty->print_cr(" speculations = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size);
232 }
233 #endif
234 }
235 };
236
237 struct native_nmethod_stats_struct {
238 uint native_nmethod_count;
239 uint native_total_size;
240 uint native_relocation_size;
241 uint native_insts_size;
242 uint native_oops_size;
243 uint native_metadata_size;
244 void note_native_nmethod(nmethod* nm) {
245 native_nmethod_count += 1;
246 native_total_size += nm->size();
247 native_relocation_size += nm->relocation_size();
248 native_insts_size += nm->insts_size();
249 native_oops_size += nm->oops_size();
250 native_metadata_size += nm->metadata_size();
251 }
252 void print_native_nmethod_stats() {
253 if (native_nmethod_count == 0) return;
254 tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count);
255 if (native_total_size != 0) tty->print_cr(" N. total size = %u", native_total_size);
256 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %u", native_relocation_size);
257 if (native_insts_size != 0) tty->print_cr(" N. main code = %u", native_insts_size);
258 if (native_oops_size != 0) tty->print_cr(" N. oops = %u", native_oops_size);
259 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %u", native_metadata_size);
260 }
261 };
262
263 struct pc_nmethod_stats_struct {
264 uint pc_desc_init; // number of initialization of cache (= number of caches)
265 uint pc_desc_queries; // queries to nmethod::find_pc_desc
266 uint pc_desc_approx; // number of those which have approximate true
267 uint pc_desc_repeats; // number of _pc_descs[0] hits
268 uint pc_desc_hits; // number of LRU cache hits
269 uint pc_desc_tests; // total number of PcDesc examinations
270 uint pc_desc_searches; // total number of quasi-binary search steps
271 uint pc_desc_adds; // number of LUR cache insertions
272
273 void print_pc_stats() {
274 tty->print_cr("PcDesc Statistics: %u queries, %.2f comparisons per query",
275 pc_desc_queries,
276 (double)(pc_desc_tests + pc_desc_searches)
277 / pc_desc_queries);
278 tty->print_cr(" caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u",
279 pc_desc_init,
280 pc_desc_queries, pc_desc_approx,
281 pc_desc_repeats, pc_desc_hits,
282 pc_desc_tests, pc_desc_searches, pc_desc_adds);
283 }
284 };
285
286 #ifdef COMPILER1
287 static java_nmethod_stats_struct c1_java_nmethod_stats;
288 #endif
289 #ifdef COMPILER2
290 static java_nmethod_stats_struct c2_java_nmethod_stats;
291 #endif
292 #if INCLUDE_JVMCI
293 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
294 #endif
295 static java_nmethod_stats_struct unknown_java_nmethod_stats;
296
297 static native_nmethod_stats_struct native_nmethod_stats;
298 static pc_nmethod_stats_struct pc_nmethod_stats;
299
300 static void note_java_nmethod(nmethod* nm) {
301 #ifdef COMPILER1
302 if (nm->is_compiled_by_c1()) {
303 c1_java_nmethod_stats.note_nmethod(nm);
304 } else
305 #endif
306 #ifdef COMPILER2
307 if (nm->is_compiled_by_c2()) {
308 c2_java_nmethod_stats.note_nmethod(nm);
309 } else
310 #endif
311 #if INCLUDE_JVMCI
312 if (nm->is_compiled_by_jvmci()) {
313 jvmci_java_nmethod_stats.note_nmethod(nm);
314 } else
315 #endif
316 {
317 unknown_java_nmethod_stats.note_nmethod(nm);
318 }
319 }
320 #endif // !PRODUCT
321
322 //---------------------------------------------------------------------------------
323
324
325 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
326 assert(pc != nullptr, "Must be non null");
327 assert(exception.not_null(), "Must be non null");
328 assert(handler != nullptr, "Must be non null");
329
330 _count = 0;
331 _exception_type = exception->klass();
332 _next = nullptr;
333 _purge_list_next = nullptr;
334
335 add_address_and_handler(pc,handler);
336 }
337
338
339 address ExceptionCache::match(Handle exception, address pc) {
340 assert(pc != nullptr,"Must be non null");
341 assert(exception.not_null(),"Must be non null");
342 if (exception->klass() == exception_type()) {
343 return (test_address(pc));
344 }
345
346 return nullptr;
347 }
348
349
350 bool ExceptionCache::match_exception_with_space(Handle exception) {
351 assert(exception.not_null(),"Must be non null");
352 if (exception->klass() == exception_type() && count() < cache_size) {
353 return true;
354 }
355 return false;
356 }
357
358
359 address ExceptionCache::test_address(address addr) {
360 int limit = count();
361 for (int i = 0; i < limit; i++) {
362 if (pc_at(i) == addr) {
363 return handler_at(i);
364 }
365 }
366 return nullptr;
367 }
368
369
370 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
371 if (test_address(addr) == handler) return true;
372
373 int index = count();
374 if (index < cache_size) {
375 set_pc_at(index, addr);
376 set_handler_at(index, handler);
377 increment_count();
378 return true;
379 }
380 return false;
381 }
382
383 ExceptionCache* ExceptionCache::next() {
384 return AtomicAccess::load(&_next);
385 }
386
387 void ExceptionCache::set_next(ExceptionCache *ec) {
388 AtomicAccess::store(&_next, ec);
389 }
390
391 //-----------------------------------------------------------------------------
392
393
394 // Helper used by both find_pc_desc methods.
395 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
396 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
397 if (!approximate) {
398 return pc->pc_offset() == pc_offset;
399 } else {
400 // Do not look before the sentinel
401 assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset");
402 return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset;
403 }
404 }
405
406 void PcDescCache::init_to(PcDesc* initial_pc_desc) {
407 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init);
408 // initialize the cache by filling it with benign (non-null) values
409 assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit,
410 "must start with a sentinel");
411 for (int i = 0; i < cache_size; i++) {
412 _pc_descs[i] = initial_pc_desc;
413 }
414 }
415
416 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
417 // Note: one might think that caching the most recently
418 // read value separately would be a win, but one would be
419 // wrong. When many threads are updating it, the cache
420 // line it's in would bounce between caches, negating
421 // any benefit.
422
423 // In order to prevent race conditions do not load cache elements
424 // repeatedly, but use a local copy:
425 PcDesc* res;
426
427 // Step one: Check the most recently added value.
428 res = _pc_descs[0];
429 assert(res != nullptr, "PcDesc cache should be initialized already");
430
431 // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case.
432 if (approximate && match_desc(res, pc_offset, approximate)) {
433 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
434 return res;
435 }
436
437 // Step two: Check the rest of the LRU cache.
438 for (int i = 1; i < cache_size; ++i) {
439 res = _pc_descs[i];
440 if (res->pc_offset() < 0) break; // optimization: skip empty cache
441 if (match_desc(res, pc_offset, approximate)) {
442 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
443 return res;
444 }
445 }
446
447 // Report failure.
448 return nullptr;
449 }
450
451 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
452 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
453 // Update the LRU cache by shifting pc_desc forward.
454 for (int i = 0; i < cache_size; i++) {
455 PcDesc* next = _pc_descs[i];
456 _pc_descs[i] = pc_desc;
457 pc_desc = next;
458 }
459 }
460
461 // adjust pcs_size so that it is a multiple of both oopSize and
462 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
463 // of oopSize, then 2*sizeof(PcDesc) is)
464 static int adjust_pcs_size(int pcs_size) {
465 int nsize = align_up(pcs_size, oopSize);
466 if ((nsize % sizeof(PcDesc)) != 0) {
467 nsize = pcs_size + sizeof(PcDesc);
468 }
469 assert((nsize % oopSize) == 0, "correct alignment");
470 return nsize;
471 }
472
473 // Returns a string version of the method state.
474 const char* nmethod::state() const {
475 int state = get_state();
476 switch (state) {
477 case not_installed:
478 return "not installed";
479 case in_use:
480 return "in use";
481 case not_entrant:
482 return "not_entrant";
483 default:
484 fatal("unexpected method state: %d", state);
485 return nullptr;
486 }
487 }
488
489 void nmethod::set_deoptimized_done() {
490 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
491 if (_deoptimization_status != deoptimize_done) { // can't go backwards
492 AtomicAccess::store(&_deoptimization_status, deoptimize_done);
493 }
494 }
495
496 ExceptionCache* nmethod::exception_cache_acquire() const {
497 return AtomicAccess::load_acquire(&_exception_cache);
498 }
499
500 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
501 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
502 assert(new_entry != nullptr,"Must be non null");
503 assert(new_entry->next() == nullptr, "Must be null");
504
505 for (;;) {
506 ExceptionCache *ec = exception_cache();
507 if (ec != nullptr) {
508 Klass* ex_klass = ec->exception_type();
509 if (!ex_klass->is_loader_alive()) {
510 // We must guarantee that entries are not inserted with new next pointer
511 // edges to ExceptionCache entries with dead klasses, due to bad interactions
512 // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
513 // the head pointer forward to the first live ExceptionCache, so that the new
514 // next pointers always point at live ExceptionCaches, that are not removed due
515 // to concurrent ExceptionCache cleanup.
516 ExceptionCache* next = ec->next();
517 if (AtomicAccess::cmpxchg(&_exception_cache, ec, next) == ec) {
518 CodeCache::release_exception_cache(ec);
519 }
520 continue;
521 }
522 ec = exception_cache();
523 if (ec != nullptr) {
524 new_entry->set_next(ec);
525 }
526 }
527 if (AtomicAccess::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
528 return;
529 }
530 }
531 }
532
533 void nmethod::clean_exception_cache() {
534 // For each nmethod, only a single thread may call this cleanup function
535 // at the same time, whether called in STW cleanup or concurrent cleanup.
536 // Note that if the GC is processing exception cache cleaning in a concurrent phase,
537 // then a single writer may contend with cleaning up the head pointer to the
538 // first ExceptionCache node that has a Klass* that is alive. That is fine,
539 // as long as there is no concurrent cleanup of next pointers from concurrent writers.
540 // And the concurrent writers do not clean up next pointers, only the head.
541 // Also note that concurrent readers will walk through Klass* pointers that are not
542 // alive. That does not cause ABA problems, because Klass* is deleted after
543 // a handshake with all threads, after all stale ExceptionCaches have been
544 // unlinked. That is also when the CodeCache::exception_cache_purge_list()
545 // is deleted, with all ExceptionCache entries that were cleaned concurrently.
546 // That similarly implies that CAS operations on ExceptionCache entries do not
547 // suffer from ABA problems as unlinking and deletion is separated by a global
548 // handshake operation.
549 ExceptionCache* prev = nullptr;
550 ExceptionCache* curr = exception_cache_acquire();
551
552 while (curr != nullptr) {
553 ExceptionCache* next = curr->next();
554
555 if (!curr->exception_type()->is_loader_alive()) {
556 if (prev == nullptr) {
557 // Try to clean head; this is contended by concurrent inserts, that
558 // both lazily clean the head, and insert entries at the head. If
559 // the CAS fails, the operation is restarted.
560 if (AtomicAccess::cmpxchg(&_exception_cache, curr, next) != curr) {
561 prev = nullptr;
562 curr = exception_cache_acquire();
563 continue;
564 }
565 } else {
566 // It is impossible to during cleanup connect the next pointer to
567 // an ExceptionCache that has not been published before a safepoint
568 // prior to the cleanup. Therefore, release is not required.
569 prev->set_next(next);
570 }
571 // prev stays the same.
572
573 CodeCache::release_exception_cache(curr);
574 } else {
575 prev = curr;
576 }
577
578 curr = next;
579 }
580 }
581
582 // public method for accessing the exception cache
583 // These are the public access methods.
584 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
585 // We never grab a lock to read the exception cache, so we may
586 // have false negatives. This is okay, as it can only happen during
587 // the first few exception lookups for a given nmethod.
588 ExceptionCache* ec = exception_cache_acquire();
589 while (ec != nullptr) {
590 address ret_val;
591 if ((ret_val = ec->match(exception,pc)) != nullptr) {
592 return ret_val;
593 }
594 ec = ec->next();
595 }
596 return nullptr;
597 }
598
599 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
600 // There are potential race conditions during exception cache updates, so we
601 // must own the ExceptionCache_lock before doing ANY modifications. Because
602 // we don't lock during reads, it is possible to have several threads attempt
603 // to update the cache with the same data. We need to check for already inserted
604 // copies of the current data before adding it.
605
606 MutexLocker ml(ExceptionCache_lock);
607 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
608
609 if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) {
610 target_entry = new ExceptionCache(exception,pc,handler);
611 add_exception_cache_entry(target_entry);
612 }
613 }
614
615 // private method for handling exception cache
616 // These methods are private, and used to manipulate the exception cache
617 // directly.
618 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
619 ExceptionCache* ec = exception_cache_acquire();
620 while (ec != nullptr) {
621 if (ec->match_exception_with_space(exception)) {
622 return ec;
623 }
624 ec = ec->next();
625 }
626 return nullptr;
627 }
628
629 bool nmethod::is_at_poll_return(address pc) {
630 RelocIterator iter(this, pc, pc+1);
631 while (iter.next()) {
632 if (iter.type() == relocInfo::poll_return_type)
633 return true;
634 }
635 return false;
636 }
637
638
639 bool nmethod::is_at_poll_or_poll_return(address pc) {
640 RelocIterator iter(this, pc, pc+1);
641 while (iter.next()) {
642 relocInfo::relocType t = iter.type();
643 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
644 return true;
645 }
646 return false;
647 }
648
649 void nmethod::verify_oop_relocations() {
650 // Ensure sure that the code matches the current oop values
651 RelocIterator iter(this, nullptr, nullptr);
652 while (iter.next()) {
653 if (iter.type() == relocInfo::oop_type) {
654 oop_Relocation* reloc = iter.oop_reloc();
655 if (!reloc->oop_is_immediate()) {
656 reloc->verify_oop_relocation();
657 }
658 }
659 }
660 }
661
662
663 ScopeDesc* nmethod::scope_desc_at(address pc) {
664 PcDesc* pd = pc_desc_at(pc);
665 guarantee(pd != nullptr, "scope must be present");
666 return new ScopeDesc(this, pd);
667 }
668
669 ScopeDesc* nmethod::scope_desc_near(address pc) {
670 PcDesc* pd = pc_desc_near(pc);
671 guarantee(pd != nullptr, "scope must be present");
672 return new ScopeDesc(this, pd);
673 }
674
675 address nmethod::oops_reloc_begin() const {
676 // If the method is not entrant then a JMP is plastered over the
677 // first few bytes. If an oop in the old code was there, that oop
678 // should not get GC'd. Skip the first few bytes of oops on
679 // not-entrant methods.
680 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
681 code_begin() + frame_complete_offset() >
682 verified_entry_point() + NativeJump::instruction_size)
683 {
684 // If we have a frame_complete_offset after the native jump, then there
685 // is no point trying to look for oops before that. This is a requirement
686 // for being allowed to scan oops concurrently.
687 return code_begin() + frame_complete_offset();
688 }
689
690 address low_boundary = verified_entry_point();
691 return low_boundary;
692 }
693
694 // Method that knows how to preserve outgoing arguments at call. This method must be
695 // called with a frame corresponding to a Java invoke
696 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
697 if (method() == nullptr) {
698 return;
699 }
700
701 // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
702 JavaThread* thread = reg_map->thread();
703 if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp())
704 JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) {
705 return;
706 }
707
708 if (!method()->is_native()) {
709 address pc = fr.pc();
710 bool has_receiver, has_appendix;
711 Symbol* signature;
712
713 // The method attached by JIT-compilers should be used, if present.
714 // Bytecode can be inaccurate in such case.
715 Method* callee = attached_method_before_pc(pc);
716 if (callee != nullptr) {
717 has_receiver = !(callee->access_flags().is_static());
718 has_appendix = false;
719 signature = callee->signature();
720
721 // If inline types are passed as fields, use the extended signature
722 // which contains the types of all (oop) fields of the inline type.
723 if (is_compiled_by_c2() && callee->has_scalarized_args()) {
724 const GrowableArray<SigEntry>* sig = callee->adapter()->get_sig_cc();
725 assert(sig != nullptr, "sig should never be null");
726 TempNewSymbol tmp_sig = SigEntry::create_symbol(sig);
727 has_receiver = false; // The extended signature contains the receiver type
728 fr.oops_compiled_arguments_do(tmp_sig, has_receiver, has_appendix, reg_map, f);
729 return;
730 }
731 } else {
732 SimpleScopeDesc ssd(this, pc);
733
734 Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
735 has_receiver = call.has_receiver();
736 has_appendix = call.has_appendix();
737 signature = call.signature();
738 }
739
740 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
741 } else if (method()->is_continuation_enter_intrinsic()) {
742 // This method only calls Continuation.enter()
743 Symbol* signature = vmSymbols::continuationEnter_signature();
744 fr.oops_compiled_arguments_do(signature, false, false, reg_map, f);
745 }
746 }
747
748 Method* nmethod::attached_method(address call_instr) {
749 assert(code_contains(call_instr), "not part of the nmethod");
750 RelocIterator iter(this, call_instr, call_instr + 1);
751 while (iter.next()) {
752 if (iter.addr() == call_instr) {
753 switch(iter.type()) {
754 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value();
755 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
756 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value();
757 default: break;
758 }
759 }
760 }
761 return nullptr; // not found
762 }
763
764 Method* nmethod::attached_method_before_pc(address pc) {
765 if (NativeCall::is_call_before(pc)) {
766 NativeCall* ncall = nativeCall_before(pc);
767 return attached_method(ncall->instruction_address());
768 }
769 return nullptr; // not a call
770 }
771
772 void nmethod::clear_inline_caches() {
773 assert(SafepointSynchronize::is_at_safepoint() || (NMethodState_lock->owned_by_self() && is_not_installed()), "clearing of IC's only allowed at safepoint or when not installed");
774 RelocIterator iter(this);
775 while (iter.next()) {
776 iter.reloc()->clear_inline_cache();
777 }
778 }
779
780 #ifdef ASSERT
781 // Check class_loader is alive for this bit of metadata.
782 class CheckClass : public MetadataClosure {
783 void do_metadata(Metadata* md) {
784 Klass* klass = nullptr;
785 if (md->is_klass()) {
786 klass = ((Klass*)md);
787 } else if (md->is_method()) {
788 klass = ((Method*)md)->method_holder();
789 } else if (md->is_methodData()) {
790 klass = ((MethodData*)md)->method()->method_holder();
791 } else if (md->is_methodCounters()) {
792 klass = ((MethodCounters*)md)->method()->method_holder();
793 } else {
794 md->print();
795 ShouldNotReachHere();
796 }
797 assert(klass->is_loader_alive(), "must be alive");
798 }
799 };
800 #endif // ASSERT
801
802 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
803 template <typename CallsiteT>
804 static void clean_if_nmethod_is_unloaded(CallsiteT* callsite, bool clean_all) {
805 CodeBlob* cb = CodeCache::find_blob(callsite->destination());
806 if (!cb->is_nmethod()) {
807 return;
808 }
809 nmethod* nm = cb->as_nmethod();
810 if (clean_all || !nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
811 callsite->set_to_clean();
812 }
813 }
814
815 // Cleans caches in nmethods that point to either classes that are unloaded
816 // or nmethods that are unloaded.
817 //
818 // Can be called either in parallel by G1 currently or after all
819 // nmethods are unloaded. Return postponed=true in the parallel case for
820 // inline caches found that point to nmethods that are not yet visited during
821 // the do_unloading walk.
822 void nmethod::unload_nmethod_caches(bool unloading_occurred) {
823 ResourceMark rm;
824
825 // Exception cache only needs to be called if unloading occurred
826 if (unloading_occurred) {
827 clean_exception_cache();
828 }
829
830 cleanup_inline_caches_impl(unloading_occurred, false);
831
832 #ifdef ASSERT
833 // Check that the metadata embedded in the nmethod is alive
834 CheckClass check_class;
835 metadata_do(&check_class);
836 #endif
837 }
838
839 void nmethod::run_nmethod_entry_barrier() {
840 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
841 if (bs_nm != nullptr) {
842 // We want to keep an invariant that nmethods found through iterations of a Thread's
843 // nmethods found in safepoints have gone through an entry barrier and are not armed.
844 // By calling this nmethod entry barrier, it plays along and acts
845 // like any other nmethod found on the stack of a thread (fewer surprises).
846 nmethod* nm = this;
847 bool alive = bs_nm->nmethod_entry_barrier(nm);
848 assert(alive, "should be alive");
849 }
850 }
851
852 // Only called by whitebox test
853 void nmethod::cleanup_inline_caches_whitebox() {
854 assert_locked_or_safepoint(CodeCache_lock);
855 CompiledICLocker ic_locker(this);
856 cleanup_inline_caches_impl(false /* unloading_occurred */, true /* clean_all */);
857 }
858
859 address* nmethod::orig_pc_addr(const frame* fr) {
860 return (address*) ((address)fr->unextended_sp() + orig_pc_offset());
861 }
862
863 // Called to clean up after class unloading for live nmethods
864 void nmethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
865 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
866 ResourceMark rm;
867
868 // Find all calls in an nmethod and clear the ones that point to bad nmethods.
869 RelocIterator iter(this, oops_reloc_begin());
870 bool is_in_static_stub = false;
871 while(iter.next()) {
872
873 switch (iter.type()) {
874
875 case relocInfo::virtual_call_type:
876 if (unloading_occurred) {
877 // If class unloading occurred we first clear ICs where the cached metadata
878 // is referring to an unloaded klass or method.
879 CompiledIC_at(&iter)->clean_metadata();
880 }
881
882 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), clean_all);
883 break;
884
885 case relocInfo::opt_virtual_call_type:
886 case relocInfo::static_call_type:
887 clean_if_nmethod_is_unloaded(CompiledDirectCall::at(iter.reloc()), clean_all);
888 break;
889
890 case relocInfo::static_stub_type: {
891 is_in_static_stub = true;
892 break;
893 }
894
895 case relocInfo::metadata_type: {
896 // Only the metadata relocations contained in static/opt virtual call stubs
897 // contains the Method* passed to c2i adapters. It is the only metadata
898 // relocation that needs to be walked, as it is the one metadata relocation
899 // that violates the invariant that all metadata relocations have an oop
900 // in the compiled method (due to deferred resolution and code patching).
901
902 // This causes dead metadata to remain in compiled methods that are not
903 // unloading. Unless these slippery metadata relocations of the static
904 // stubs are at least cleared, subsequent class redefinition operations
905 // will access potentially free memory, and JavaThread execution
906 // concurrent to class unloading may call c2i adapters with dead methods.
907 if (!is_in_static_stub) {
908 // The first metadata relocation after a static stub relocation is the
909 // metadata relocation of the static stub used to pass the Method* to
910 // c2i adapters.
911 continue;
912 }
913 is_in_static_stub = false;
914 if (is_unloading()) {
915 // If the nmethod itself is dying, then it may point at dead metadata.
916 // Nobody should follow that metadata; it is strictly unsafe.
917 continue;
918 }
919 metadata_Relocation* r = iter.metadata_reloc();
920 Metadata* md = r->metadata_value();
921 if (md != nullptr && md->is_method()) {
922 Method* method = static_cast<Method*>(md);
923 if (!method->method_holder()->is_loader_alive()) {
924 AtomicAccess::store(r->metadata_addr(), (Method*)nullptr);
925
926 if (!r->metadata_is_immediate()) {
927 r->fix_metadata_relocation();
928 }
929 }
930 }
931 break;
932 }
933
934 default:
935 break;
936 }
937 }
938 }
939
940 address nmethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
941 // Exception happened outside inline-cache check code => we are inside
942 // an active nmethod => use cpc to determine a return address
943 int exception_offset = int(pc - code_begin());
944 int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
945 #ifdef ASSERT
946 if (cont_offset == 0) {
947 Thread* thread = Thread::current();
948 ResourceMark rm(thread);
949 CodeBlob* cb = CodeCache::find_blob(pc);
950 assert(cb != nullptr && cb == this, "");
951
952 // Keep tty output consistent. To avoid ttyLocker, we buffer in stream, and print all at once.
953 stringStream ss;
954 ss.print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
955 print_on(&ss);
956 // Buffering to a stringStream, disable internal buffering so it's not done twice.
957 method()->print_codes_on(&ss, 0, false);
958 print_code_on(&ss);
959 print_pcs_on(&ss);
960 tty->print("%s", ss.as_string()); // print all at once
961 }
962 #endif
963 if (cont_offset == 0) {
964 // Let the normal error handling report the exception
965 return nullptr;
966 }
967 if (cont_offset == exception_offset) {
968 #if INCLUDE_JVMCI
969 Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
970 JavaThread *thread = JavaThread::current();
971 thread->set_jvmci_implicit_exception_pc(pc);
972 thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
973 Deoptimization::Action_reinterpret));
974 return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
975 #else
976 ShouldNotReachHere();
977 #endif
978 }
979 return code_begin() + cont_offset;
980 }
981
982 class HasEvolDependency : public MetadataClosure {
983 bool _has_evol_dependency;
984 public:
985 HasEvolDependency() : _has_evol_dependency(false) {}
986 void do_metadata(Metadata* md) {
987 if (md->is_method()) {
988 Method* method = (Method*)md;
989 if (method->is_old()) {
990 _has_evol_dependency = true;
991 }
992 }
993 }
994 bool has_evol_dependency() const { return _has_evol_dependency; }
995 };
996
997 bool nmethod::has_evol_metadata() {
998 // Check the metadata in relocIter and CompiledIC and also deoptimize
999 // any nmethod that has reference to old methods.
1000 HasEvolDependency check_evol;
1001 metadata_do(&check_evol);
1002 if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
1003 ResourceMark rm;
1004 log_debug(redefine, class, nmethod)
1005 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
1006 _method->method_holder()->external_name(),
1007 _method->name()->as_C_string(),
1008 _method->signature()->as_C_string(),
1009 compile_id());
1010 }
1011 return check_evol.has_evol_dependency();
1012 }
1013
1014 int nmethod::total_size() const {
1015 return
1016 consts_size() +
1017 insts_size() +
1018 stub_size() +
1019 scopes_data_size() +
1020 scopes_pcs_size() +
1021 handler_table_size() +
1022 nul_chk_table_size();
1023 }
1024
1025 const char* nmethod::compile_kind() const {
1026 if (is_osr_method()) return "osr";
1027 if (method() != nullptr && is_native_method()) {
1028 if (method()->is_continuation_native_intrinsic()) {
1029 return "cnt";
1030 }
1031 return "c2n";
1032 }
1033 return nullptr;
1034 }
1035
1036 const char* nmethod::compiler_name() const {
1037 return compilertype2name(_compiler_type);
1038 }
1039
1040 #ifdef ASSERT
1041 class CheckForOopsClosure : public OopClosure {
1042 bool _found_oop = false;
1043 public:
1044 virtual void do_oop(oop* o) { _found_oop = true; }
1045 virtual void do_oop(narrowOop* o) { _found_oop = true; }
1046 bool found_oop() { return _found_oop; }
1047 };
1048 class CheckForMetadataClosure : public MetadataClosure {
1049 bool _found_metadata = false;
1050 Metadata* _ignore = nullptr;
1051 public:
1052 CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {}
1053 virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; }
1054 bool found_metadata() { return _found_metadata; }
1055 };
1056
1057 static void assert_no_oops_or_metadata(nmethod* nm) {
1058 if (nm == nullptr) return;
1059 assert(nm->oop_maps() == nullptr, "expectation");
1060
1061 CheckForOopsClosure cfo;
1062 nm->oops_do(&cfo);
1063 assert(!cfo.found_oop(), "no oops allowed");
1064
1065 // We allow an exception for the own Method, but require its class to be permanent.
1066 Method* own_method = nm->method();
1067 CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method);
1068 nm->metadata_do(&cfm);
1069 assert(!cfm.found_metadata(), "no metadata allowed");
1070
1071 assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(),
1072 "Method's class needs to be permanent");
1073 }
1074 #endif
1075
1076 static int required_mutable_data_size(CodeBuffer* code_buffer,
1077 int jvmci_data_size = 0) {
1078 return align_up(code_buffer->total_relocation_size(), oopSize) +
1079 align_up(code_buffer->total_metadata_size(), oopSize) +
1080 align_up(jvmci_data_size, oopSize);
1081 }
1082
1083 nmethod* nmethod::new_native_nmethod(const methodHandle& method,
1084 int compile_id,
1085 CodeBuffer *code_buffer,
1086 int vep_offset,
1087 int frame_complete,
1088 int frame_size,
1089 ByteSize basic_lock_owner_sp_offset,
1090 ByteSize basic_lock_sp_offset,
1091 OopMapSet* oop_maps,
1092 int exception_handler) {
1093 code_buffer->finalize_oop_references(method);
1094 // create nmethod
1095 nmethod* nm = nullptr;
1096 int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1097 {
1098 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1099
1100 CodeOffsets offsets;
1101 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
1102 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
1103 if (exception_handler != -1) {
1104 offsets.set_value(CodeOffsets::Exceptions, exception_handler);
1105 }
1106
1107 int mutable_data_size = required_mutable_data_size(code_buffer);
1108
1109 // MH intrinsics are dispatch stubs which are compatible with NonNMethod space.
1110 // IsUnloadingBehaviour::is_unloading needs to handle them separately.
1111 bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space();
1112 nm = new (native_nmethod_size, allow_NonNMethod_space)
1113 nmethod(method(), compiler_none, native_nmethod_size,
1114 compile_id, &offsets,
1115 code_buffer, frame_size,
1116 basic_lock_owner_sp_offset,
1117 basic_lock_sp_offset,
1118 oop_maps, mutable_data_size);
1119 DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); )
1120 NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm));
1121 }
1122
1123 if (nm != nullptr) {
1124 // verify nmethod
1125 DEBUG_ONLY(nm->verify();) // might block
1126
1127 nm->log_new_nmethod();
1128 }
1129 return nm;
1130 }
1131
1132 nmethod* nmethod::new_nmethod(const methodHandle& method,
1133 int compile_id,
1134 int entry_bci,
1135 CodeOffsets* offsets,
1136 int orig_pc_offset,
1137 DebugInformationRecorder* debug_info,
1138 Dependencies* dependencies,
1139 CodeBuffer* code_buffer, int frame_size,
1140 OopMapSet* oop_maps,
1141 ExceptionHandlerTable* handler_table,
1142 ImplicitExceptionTable* nul_chk_table,
1143 AbstractCompiler* compiler,
1144 CompLevel comp_level
1145 #if INCLUDE_JVMCI
1146 , char* speculations,
1147 int speculations_len,
1148 JVMCINMethodData* jvmci_data
1149 #endif
1150 )
1151 {
1152 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1153 code_buffer->finalize_oop_references(method);
1154 // create nmethod
1155 nmethod* nm = nullptr;
1156 int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1157
1158 int immutable_data_size =
1159 adjust_pcs_size(debug_info->pcs_size())
1160 + align_up((int)dependencies->size_in_bytes(), oopSize)
1161 + align_up(handler_table->size_in_bytes() , oopSize)
1162 + align_up(nul_chk_table->size_in_bytes() , oopSize)
1163 #if INCLUDE_JVMCI
1164 + align_up(speculations_len , oopSize)
1165 #endif
1166 + align_up(debug_info->data_size() , oopSize);
1167
1168 // First, allocate space for immutable data in C heap.
1169 address immutable_data = nullptr;
1170 if (immutable_data_size > 0) {
1171 immutable_data_size += ImmutableDataRefCountSize;
1172 immutable_data = (address)os::malloc(immutable_data_size, mtCode);
1173 if (immutable_data == nullptr) {
1174 vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data");
1175 return nullptr;
1176 }
1177 }
1178
1179 int mutable_data_size = required_mutable_data_size(code_buffer
1180 JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0)));
1181
1182 {
1183 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1184
1185 nm = new (nmethod_size, comp_level)
1186 nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size,
1187 compile_id, entry_bci, immutable_data, offsets, orig_pc_offset,
1188 debug_info, dependencies, code_buffer, frame_size, oop_maps,
1189 handler_table, nul_chk_table, compiler, comp_level
1190 #if INCLUDE_JVMCI
1191 , speculations,
1192 speculations_len,
1193 jvmci_data
1194 #endif
1195 );
1196
1197 if (nm != nullptr) {
1198 // To make dependency checking during class loading fast, record
1199 // the nmethod dependencies in the classes it is dependent on.
1200 // This allows the dependency checking code to simply walk the
1201 // class hierarchy above the loaded class, checking only nmethods
1202 // which are dependent on those classes. The slow way is to
1203 // check every nmethod for dependencies which makes it linear in
1204 // the number of methods compiled. For applications with a lot
1205 // classes the slow way is too slow.
1206 for (Dependencies::DepStream deps(nm); deps.next(); ) {
1207 if (deps.type() == Dependencies::call_site_target_value) {
1208 // CallSite dependencies are managed on per-CallSite instance basis.
1209 oop call_site = deps.argument_oop(0);
1210 MethodHandles::add_dependent_nmethod(call_site, nm);
1211 } else {
1212 InstanceKlass* ik = deps.context_type();
1213 if (ik == nullptr) {
1214 continue; // ignore things like evol_method
1215 }
1216 // record this nmethod as dependent on this klass
1217 ik->add_dependent_nmethod(nm);
1218 }
1219 }
1220 NOT_PRODUCT(if (nm != nullptr) note_java_nmethod(nm));
1221 }
1222 }
1223 // Do verification and logging outside CodeCache_lock.
1224 if (nm != nullptr) {
1225 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1226 DEBUG_ONLY(nm->verify();)
1227 nm->log_new_nmethod();
1228 }
1229 return nm;
1230 }
1231
1232 // Fill in default values for various fields
1233 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) {
1234 // avoid uninitialized fields, even for short time periods
1235 _exception_cache = nullptr;
1236 _gc_data = nullptr;
1237 _oops_do_mark_link = nullptr;
1238 _compiled_ic_data = nullptr;
1239
1240 _is_unloading_state = 0;
1241 _state = not_installed;
1242
1243 _has_unsafe_access = 0;
1244 _has_wide_vectors = 0;
1245 _has_monitors = 0;
1246 _has_scoped_access = 0;
1247 _has_flushed_dependencies = 0;
1248 _is_unlinked = 0;
1249 _load_reported = 0; // jvmti state
1250
1251 _deoptimization_status = not_marked;
1252
1253 // SECT_CONSTS is first in code buffer so the offset should be 0.
1254 int consts_offset = code_buffer->total_offset_of(code_buffer->consts());
1255 assert(consts_offset == 0, "const_offset: %d", consts_offset);
1256
1257 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
1258
1259 CHECKED_CAST(_entry_offset, uint16_t, (offsets->value(CodeOffsets::Entry)));
1260 CHECKED_CAST(_verified_entry_offset, uint16_t, (offsets->value(CodeOffsets::Verified_Entry)));
1261
1262 _inline_entry_offset = _entry_offset;
1263 _verified_inline_entry_offset = _verified_entry_offset;
1264 _verified_inline_ro_entry_offset = _verified_entry_offset;
1265
1266 _skipped_instructions_size = code_buffer->total_skipped_instructions_size();
1267 }
1268
1269 // Post initialization
1270 void nmethod::post_init() {
1271 clear_unloading_state();
1272
1273 finalize_relocations();
1274
1275 // Flush generated code
1276 ICache::invalidate_range(code_begin(), code_size());
1277
1278 Universe::heap()->register_nmethod(this);
1279
1280 #ifdef COMPILER2
1281 HotCodeCollector::register_nmethod(this);
1282 #endif // COMPILER2
1283
1284 DEBUG_ONLY(Universe::heap()->verify_nmethod(this));
1285
1286 CodeCache::commit(this);
1287 }
1288
1289 // For native wrappers
1290 nmethod::nmethod(
1291 Method* method,
1292 CompilerType type,
1293 int nmethod_size,
1294 int compile_id,
1295 CodeOffsets* offsets,
1296 CodeBuffer* code_buffer,
1297 int frame_size,
1298 ByteSize basic_lock_owner_sp_offset,
1299 ByteSize basic_lock_sp_offset,
1300 OopMapSet* oop_maps,
1301 int mutable_data_size)
1302 : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1303 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1304 _deoptimization_generation(0),
1305 _gc_epoch(CodeCache::gc_epoch()),
1306 _method(method),
1307 _native_receiver_sp_offset(basic_lock_owner_sp_offset),
1308 _native_basic_lock_sp_offset(basic_lock_sp_offset)
1309 {
1310 {
1311 DEBUG_ONLY(NoSafepointVerifier nsv;)
1312 assert_locked_or_safepoint(CodeCache_lock);
1313 assert(!method->has_scalarized_args(), "scalarized native wrappers not supported yet");
1314 init_defaults(code_buffer, offsets);
1315
1316 _osr_entry_point = nullptr;
1317 _pc_desc_container = nullptr;
1318 _entry_bci = InvocationEntryBci;
1319 _compile_id = compile_id;
1320 _comp_level = CompLevel_none;
1321 _compiler_type = type;
1322 _orig_pc_offset = 0;
1323 _num_stack_arg_slots = 0;
1324
1325 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1326 // Continuation enter intrinsic
1327 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1328 } else {
1329 _exception_offset = 0;
1330 }
1331 // Native wrappers do not have deopt handlers. Make the values
1332 // something that will never match a pc like the nmethod vtable entry
1333 _deopt_handler_entry_offset = 0;
1334 _unwind_handler_offset = 0;
1335
1336 int metadata_size = align_up(code_buffer->total_metadata_size(), wordSize);
1337 JVMCI_ONLY( _metadata_size = metadata_size; )
1338 assert(_mutable_data_size == _relocation_size + metadata_size,
1339 "wrong mutable data size: %d != %d + %d",
1340 _mutable_data_size, _relocation_size, metadata_size);
1341
1342 // native wrapper does not have read-only data but we need unique not null address
1343 _immutable_data = blob_end();
1344 _immutable_data_size = 0;
1345 _nul_chk_table_offset = 0;
1346 _handler_table_offset = 0;
1347 _scopes_pcs_offset = 0;
1348 _scopes_data_offset = 0;
1349 #if INCLUDE_JVMCI
1350 _speculations_offset = 0;
1351 #endif
1352 _immutable_data_ref_count_offset = 0;
1353
1354 code_buffer->copy_code_and_locs_to(this);
1355 code_buffer->copy_values_to(this);
1356
1357 post_init();
1358 }
1359
1360 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
1361 ttyLocker ttyl; // keep the following output all in one block
1362 // This output goes directly to the tty, not the compiler log.
1363 // To enable tools to match it up with the compilation activity,
1364 // be sure to tag this tty output with the compile ID.
1365 if (xtty != nullptr) {
1366 xtty->begin_head("print_native_nmethod");
1367 xtty->method(_method);
1368 xtty->stamp();
1369 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
1370 }
1371 // Print the header part, then print the requested information.
1372 // This is both handled in decode2(), called via print_code() -> decode()
1373 if (PrintNativeNMethods) {
1374 tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");
1375 print_code();
1376 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1377 #if defined(SUPPORT_DATA_STRUCTS)
1378 if (AbstractDisassembler::show_structs()) {
1379 if (oop_maps != nullptr) {
1380 tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning
1381 oop_maps->print_on(tty);
1382 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1383 }
1384 }
1385 #endif
1386 } else {
1387 print(); // print the header part only.
1388 }
1389 #if defined(SUPPORT_DATA_STRUCTS)
1390 if (AbstractDisassembler::show_structs()) {
1391 if (PrintRelocations) {
1392 print_relocations();
1393 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1394 }
1395 }
1396 #endif
1397 if (xtty != nullptr) {
1398 xtty->tail("print_native_nmethod");
1399 }
1400 }
1401 }
1402
1403
1404 nmethod::nmethod(const nmethod &nm) : CodeBlob(nm._name, nm._kind, nm._size, nm._header_size)
1405 {
1406
1407 if (nm._oop_maps != nullptr) {
1408 _oop_maps = nm._oop_maps->clone();
1409 } else {
1410 _oop_maps = nullptr;
1411 }
1412
1413 _size = nm._size;
1414 _relocation_size = nm._relocation_size;
1415 _content_offset = nm._content_offset;
1416 _code_offset = nm._code_offset;
1417 _data_offset = nm._data_offset;
1418 _frame_size = nm._frame_size;
1419
1420 S390_ONLY( _ctable_offset = nm._ctable_offset; )
1421
1422 _header_size = nm._header_size;
1423 _frame_complete_offset = nm._frame_complete_offset;
1424
1425 _kind = nm._kind;
1426
1427 _caller_must_gc_arguments = nm._caller_must_gc_arguments;
1428
1429 #ifndef PRODUCT
1430 _asm_remarks.share(nm._asm_remarks);
1431 _dbg_strings.share(nm._dbg_strings);
1432 #endif
1433
1434 // Allocate memory and copy mutable data to C heap
1435 _mutable_data_size = nm._mutable_data_size;
1436 if (_mutable_data_size > 0) {
1437 _mutable_data = (address)os::malloc(_mutable_data_size, mtCode);
1438 if (_mutable_data == nullptr) {
1439 vm_exit_out_of_memory(_mutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for mutable data");
1440 }
1441 memcpy(mutable_data_begin(), nm.mutable_data_begin(), nm.mutable_data_size());
1442 } else {
1443 _mutable_data = nullptr;
1444 }
1445
1446 _deoptimization_generation = 0;
1447 _gc_epoch = CodeCache::gc_epoch();
1448 _method = nm._method;
1449 _osr_link = nullptr;
1450
1451 _exception_cache = nullptr;
1452 _gc_data = nullptr;
1453 _oops_do_mark_nmethods = nullptr;
1454 _oops_do_mark_link = nullptr;
1455 _compiled_ic_data = nullptr;
1456
1457 // Relocate the OSR entry point from nm to the new nmethod.
1458 if (nm._osr_entry_point == nullptr) {
1459 _osr_entry_point = nullptr;
1460 } else {
1461 address new_addr = nm._osr_entry_point - (address) &nm + (address) this;
1462 assert(new_addr >= code_begin() && new_addr < code_end(),
1463 "relocated address must be within code bounds");
1464 _osr_entry_point = new_addr;
1465 }
1466 _entry_offset = nm._entry_offset;
1467 _verified_entry_offset = nm._verified_entry_offset;
1468 _inline_entry_offset = nm._inline_entry_offset;
1469 _verified_inline_entry_offset = nm._verified_inline_entry_offset;
1470 _verified_inline_ro_entry_offset = nm._verified_inline_ro_entry_offset;
1471
1472 _entry_bci = nm._entry_bci;
1473 _immutable_data_size = nm._immutable_data_size;
1474
1475 _skipped_instructions_size = nm._skipped_instructions_size;
1476 _stub_offset = nm._stub_offset;
1477 _exception_offset = nm._exception_offset;
1478 _deopt_handler_entry_offset = nm._deopt_handler_entry_offset;
1479 _unwind_handler_offset = nm._unwind_handler_offset;
1480 _num_stack_arg_slots = nm._num_stack_arg_slots;
1481 #if INCLUDE_JVMCI
1482 _metadata_size = nm._metadata_size;
1483 #endif
1484 _nul_chk_table_offset = nm._nul_chk_table_offset;
1485 _handler_table_offset = nm._handler_table_offset;
1486 _scopes_pcs_offset = nm._scopes_pcs_offset;
1487 _scopes_data_offset = nm._scopes_data_offset;
1488 #if INCLUDE_JVMCI
1489 _speculations_offset = nm._speculations_offset;
1490 #endif
1491 _immutable_data_ref_count_offset = nm._immutable_data_ref_count_offset;
1492
1493 // Increment number of references to immutable data to share it between nmethods
1494 if (_immutable_data_size > 0) {
1495 _immutable_data = nm._immutable_data;
1496 inc_immutable_data_ref_count();
1497 } else {
1498 _immutable_data = blob_end();
1499 }
1500
1501 _orig_pc_offset = nm._orig_pc_offset;
1502 _compile_id = nm._compile_id;
1503 _comp_level = nm._comp_level;
1504 _compiler_type = nm._compiler_type;
1505 _is_unloading_state = nm._is_unloading_state;
1506 _state = not_installed;
1507
1508 _has_unsafe_access = nm._has_unsafe_access;
1509 _has_wide_vectors = nm._has_wide_vectors;
1510 _has_monitors = nm._has_monitors;
1511 _has_scoped_access = nm._has_scoped_access;
1512 _has_flushed_dependencies = nm._has_flushed_dependencies;
1513 _is_unlinked = nm._is_unlinked;
1514 _load_reported = nm._load_reported;
1515
1516 _deoptimization_status = nm._deoptimization_status;
1517
1518 if (nm._pc_desc_container != nullptr) {
1519 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1520 } else {
1521 _pc_desc_container = nullptr;
1522 }
1523
1524 // Copy nmethod contents excluding header
1525 // - Constant part (doubles, longs and floats used in nmethod)
1526 // - Code part:
1527 // - Code body
1528 // - Exception handler
1529 // - Stub code
1530 // - OOP table
1531 memcpy(consts_begin(), nm.consts_begin(), nm.data_end() - nm.consts_begin());
1532
1533 // Fix relocation
1534 RelocIterator iter(this);
1535 CodeBuffer src(&nm);
1536 CodeBuffer dst(this);
1537 while (iter.next()) {
1538 #ifdef USE_TRAMPOLINE_STUB_FIX_OWNER
1539 // After an nmethod is moved, some direct call sites may end up out of range.
1540 // CallRelocation::fix_relocation_after_move() assumes the target is always
1541 // reachable and does not check branch range. Calling it without range checks
1542 // could cause us to write an offset too large for the instruction.
1543 //
1544 // If a call site has a trampoline, we skip the normal call relocation. The
1545 // associated trampoline_stub_Relocation will handle the call and the
1546 // trampoline, including range checks and updating the branch as needed.
1547 //
1548 // If no trampoline exists, we can assume the call target is always
1549 // reachable and therefore within direct branch range, so calling
1550 // CallRelocation::fix_relocation_after_move() is safe.
1551 if (iter.reloc()->is_call()) {
1552 address trampoline = trampoline_stub_Relocation::get_trampoline_for(iter.reloc()->addr(), this);
1553 if (trampoline != nullptr) {
1554 continue;
1555 }
1556 }
1557 #endif
1558
1559 iter.reloc()->fix_relocation_after_move(&src, &dst);
1560 }
1561
1562 {
1563 MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1564 clear_inline_caches();
1565 }
1566
1567 post_init();
1568 }
1569
1570 nmethod* nmethod::relocate(CodeBlobType code_blob_type) {
1571 assert(NMethodRelocation, "must enable use of function");
1572
1573 // Locks required to be held by caller to ensure the nmethod
1574 // is not modified or purged from code cache during relocation
1575 assert_lock_strong(CodeCache_lock);
1576 assert_lock_strong(Compile_lock);
1577 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
1578
1579 if (!is_relocatable()) {
1580 return nullptr;
1581 }
1582
1583 run_nmethod_entry_barrier();
1584 nmethod* nm_copy = new (size(), code_blob_type) nmethod(*this);
1585
1586 if (nm_copy == nullptr) {
1587 return nullptr;
1588 }
1589
1590 // To make dependency checking during class loading fast, record
1591 // the nmethod dependencies in the classes it is dependent on.
1592 // This allows the dependency checking code to simply walk the
1593 // class hierarchy above the loaded class, checking only nmethods
1594 // which are dependent on those classes. The slow way is to
1595 // check every nmethod for dependencies which makes it linear in
1596 // the number of methods compiled. For applications with a lot
1597 // classes the slow way is too slow.
1598 for (Dependencies::DepStream deps(nm_copy); deps.next(); ) {
1599 if (deps.type() == Dependencies::call_site_target_value) {
1600 // CallSite dependencies are managed on per-CallSite instance basis.
1601 oop call_site = deps.argument_oop(0);
1602 MethodHandles::add_dependent_nmethod(call_site, nm_copy);
1603 } else {
1604 InstanceKlass* ik = deps.context_type();
1605 if (ik == nullptr) {
1606 continue; // ignore things like evol_method
1607 }
1608 // record this nmethod as dependent on this klass
1609 ik->add_dependent_nmethod(nm_copy);
1610 }
1611 }
1612
1613 MutexLocker ml_NMethodState_lock(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1614
1615 // Verify the nm we copied from is still valid
1616 if (!is_marked_for_deoptimization() && is_in_use()) {
1617 assert(method() != nullptr && method()->code() == this, "should be if is in use");
1618
1619 // Attempt to start using the copy
1620 if (nm_copy->make_in_use()) {
1621 methodHandle mh(Thread::current(), nm_copy->method());
1622 nm_copy->method()->set_code(mh, nm_copy);
1623
1624 make_not_entrant(InvalidationReason::RELOCATED);
1625
1626 nm_copy->post_compiled_method_load_event();
1627
1628 nm_copy->log_relocated_nmethod(this);
1629
1630 return nm_copy;
1631 }
1632 }
1633
1634 nm_copy->make_not_used();
1635
1636 return nullptr;
1637 }
1638
1639 bool nmethod::is_relocatable() {
1640 if (!is_java_method()) {
1641 return false;
1642 }
1643
1644 if (!is_in_use()) {
1645 return false;
1646 }
1647
1648 if (is_osr_method()) {
1649 return false;
1650 }
1651
1652 if (is_marked_for_deoptimization()) {
1653 return false;
1654 }
1655
1656 #if INCLUDE_JVMCI
1657 if (jvmci_nmethod_data() != nullptr && jvmci_nmethod_data()->has_mirror()) {
1658 return false;
1659 }
1660 #endif
1661
1662 if (is_unloading()) {
1663 return false;
1664 }
1665
1666 if (has_evol_metadata()) {
1667 return false;
1668 }
1669
1670 return true;
1671 }
1672
1673 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
1674 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
1675 }
1676
1677 void* nmethod::operator new(size_t size, int nmethod_size, CodeBlobType code_blob_type) throw () {
1678 return CodeCache::allocate(nmethod_size, code_blob_type);
1679 }
1680
1681 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () {
1682 // Try MethodNonProfiled and MethodProfiled.
1683 void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled);
1684 if (return_value != nullptr || !allow_NonNMethod_space) return return_value;
1685 // Try NonNMethod or give up.
1686 return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod);
1687 }
1688
1689 // For normal JIT compiled code
1690 nmethod::nmethod(
1691 Method* method,
1692 CompilerType type,
1693 int nmethod_size,
1694 int immutable_data_size,
1695 int mutable_data_size,
1696 int compile_id,
1697 int entry_bci,
1698 address immutable_data,
1699 CodeOffsets* offsets,
1700 int orig_pc_offset,
1701 DebugInformationRecorder* debug_info,
1702 Dependencies* dependencies,
1703 CodeBuffer *code_buffer,
1704 int frame_size,
1705 OopMapSet* oop_maps,
1706 ExceptionHandlerTable* handler_table,
1707 ImplicitExceptionTable* nul_chk_table,
1708 AbstractCompiler* compiler,
1709 CompLevel comp_level
1710 #if INCLUDE_JVMCI
1711 , char* speculations,
1712 int speculations_len,
1713 JVMCINMethodData* jvmci_data
1714 #endif
1715 )
1716 : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1717 offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1718 _deoptimization_generation(0),
1719 _gc_epoch(CodeCache::gc_epoch()),
1720 _method(method),
1721 _osr_link(nullptr)
1722 {
1723 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1724 {
1725 DEBUG_ONLY(NoSafepointVerifier nsv;)
1726 assert_locked_or_safepoint(CodeCache_lock);
1727
1728 init_defaults(code_buffer, offsets);
1729
1730 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
1731 _entry_bci = entry_bci;
1732 _compile_id = compile_id;
1733 _comp_level = comp_level;
1734 _compiler_type = type;
1735 _orig_pc_offset = orig_pc_offset;
1736
1737 _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots();
1738
1739 set_ctable_begin(header_begin() + content_offset());
1740
1741 #if INCLUDE_JVMCI
1742 if (compiler->is_jvmci()) {
1743 // JVMCI might not produce any stub sections
1744 if (offsets->value(CodeOffsets::Exceptions) != -1) {
1745 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);
1746 } else {
1747 _exception_offset = -1;
1748 }
1749 if (offsets->value(CodeOffsets::Deopt) != -1) {
1750 _deopt_handler_entry_offset = code_offset() + offsets->value(CodeOffsets::Deopt);
1751 } else {
1752 _deopt_handler_entry_offset = -1;
1753 }
1754 } else
1755 #endif
1756 {
1757 // Exception handler and deopt handler are in the stub section
1758 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");
1759
1760 bool has_exception_handler = (offsets->value(CodeOffsets::Exceptions) != -1);
1761 assert(has_exception_handler == (compiler->type() != compiler_c2),
1762 "C2 compiler doesn't provide exception handler stub code.");
1763 if (has_exception_handler) {
1764 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);
1765 } else {
1766 _exception_offset = -1;
1767 }
1768
1769 _deopt_handler_entry_offset = _stub_offset + offsets->value(CodeOffsets::Deopt);
1770 }
1771 if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
1772 // C1 generates UnwindHandler at the end of instructions section.
1773 // Calculate positive offset as distance between the start of stubs section
1774 // (which is also the end of instructions section) and the start of the handler.
1775 int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
1776 CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset));
1777 } else {
1778 _unwind_handler_offset = -1;
1779 }
1780
1781 int metadata_size = align_up(code_buffer->total_metadata_size(), wordSize);
1782 JVMCI_ONLY( _metadata_size = metadata_size; )
1783 int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize));
1784 if (offsets->value(CodeOffsets::Inline_Entry) != CodeOffsets::no_such_entry_point) {
1785 CHECKED_CAST(_inline_entry_offset , uint16_t, offsets->value(CodeOffsets::Inline_Entry));
1786 }
1787 if (offsets->value(CodeOffsets::Verified_Inline_Entry) != CodeOffsets::no_such_entry_point) {
1788 CHECKED_CAST(_verified_inline_entry_offset , uint16_t, offsets->value(CodeOffsets::Verified_Inline_Entry));
1789 }
1790 if (offsets->value(CodeOffsets::Verified_Inline_Entry_RO) != CodeOffsets::no_such_entry_point) {
1791 CHECKED_CAST(_verified_inline_ro_entry_offset, uint16_t, offsets->value(CodeOffsets::Verified_Inline_Entry_RO));
1792 }
1793
1794 assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size,
1795 "wrong mutable data size: %d != %d + %d + %d",
1796 _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size);
1797 assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d",
1798 nmethod_size, (int)(code_end() - header_begin()));
1799
1800 _immutable_data_size = immutable_data_size;
1801 if (immutable_data_size > 0) {
1802 assert(immutable_data != nullptr, "required");
1803 _immutable_data = immutable_data;
1804 } else {
1805 // We need unique not null address
1806 _immutable_data = blob_end();
1807 }
1808 CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize)));
1809 CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize)));
1810 _scopes_pcs_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);
1811 _scopes_data_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());
1812
1813 #if INCLUDE_JVMCI
1814 _speculations_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1815 _immutable_data_ref_count_offset = _speculations_offset + align_up(speculations_len, oopSize);
1816 #else
1817 _immutable_data_ref_count_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize);
1818 #endif
1819 DEBUG_ONLY( int immutable_data_end_offset = _immutable_data_ref_count_offset + ImmutableDataRefCountSize; )
1820 assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d",
1821 immutable_data_end_offset, immutable_data_size);
1822
1823 // Copy code and relocation info
1824 code_buffer->copy_code_and_locs_to(this);
1825 // Copy oops and metadata
1826 code_buffer->copy_values_to(this);
1827 dependencies->copy_to(this);
1828 // Copy PcDesc and ScopeDesc data
1829 debug_info->copy_to(this);
1830
1831 // Create cache after PcDesc data is copied - it will be used to initialize cache
1832 _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1833
1834 #if INCLUDE_JVMCI
1835 if (compiler->is_jvmci()) {
1836 // Initialize the JVMCINMethodData object inlined into nm
1837 jvmci_nmethod_data()->copy(jvmci_data);
1838 }
1839 #endif
1840
1841 // Copy contents of ExceptionHandlerTable to nmethod
1842 handler_table->copy_to(this);
1843 nul_chk_table->copy_to(this);
1844
1845 #if INCLUDE_JVMCI
1846 // Copy speculations to nmethod
1847 if (speculations_size() != 0) {
1848 memcpy(speculations_begin(), speculations, speculations_len);
1849 }
1850 #endif
1851 init_immutable_data_ref_count();
1852
1853 post_init();
1854
1855 // we use the information of entry points to find out if a method is
1856 // static or non static
1857 assert(compiler->is_c2() || compiler->is_jvmci() ||
1858 _method->is_static() == (entry_point() == verified_entry_point()),
1859 " entry points must be same for static methods and vice versa");
1860 }
1861 }
1862
1863 // Print a short set of xml attributes to identify this nmethod. The
1864 // output should be embedded in some other element.
1865 void nmethod::log_identity(xmlStream* log) const {
1866 log->print(" compile_id='%d'", compile_id());
1867 const char* nm_kind = compile_kind();
1868 if (nm_kind != nullptr) log->print(" compile_kind='%s'", nm_kind);
1869 log->print(" compiler='%s'", compiler_name());
1870 if (TieredCompilation) {
1871 log->print(" level='%d'", comp_level());
1872 }
1873 #if INCLUDE_JVMCI
1874 if (jvmci_nmethod_data() != nullptr) {
1875 const char* jvmci_name = jvmci_nmethod_data()->name();
1876 if (jvmci_name != nullptr) {
1877 log->print(" jvmci_mirror_name='");
1878 log->text("%s", jvmci_name);
1879 log->print("'");
1880 }
1881 }
1882 #endif
1883 }
1884
1885
1886 #define LOG_OFFSET(log, name) \
1887 if (p2i(name##_end()) - p2i(name##_begin())) \
1888 log->print(" " XSTR(name) "_offset='%zd'" , \
1889 p2i(name##_begin()) - p2i(this))
1890
1891
1892 void nmethod::log_new_nmethod() const {
1893 if (LogCompilation && xtty != nullptr) {
1894 ttyLocker ttyl;
1895 xtty->begin_elem("nmethod");
1896 log_identity(xtty);
1897 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1898 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));
1899
1900 LOG_OFFSET(xtty, relocation);
1901 LOG_OFFSET(xtty, consts);
1902 LOG_OFFSET(xtty, insts);
1903 LOG_OFFSET(xtty, stub);
1904 LOG_OFFSET(xtty, scopes_data);
1905 LOG_OFFSET(xtty, scopes_pcs);
1906 LOG_OFFSET(xtty, dependencies);
1907 LOG_OFFSET(xtty, handler_table);
1908 LOG_OFFSET(xtty, nul_chk_table);
1909 LOG_OFFSET(xtty, oops);
1910 LOG_OFFSET(xtty, metadata);
1911
1912 xtty->method(method());
1913 xtty->stamp();
1914 xtty->end_elem();
1915 }
1916 }
1917
1918
1919 void nmethod::log_relocated_nmethod(nmethod* original) const {
1920 if (LogCompilation && xtty != nullptr) {
1921 ttyLocker ttyl;
1922 xtty->begin_elem("relocated nmethod");
1923 log_identity(xtty);
1924 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1925
1926 const char* original_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(original));
1927 xtty->print(" original_address='" INTPTR_FORMAT "'", p2i(original));
1928 xtty->print(" original_code_heap='%s'", original_code_heap_name);
1929
1930 const char* new_code_heap_name = CodeCache::get_code_heap_name(CodeCache::get_code_blob_type(this));
1931 xtty->print(" new_address='" INTPTR_FORMAT "'", p2i(this));
1932 xtty->print(" new_code_heap='%s'", new_code_heap_name);
1933
1934 LOG_OFFSET(xtty, relocation);
1935 LOG_OFFSET(xtty, consts);
1936 LOG_OFFSET(xtty, insts);
1937 LOG_OFFSET(xtty, stub);
1938 LOG_OFFSET(xtty, scopes_data);
1939 LOG_OFFSET(xtty, scopes_pcs);
1940 LOG_OFFSET(xtty, dependencies);
1941 LOG_OFFSET(xtty, handler_table);
1942 LOG_OFFSET(xtty, nul_chk_table);
1943 LOG_OFFSET(xtty, oops);
1944 LOG_OFFSET(xtty, metadata);
1945
1946 xtty->method(method());
1947 xtty->stamp();
1948 xtty->end_elem();
1949 }
1950 }
1951
1952 #undef LOG_OFFSET
1953
1954
1955 // Print out more verbose output usually for a newly created nmethod.
1956 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const {
1957 if (st != nullptr) {
1958 ttyLocker ttyl;
1959 if (WizardMode) {
1960 CompileTask::print(st, this, msg, /*short_form:*/ true);
1961 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));
1962 } else {
1963 CompileTask::print(st, this, msg, /*short_form:*/ false);
1964 }
1965 }
1966 }
1967
1968 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) {
1969 bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
1970 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
1971 print_nmethod(printnmethods);
1972 }
1973 }
1974
1975 void nmethod::print_nmethod(bool printmethod) {
1976 ttyLocker ttyl; // keep the following output all in one block
1977 if (xtty != nullptr) {
1978 xtty->begin_head("print_nmethod");
1979 log_identity(xtty);
1980 xtty->stamp();
1981 xtty->end_head();
1982 }
1983 // Print the header part, then print the requested information.
1984 // This is both handled in decode2().
1985 if (printmethod) {
1986 ResourceMark m;
1987 if (is_compiled_by_c1()) {
1988 tty->cr();
1989 tty->print_cr("============================= C1-compiled nmethod ==============================");
1990 }
1991 if (is_compiled_by_jvmci()) {
1992 tty->cr();
1993 tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
1994 }
1995 tty->print_cr("----------------------------------- Assembly -----------------------------------");
1996 decode2(tty);
1997 #if defined(SUPPORT_DATA_STRUCTS)
1998 if (AbstractDisassembler::show_structs()) {
1999 // Print the oops from the underlying CodeBlob as well.
2000 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2001 print_oops(tty);
2002 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2003 print_metadata(tty);
2004 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2005 print_pcs_on(tty);
2006 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2007 if (oop_maps() != nullptr) {
2008 tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
2009 oop_maps()->print_on(tty);
2010 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2011 }
2012 }
2013 #endif
2014 } else {
2015 print(); // print the header part only.
2016 }
2017
2018 #if defined(SUPPORT_DATA_STRUCTS)
2019 if (AbstractDisassembler::show_structs()) {
2020 methodHandle mh(Thread::current(), _method);
2021 if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) {
2022 print_scopes();
2023 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2024 }
2025 if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) {
2026 print_relocations();
2027 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2028 }
2029 if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) {
2030 print_dependencies_on(tty);
2031 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2032 }
2033 if (printmethod || PrintExceptionHandlers) {
2034 print_handler_table();
2035 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2036 print_nul_chk_table();
2037 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2038 }
2039
2040 if (printmethod) {
2041 print_recorded_oops();
2042 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2043 print_recorded_metadata();
2044 tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
2045 }
2046 }
2047 #endif
2048
2049 if (xtty != nullptr) {
2050 xtty->tail("print_nmethod");
2051 }
2052 }
2053
2054
2055 // Promote one word from an assembly-time handle to a live embedded oop.
2056 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
2057 if (handle == nullptr ||
2058 // As a special case, IC oops are initialized to 1 or -1.
2059 handle == (jobject) Universe::non_oop_word()) {
2060 *(void**)dest = handle;
2061 } else {
2062 *dest = JNIHandles::resolve_non_null(handle);
2063 }
2064 }
2065
2066
2067 // Have to have the same name because it's called by a template
2068 void nmethod::copy_values(GrowableArray<jobject>* array) {
2069 int length = array->length();
2070 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
2071 oop* dest = oops_begin();
2072 for (int index = 0 ; index < length; index++) {
2073 initialize_immediate_oop(&dest[index], array->at(index));
2074 }
2075
2076 // Now we can fix up all the oops in the code. We need to do this
2077 // in the code because the assembler uses jobjects as placeholders.
2078 // The code and relocations have already been initialized by the
2079 // CodeBlob constructor, so it is valid even at this early point to
2080 // iterate over relocations and patch the code.
2081 fix_oop_relocations(/*initialize_immediates=*/ true);
2082 }
2083
2084 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
2085 int length = array->length();
2086 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
2087 Metadata** dest = metadata_begin();
2088 for (int index = 0 ; index < length; index++) {
2089 dest[index] = array->at(index);
2090 }
2091 }
2092
2093 bool nmethod::fix_oop_relocations(bool initialize_immediates) {
2094 // re-patch all oop-bearing instructions, just in case some oops moved
2095 RelocIterator iter(this);
2096 bool modified_code = false;
2097 while (iter.next()) {
2098 if (iter.type() == relocInfo::oop_type) {
2099 oop_Relocation* reloc = iter.oop_reloc();
2100 if (!reloc->oop_is_immediate()) {
2101 // Refresh the oop-related bits of this instruction.
2102 reloc->set_value(reloc->value());
2103 modified_code = true;
2104 } else if (initialize_immediates) {
2105 oop* dest = reloc->oop_addr();
2106 jobject obj = *reinterpret_cast<jobject*>(dest);
2107 initialize_immediate_oop(dest, obj);
2108 }
2109 } else if (iter.type() == relocInfo::metadata_type) {
2110 metadata_Relocation* reloc = iter.metadata_reloc();
2111 reloc->fix_metadata_relocation();
2112 modified_code |= !reloc->metadata_is_immediate();
2113 }
2114 }
2115 return modified_code;
2116 }
2117
2118 void nmethod::fix_oop_relocations() {
2119 ICacheInvalidationContext icic;
2120 fix_oop_relocations(&icic);
2121 }
2122
2123 void nmethod::fix_oop_relocations(ICacheInvalidationContext* icic) {
2124 assert(icic != nullptr, "must provide context to track if code was modified");
2125 bool modified_code = fix_oop_relocations(/*initialize_immediates=*/ false);
2126 if (modified_code) {
2127 icic->set_has_modified_code();
2128 }
2129 }
2130
2131 static void install_post_call_nop_displacement(nmethod* nm, address pc) {
2132 NativePostCallNop* nop = nativePostCallNop_at((address) pc);
2133 intptr_t cbaddr = (intptr_t) nm;
2134 intptr_t offset = ((intptr_t) pc) - cbaddr;
2135
2136 int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin()));
2137 if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks
2138 log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset);
2139 } else if (!nop->patch(oopmap_slot, offset)) {
2140 log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
2141 }
2142 }
2143
2144 void nmethod::finalize_relocations() {
2145 NoSafepointVerifier nsv;
2146
2147 GrowableArray<NativeMovConstReg*> virtual_call_data;
2148
2149 // Make sure that post call nops fill in nmethod offsets eagerly so
2150 // we don't have to race with deoptimization
2151 RelocIterator iter(this);
2152 while (iter.next()) {
2153 if (iter.type() == relocInfo::virtual_call_type) {
2154 virtual_call_Relocation* r = iter.virtual_call_reloc();
2155 NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value());
2156 virtual_call_data.append(value);
2157 } else if (iter.type() == relocInfo::post_call_nop_type) {
2158 post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc();
2159 address pc = reloc->addr();
2160 install_post_call_nop_displacement(this, pc);
2161 }
2162 }
2163
2164 if (virtual_call_data.length() > 0) {
2165 // We allocate a block of CompiledICData per nmethod so the GC can purge this faster.
2166 _compiled_ic_data = new CompiledICData[virtual_call_data.length()];
2167 CompiledICData* next_data = _compiled_ic_data;
2168
2169 for (NativeMovConstReg* value : virtual_call_data) {
2170 value->set_data((intptr_t)next_data);
2171 next_data++;
2172 }
2173 }
2174 }
2175
2176 void nmethod::make_deoptimized() {
2177 if (!Continuations::enabled()) {
2178 // Don't deopt this again.
2179 set_deoptimized_done();
2180 return;
2181 }
2182
2183 assert(method() == nullptr || can_be_deoptimized(), "");
2184
2185 CompiledICLocker ml(this);
2186 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2187
2188 // If post call nops have been already patched, we can just bail-out.
2189 if (has_been_deoptimized()) {
2190 return;
2191 }
2192
2193 ResourceMark rm;
2194 RelocIterator iter(this, oops_reloc_begin());
2195
2196 // Assume there will be some calls to make deoptimized.
2197 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2198
2199 while (iter.next()) {
2200
2201 switch (iter.type()) {
2202 case relocInfo::virtual_call_type: {
2203 CompiledIC *ic = CompiledIC_at(&iter);
2204 address pc = ic->end_of_call();
2205 NativePostCallNop* nop = nativePostCallNop_at(pc);
2206 if (nop != nullptr) {
2207 nop->make_deopt();
2208 }
2209 assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2210 break;
2211 }
2212 case relocInfo::static_call_type:
2213 case relocInfo::opt_virtual_call_type: {
2214 CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc());
2215 address pc = csc->end_of_call();
2216 NativePostCallNop* nop = nativePostCallNop_at(pc);
2217 //tty->print_cr(" - static pc %p", pc);
2218 if (nop != nullptr) {
2219 nop->make_deopt();
2220 }
2221 // We can't assert here, there are some calls to stubs / runtime
2222 // that have reloc data and doesn't have a post call NOP.
2223 //assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2224 break;
2225 }
2226 default:
2227 break;
2228 }
2229 }
2230 // Don't deopt this again.
2231 set_deoptimized_done();
2232 }
2233
2234 void nmethod::verify_clean_inline_caches() {
2235 assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2236
2237 ResourceMark rm;
2238 RelocIterator iter(this, oops_reloc_begin());
2239 while(iter.next()) {
2240 switch(iter.type()) {
2241 case relocInfo::virtual_call_type: {
2242 CompiledIC *ic = CompiledIC_at(&iter);
2243 CodeBlob *cb = CodeCache::find_blob(ic->destination());
2244 assert(cb != nullptr, "destination not in CodeBlob?");
2245 nmethod* nm = cb->as_nmethod_or_null();
2246 if (nm != nullptr) {
2247 // Verify that inline caches pointing to bad nmethods are clean
2248 if (!nm->is_in_use() || nm->is_unloading()) {
2249 assert(ic->is_clean(), "IC should be clean");
2250 }
2251 }
2252 break;
2253 }
2254 case relocInfo::static_call_type:
2255 case relocInfo::opt_virtual_call_type: {
2256 CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc());
2257 CodeBlob *cb = CodeCache::find_blob(cdc->destination());
2258 assert(cb != nullptr, "destination not in CodeBlob?");
2259 nmethod* nm = cb->as_nmethod_or_null();
2260 if (nm != nullptr) {
2261 // Verify that inline caches pointing to bad nmethods are clean
2262 if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
2263 assert(cdc->is_clean(), "IC should be clean");
2264 }
2265 }
2266 break;
2267 }
2268 default:
2269 break;
2270 }
2271 }
2272 }
2273
2274 void nmethod::mark_as_maybe_on_stack() {
2275 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2276 AtomicAccess::store(&_gc_epoch, CodeCache::gc_epoch());
2277 }
2278
2279 bool nmethod::is_maybe_on_stack() {
2280 // If the condition below is true, it means that the nmethod was found to
2281 // be alive the previous completed marking cycle.
2282 return AtomicAccess::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle();
2283 }
2284
2285 void nmethod::inc_decompile_count() {
2286 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
2287 // Could be gated by ProfileTraps, but do not bother...
2288 #if INCLUDE_JVMCI
2289 if (jvmci_skip_profile_deopt()) {
2290 return;
2291 }
2292 #endif
2293 Method* m = method();
2294 if (m == nullptr) return;
2295 MethodData* mdo = m->method_data();
2296 if (mdo == nullptr) return;
2297 // There is a benign race here. See comments in methodData.hpp.
2298 mdo->inc_decompile_count();
2299 }
2300
2301 bool nmethod::try_transition(signed char new_state_int) {
2302 signed char new_state = new_state_int;
2303 assert_lock_strong(NMethodState_lock);
2304 signed char old_state = _state;
2305 if (old_state >= new_state) {
2306 // Ensure monotonicity of transitions.
2307 return false;
2308 }
2309 AtomicAccess::store(&_state, new_state);
2310 return true;
2311 }
2312
2313 void nmethod::invalidate_osr_method() {
2314 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
2315 // Remove from list of active nmethods
2316 if (method() != nullptr) {
2317 method()->method_holder()->remove_osr_nmethod(this);
2318 }
2319 }
2320
2321 void nmethod::log_state_change(InvalidationReason invalidation_reason) const {
2322 if (LogCompilation) {
2323 if (xtty != nullptr) {
2324 ttyLocker ttyl; // keep the following output all in one block
2325 xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
2326 os::current_thread_id(), invalidation_reason_to_string(invalidation_reason));
2327 log_identity(xtty);
2328 xtty->stamp();
2329 xtty->end_elem();
2330 }
2331 }
2332
2333 ResourceMark rm;
2334 stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2335 ss.print("made not entrant: %s", invalidation_reason_to_string(invalidation_reason));
2336
2337 CompileTask::print_ul(this, ss.freeze());
2338 if (PrintCompilation) {
2339 print_on_with_msg(tty, ss.freeze());
2340 }
2341 }
2342
2343 void nmethod::unlink_from_method() {
2344 if (method() != nullptr) {
2345 method()->unlink_code(this);
2346 }
2347 }
2348
2349 // Invalidate code
2350 bool nmethod::make_not_entrant(InvalidationReason invalidation_reason) {
2351 // This can be called while the system is already at a safepoint which is ok
2352 NoSafepointVerifier nsv;
2353
2354 if (is_unloading()) {
2355 // If the nmethod is unloading, then it is already not entrant through
2356 // the nmethod entry barriers. No need to do anything; GC will unload it.
2357 return false;
2358 }
2359
2360 if (AtomicAccess::load(&_state) == not_entrant) {
2361 // Avoid taking the lock if already in required state.
2362 // This is safe from races because the state is an end-state,
2363 // which the nmethod cannot back out of once entered.
2364 // No need for fencing either.
2365 return false;
2366 }
2367
2368 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2369
2370 {
2371 // Enter critical section. Does not block for safepoint.
2372 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2373
2374 if (AtomicAccess::load(&_state) == not_entrant) {
2375 // another thread already performed this transition so nothing
2376 // to do, but return false to indicate this.
2377 return false;
2378 }
2379
2380 if (is_osr_method()) {
2381 // This logic is equivalent to the logic below for patching the
2382 // verified entry point of regular methods.
2383 // this effectively makes the osr nmethod not entrant
2384 invalidate_osr_method();
2385 } else {
2386 // The caller can be calling the method statically or through an inline
2387 // cache call.
2388 BarrierSet::barrier_set()->barrier_set_nmethod()->make_not_entrant(this);
2389 }
2390
2391 if (update_recompile_counts()) {
2392 // Mark the method as decompiled.
2393 inc_decompile_count();
2394 }
2395
2396 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2397 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2398 // If nmethod entry barriers are not supported, we won't mark
2399 // nmethods as on-stack when they become on-stack. So we
2400 // degrade to a less accurate flushing strategy, for now.
2401 mark_as_maybe_on_stack();
2402 }
2403
2404 // Change state
2405 bool success = try_transition(not_entrant);
2406 assert(success, "Transition can't fail");
2407
2408 // Log the transition once
2409 log_state_change(invalidation_reason);
2410
2411 // Remove nmethod from method.
2412 unlink_from_method();
2413
2414 } // leave critical region under NMethodState_lock
2415
2416 #if INCLUDE_JVMCI
2417 // Invalidate can't occur while holding the NMethodState_lock
2418 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2419 if (nmethod_data != nullptr) {
2420 nmethod_data->invalidate_nmethod_mirror(this, invalidation_reason);
2421 }
2422 #endif
2423
2424 #ifdef ASSERT
2425 if (is_osr_method() && method() != nullptr) {
2426 // Make sure osr nmethod is invalidated, i.e. not on the list
2427 bool found = method()->method_holder()->remove_osr_nmethod(this);
2428 assert(!found, "osr nmethod should have been invalidated");
2429 }
2430 #endif
2431
2432 return true;
2433 }
2434
2435 // For concurrent GCs, there must be a handshake between unlink and flush
2436 void nmethod::unlink() {
2437 if (is_unlinked()) {
2438 // Already unlinked.
2439 return;
2440 }
2441
2442 flush_dependencies();
2443
2444 // unlink_from_method will take the NMethodState_lock.
2445 // In this case we don't strictly need it when unlinking nmethods from
2446 // the Method, because it is only concurrently unlinked by
2447 // the entry barrier, which acquires the per nmethod lock.
2448 unlink_from_method();
2449
2450 if (is_osr_method()) {
2451 invalidate_osr_method();
2452 }
2453
2454 #if INCLUDE_JVMCI
2455 // Clear the link between this nmethod and a HotSpotNmethod mirror
2456 JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2457 if (nmethod_data != nullptr) {
2458 nmethod_data->invalidate_nmethod_mirror(this, is_cold() ?
2459 nmethod::InvalidationReason::UNLOADING_COLD :
2460 nmethod::InvalidationReason::UNLOADING);
2461 }
2462 #endif
2463
2464 // Post before flushing as jmethodID is being used
2465 post_compiled_method_unload();
2466
2467 // Register for flushing when it is safe. For concurrent class unloading,
2468 // that would be after the unloading handshake, and for STW class unloading
2469 // that would be when getting back to the VM thread.
2470 ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2471 }
2472
2473 void nmethod::purge(bool unregister_nmethod) {
2474
2475 MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2476
2477 // completely deallocate this method
2478 Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, is_osr_method() ? "osr" : "", p2i(this));
2479
2480 LogTarget(Debug, codecache) lt;
2481 if (lt.is_enabled()) {
2482 ResourceMark rm;
2483 LogStream ls(lt);
2484 const char* method_name = method()->name()->as_C_string();
2485 const size_t codecache_capacity = CodeCache::capacity()/1024;
2486 const size_t codecache_free_space = CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024;
2487 ls.print("Flushing nmethod %6d/" INTPTR_FORMAT ", level=%d, osr=%d, cold=%d, epoch=" UINT64_FORMAT ", cold_count=" UINT64_FORMAT ". "
2488 "Cache capacity: %zuKb, free space: %zuKb. method %s (%s)",
2489 _compile_id, p2i(this), _comp_level, is_osr_method(), is_cold(), _gc_epoch, CodeCache::cold_gc_count(),
2490 codecache_capacity, codecache_free_space, method_name, compiler_name());
2491 }
2492
2493 // We need to deallocate any ExceptionCache data.
2494 // Note that we do not need to grab the nmethod lock for this, it
2495 // better be thread safe if we're disposing of it!
2496 ExceptionCache* ec = exception_cache();
2497 while(ec != nullptr) {
2498 ExceptionCache* next = ec->next();
2499 delete ec;
2500 ec = next;
2501 }
2502 if (_pc_desc_container != nullptr) {
2503 delete _pc_desc_container;
2504 }
2505 delete[] _compiled_ic_data;
2506
2507 if (_immutable_data != blob_end()) {
2508 // Free memory if this was the last nmethod referencing immutable data
2509 if (dec_immutable_data_ref_count() == 0) {
2510 os::free(_immutable_data);
2511 }
2512
2513 _immutable_data = blob_end(); // Valid not null address
2514 }
2515
2516 if (unregister_nmethod) {
2517 Universe::heap()->unregister_nmethod(this);
2518 }
2519
2520 #ifdef COMPILER2
2521 HotCodeCollector::unregister_nmethod(this);
2522 #endif // COMPILER2
2523
2524 CodeCache::unregister_old_nmethod(this);
2525
2526 JVMCI_ONLY( _metadata_size = 0; )
2527 CodeBlob::purge();
2528 }
2529
2530 oop nmethod::oop_at(int index) const {
2531 if (index == 0) {
2532 return nullptr;
2533 }
2534
2535 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2536 return bs_nm->oop_load_no_keepalive(this, index);
2537 }
2538
2539 oop nmethod::oop_at_phantom(int index) const {
2540 if (index == 0) {
2541 return nullptr;
2542 }
2543
2544 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2545 return bs_nm->oop_load_phantom(this, index);
2546 }
2547
2548 //
2549 // Notify all classes this nmethod is dependent on that it is no
2550 // longer dependent.
2551
2552 void nmethod::flush_dependencies() {
2553 if (!has_flushed_dependencies()) {
2554 set_has_flushed_dependencies(true);
2555 for (Dependencies::DepStream deps(this); deps.next(); ) {
2556 if (deps.type() == Dependencies::call_site_target_value) {
2557 // CallSite dependencies are managed on per-CallSite instance basis.
2558 oop call_site = deps.argument_oop(0);
2559 MethodHandles::clean_dependency_context(call_site);
2560 } else {
2561 InstanceKlass* ik = deps.context_type();
2562 if (ik == nullptr) {
2563 continue; // ignore things like evol_method
2564 }
2565 // During GC liveness of dependee determines class that needs to be updated.
2566 // The GC may clean dependency contexts concurrently and in parallel.
2567 ik->clean_dependency_context();
2568 }
2569 }
2570 }
2571 }
2572
2573 void nmethod::post_compiled_method(CompileTask* task) {
2574 task->mark_success();
2575 task->set_nm_content_size(content_size());
2576 task->set_nm_insts_size(insts_size());
2577 task->set_nm_total_size(total_size());
2578
2579 // JVMTI -- compiled method notification (must be done outside lock)
2580 post_compiled_method_load_event();
2581
2582 if (CompilationLog::log() != nullptr) {
2583 CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2584 }
2585
2586 const DirectiveSet* directive = task->directive();
2587 maybe_print_nmethod(directive);
2588 }
2589
2590 #if INCLUDE_CDS
2591 static GrowableArrayCHeap<nmethod*, mtClassShared>* _delayed_compiled_method_load_events = nullptr;
2592
2593 void nmethod::add_delayed_compiled_method_load_event(nmethod* nm) {
2594 precond(CDSConfig::is_using_aot_linked_classes());
2595 precond(!ServiceThread::has_started());
2596
2597 // We are still in single threaded stage of VM bootstrap. No need to lock.
2598 if (_delayed_compiled_method_load_events == nullptr) {
2599 _delayed_compiled_method_load_events = new GrowableArrayCHeap<nmethod*, mtClassShared>();
2600 }
2601 _delayed_compiled_method_load_events->append(nm);
2602 }
2603
2604 void nmethod::post_delayed_compiled_method_load_events() {
2605 precond(ServiceThread::has_started());
2606 if (_delayed_compiled_method_load_events != nullptr) {
2607 for (int i = 0; i < _delayed_compiled_method_load_events->length(); i++) {
2608 nmethod* nm = _delayed_compiled_method_load_events->at(i);
2609 nm->post_compiled_method_load_event();
2610 }
2611 delete _delayed_compiled_method_load_events;
2612 _delayed_compiled_method_load_events = nullptr;
2613 }
2614 }
2615 #endif
2616
2617 // ------------------------------------------------------------------
2618 // post_compiled_method_load_event
2619 // new method for install_code() path
2620 // Transfer information from compilation to jvmti
2621 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2622 #if INCLUDE_CDS
2623 if (!ServiceThread::has_started()) {
2624 // With AOT-linked classes, we could compile wrappers for native methods before the
2625 // ServiceThread has been started, so we must delay the events to be posted later.
2626 assert(state == nullptr, "must be");
2627 add_delayed_compiled_method_load_event(this);
2628 return;
2629 }
2630 #endif
2631
2632 // This is a bad time for a safepoint. We don't want
2633 // this nmethod to get unloaded while we're queueing the event.
2634 NoSafepointVerifier nsv;
2635
2636 Method* m = method();
2637 HOTSPOT_COMPILED_METHOD_LOAD(
2638 (char *) m->klass_name()->bytes(),
2639 m->klass_name()->utf8_length(),
2640 (char *) m->name()->bytes(),
2641 m->name()->utf8_length(),
2642 (char *) m->signature()->bytes(),
2643 m->signature()->utf8_length(),
2644 insts_begin(), insts_size());
2645
2646
2647 if (JvmtiExport::should_post_compiled_method_load()) {
2648 // Only post unload events if load events are found.
2649 set_load_reported();
2650 // If a JavaThread hasn't been passed in, let the Service thread
2651 // (which is a real Java thread) post the event
2652 JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2653 if (state == nullptr) {
2654 // Execute any barrier code for this nmethod as if it's called, since
2655 // keeping it alive looks like stack walking.
2656 run_nmethod_entry_barrier();
2657 ServiceThread::enqueue_deferred_event(&event);
2658 } else {
2659 // This enters the nmethod barrier outside in the caller.
2660 state->enqueue_event(&event);
2661 }
2662 }
2663 }
2664
2665 void nmethod::post_compiled_method_unload() {
2666 assert(_method != nullptr, "just checking");
2667 DTRACE_METHOD_UNLOAD_PROBE(method());
2668
2669 // If a JVMTI agent has enabled the CompiledMethodUnload event then
2670 // post the event. The Method* will not be valid when this is freed.
2671
2672 // Don't bother posting the unload if the load event wasn't posted.
2673 if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2674 JvmtiDeferredEvent event =
2675 JvmtiDeferredEvent::compiled_method_unload_event(
2676 method()->jmethod_id(), insts_begin());
2677 ServiceThread::enqueue_deferred_event(&event);
2678 }
2679 }
2680
2681 // Iterate over metadata calling this function. Used by RedefineClasses
2682 void nmethod::metadata_do(MetadataClosure* f) {
2683 {
2684 // Visit all immediate references that are embedded in the instruction stream.
2685 RelocIterator iter(this, oops_reloc_begin());
2686 while (iter.next()) {
2687 if (iter.type() == relocInfo::metadata_type) {
2688 metadata_Relocation* r = iter.metadata_reloc();
2689 // In this metadata, we must only follow those metadatas directly embedded in
2690 // the code. Other metadatas (oop_index>0) are seen as part of
2691 // the metadata section below.
2692 assert(1 == (r->metadata_is_immediate()) +
2693 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2694 "metadata must be found in exactly one place");
2695 if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2696 Metadata* md = r->metadata_value();
2697 if (md != _method) f->do_metadata(md);
2698 }
2699 } else if (iter.type() == relocInfo::virtual_call_type) {
2700 // Check compiledIC holders associated with this nmethod
2701 ResourceMark rm;
2702 CompiledIC *ic = CompiledIC_at(&iter);
2703 ic->metadata_do(f);
2704 }
2705 }
2706 }
2707
2708 // Visit the metadata section
2709 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2710 if (*p == Universe::non_oop_word() || *p == nullptr) continue; // skip non-oops
2711 Metadata* md = *p;
2712 f->do_metadata(md);
2713 }
2714
2715 // Visit metadata not embedded in the other places.
2716 if (_method != nullptr) f->do_metadata(_method);
2717 }
2718
2719 // Heuristic for nuking nmethods even though their oops are live.
2720 // Main purpose is to reduce code cache pressure and get rid of
2721 // nmethods that don't seem to be all that relevant any longer.
2722 bool nmethod::is_cold() {
2723 if (!MethodFlushing || is_not_installed()) {
2724 // No heuristic unloading at all
2725 return false;
2726 }
2727
2728 if (!is_maybe_on_stack() && is_not_entrant()) {
2729 // Not entrant nmethods that are not on any stack can just
2730 // be removed
2731 return true;
2732 }
2733
2734 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2735 if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2736 // On platforms that don't support nmethod entry barriers, we can't
2737 // trust the temporal aspect of the gc epochs. So we can't detect
2738 // cold nmethods on such platforms.
2739 return false;
2740 }
2741
2742 if (!UseCodeCacheFlushing) {
2743 // Bail out if we don't heuristically remove nmethods
2744 return false;
2745 }
2746
2747 // Other code can be phased out more gradually after N GCs
2748 return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2749 }
2750
2751 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2752 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2753 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2754 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2755 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2756
2757 class IsUnloadingState: public AllStatic {
2758 static const uint8_t _is_unloading_mask = 1;
2759 static const uint8_t _is_unloading_shift = 0;
2760 static const uint8_t _unloading_cycle_mask = 6;
2761 static const uint8_t _unloading_cycle_shift = 1;
2762
2763 static uint8_t set_is_unloading(uint8_t state, bool value) {
2764 state &= (uint8_t)~_is_unloading_mask;
2765 if (value) {
2766 state |= 1 << _is_unloading_shift;
2767 }
2768 assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2769 return state;
2770 }
2771
2772 static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2773 state &= (uint8_t)~_unloading_cycle_mask;
2774 state |= (uint8_t)(value << _unloading_cycle_shift);
2775 assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2776 return state;
2777 }
2778
2779 public:
2780 static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2781 static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2782
2783 static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2784 uint8_t state = 0;
2785 state = set_is_unloading(state, is_unloading);
2786 state = set_unloading_cycle(state, unloading_cycle);
2787 return state;
2788 }
2789 };
2790
2791 bool nmethod::is_unloading() {
2792 uint8_t state = AtomicAccess::load(&_is_unloading_state);
2793 bool state_is_unloading = IsUnloadingState::is_unloading(state);
2794 if (state_is_unloading) {
2795 return true;
2796 }
2797 uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2798 uint8_t current_cycle = CodeCache::unloading_cycle();
2799 if (state_unloading_cycle == current_cycle) {
2800 return false;
2801 }
2802
2803 // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2804 // should be unloaded. This can be either because there is a dead oop,
2805 // or because is_cold() heuristically determines it is time to unload.
2806 state_unloading_cycle = current_cycle;
2807 state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2808 uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2809
2810 MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
2811
2812 // Note that if an nmethod has dead oops, everyone will agree that the
2813 // nmethod is_unloading. However, the is_cold heuristics can yield
2814 // different outcomes, so we guard the computed result with a CAS
2815 // to ensure all threads have a shared view of whether an nmethod
2816 // is_unloading or not.
2817 uint8_t found_state = AtomicAccess::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2818
2819 if (found_state == state) {
2820 // First to change state, we win
2821 return state_is_unloading;
2822 } else {
2823 // State already set, so use it
2824 return IsUnloadingState::is_unloading(found_state);
2825 }
2826 }
2827
2828 void nmethod::clear_unloading_state() {
2829 uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2830 AtomicAccess::store(&_is_unloading_state, state);
2831 }
2832
2833
2834 // This is called at the end of the strong tracing/marking phase of a
2835 // GC to unload an nmethod if it contains otherwise unreachable
2836 // oops or is heuristically found to be not important.
2837 void nmethod::do_unloading(bool unloading_occurred) {
2838 // Make sure the oop's ready to receive visitors
2839 if (is_unloading()) {
2840 unlink();
2841 } else {
2842 unload_nmethod_caches(unloading_occurred);
2843 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2844 if (bs_nm != nullptr) {
2845 bs_nm->disarm(this);
2846 }
2847 }
2848 }
2849
2850 void nmethod::oops_do(OopClosure* f) {
2851 // Prevent extra code cache walk for platforms that don't have immediate oops.
2852 if (relocInfo::mustIterateImmediateOopsInCode()) {
2853 RelocIterator iter(this, oops_reloc_begin());
2854
2855 while (iter.next()) {
2856 if (iter.type() == relocInfo::oop_type ) {
2857 oop_Relocation* r = iter.oop_reloc();
2858 // In this loop, we must only follow those oops directly embedded in
2859 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
2860 assert(1 == (r->oop_is_immediate()) +
2861 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2862 "oop must be found in exactly one place");
2863 if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2864 f->do_oop(r->oop_addr());
2865 }
2866 }
2867 }
2868 }
2869
2870 // Scopes
2871 // This includes oop constants not inlined in the code stream.
2872 for (oop* p = oops_begin(); p < oops_end(); p++) {
2873 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2874 f->do_oop(p);
2875 }
2876 }
2877
2878 void nmethod::follow_nmethod(OopIterateClosure* cl) {
2879 // Process oops in the nmethod
2880 oops_do(cl);
2881
2882 // CodeCache unloading support
2883 mark_as_maybe_on_stack();
2884
2885 BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2886 bs_nm->disarm(this);
2887
2888 // There's an assumption made that this function is not used by GCs that
2889 // relocate objects, and therefore we don't call fix_oop_relocations.
2890 }
2891
2892 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2893
2894 void nmethod::oops_do_log_change(const char* state) {
2895 LogTarget(Trace, gc, nmethod) lt;
2896 if (lt.is_enabled()) {
2897 LogStream ls(lt);
2898 CompileTask::print(&ls, this, state, true /* short_form */);
2899 }
2900 }
2901
2902 bool nmethod::oops_do_try_claim() {
2903 if (oops_do_try_claim_weak_request()) {
2904 nmethod* result = oops_do_try_add_to_list_as_weak_done();
2905 assert(result == nullptr, "adding to global list as weak done must always succeed.");
2906 return true;
2907 }
2908 return false;
2909 }
2910
2911 bool nmethod::oops_do_try_claim_weak_request() {
2912 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2913
2914 if ((_oops_do_mark_link == nullptr) &&
2915 (AtomicAccess::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
2916 oops_do_log_change("oops_do, mark weak request");
2917 return true;
2918 }
2919 return false;
2920 }
2921
2922 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
2923 _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
2924 }
2925
2926 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
2927 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2928
2929 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(nullptr, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));
2930 if (old_next == nullptr) {
2931 oops_do_log_change("oops_do, mark strong done");
2932 }
2933 return old_next;
2934 }
2935
2936 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
2937 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2938 assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
2939
2940 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
2941 if (old_next == next) {
2942 oops_do_log_change("oops_do, mark strong request");
2943 }
2944 return old_next;
2945 }
2946
2947 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
2948 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2949 assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
2950
2951 oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
2952 if (old_next == next) {
2953 oops_do_log_change("oops_do, mark weak done -> mark strong done");
2954 return true;
2955 }
2956 return false;
2957 }
2958
2959 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
2960 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2961
2962 assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
2963 extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2964 "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2965
2966 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2967 // Self-loop if needed.
2968 if (old_head == nullptr) {
2969 old_head = this;
2970 }
2971 // Try to install end of list and weak done tag.
2972 if (AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag), mark_link(old_head, claim_weak_done_tag)) == mark_link(this, claim_weak_request_tag)) {
2973 oops_do_log_change("oops_do, mark weak done");
2974 return nullptr;
2975 } else {
2976 return old_head;
2977 }
2978 }
2979
2980 void nmethod::oops_do_add_to_list_as_strong_done() {
2981 assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2982
2983 nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2984 // Self-loop if needed.
2985 if (old_head == nullptr) {
2986 old_head = this;
2987 }
2988 assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
2989 p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2990
2991 oops_do_set_strong_done(old_head);
2992 }
2993
2994 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
2995 if (!oops_do_try_claim_weak_request()) {
2996 // Failed to claim for weak processing.
2997 oops_do_log_change("oops_do, mark weak request fail");
2998 return;
2999 }
3000
3001 p->do_regular_processing(this);
3002
3003 nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
3004 if (old_head == nullptr) {
3005 return;
3006 }
3007 oops_do_log_change("oops_do, mark weak done fail");
3008 // Adding to global list failed, another thread added a strong request.
3009 assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
3010 "must be but is %u", extract_state(_oops_do_mark_link));
3011
3012 oops_do_log_change("oops_do, mark weak request -> mark strong done");
3013
3014 oops_do_set_strong_done(old_head);
3015 // Do missing strong processing.
3016 p->do_remaining_strong_processing(this);
3017 }
3018
3019 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
3020 oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
3021 if (next_raw == nullptr) {
3022 p->do_regular_processing(this);
3023 oops_do_add_to_list_as_strong_done();
3024 return;
3025 }
3026 // Claim failed. Figure out why and handle it.
3027 if (oops_do_has_weak_request(next_raw)) {
3028 oops_do_mark_link* old = next_raw;
3029 // Claim failed because being weak processed (state == "weak request").
3030 // Try to request deferred strong processing.
3031 next_raw = oops_do_try_add_strong_request(old);
3032 if (next_raw == old) {
3033 // Successfully requested deferred strong processing.
3034 return;
3035 }
3036 // Failed because of a concurrent transition. No longer in "weak request" state.
3037 }
3038 if (oops_do_has_any_strong_state(next_raw)) {
3039 // Already claimed for strong processing or requested for such.
3040 return;
3041 }
3042 if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
3043 // Successfully claimed "weak done" as "strong done". Do the missing marking.
3044 p->do_remaining_strong_processing(this);
3045 return;
3046 }
3047 // Claim failed, some other thread got it.
3048 }
3049
3050 void nmethod::oops_do_marking_prologue() {
3051 assert_at_safepoint();
3052
3053 log_trace(gc, nmethod)("oops_do_marking_prologue");
3054 assert(_oops_do_mark_nmethods == nullptr, "must be empty");
3055 }
3056
3057 void nmethod::oops_do_marking_epilogue() {
3058 assert_at_safepoint();
3059
3060 nmethod* next = _oops_do_mark_nmethods;
3061 _oops_do_mark_nmethods = nullptr;
3062 if (next != nullptr) {
3063 nmethod* cur;
3064 do {
3065 cur = next;
3066 next = extract_nmethod(cur->_oops_do_mark_link);
3067 cur->_oops_do_mark_link = nullptr;
3068 DEBUG_ONLY(cur->verify_oop_relocations());
3069
3070 LogTarget(Trace, gc, nmethod) lt;
3071 if (lt.is_enabled()) {
3072 LogStream ls(lt);
3073 CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
3074 }
3075 // End if self-loop has been detected.
3076 } while (cur != next);
3077 }
3078 log_trace(gc, nmethod)("oops_do_marking_epilogue");
3079 }
3080
3081 inline bool includes(void* p, void* from, void* to) {
3082 return from <= p && p < to;
3083 }
3084
3085
3086 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
3087 assert(count >= 2, "must be sentinel values, at least");
3088
3089 #ifdef ASSERT
3090 // must be sorted and unique; we do a binary search in find_pc_desc()
3091 int prev_offset = pcs[0].pc_offset();
3092 assert(prev_offset == PcDesc::lower_offset_limit,
3093 "must start with a sentinel");
3094 for (int i = 1; i < count; i++) {
3095 int this_offset = pcs[i].pc_offset();
3096 assert(this_offset > prev_offset, "offsets must be sorted");
3097 prev_offset = this_offset;
3098 }
3099 assert(prev_offset == PcDesc::upper_offset_limit,
3100 "must end with a sentinel");
3101 #endif //ASSERT
3102
3103 int size = count * sizeof(PcDesc);
3104 assert(scopes_pcs_size() >= size, "oob");
3105 memcpy(scopes_pcs_begin(), pcs, size);
3106
3107 // Adjust the final sentinel downward.
3108 PcDesc* last_pc = &scopes_pcs_begin()[count-1];
3109 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
3110 last_pc->set_pc_offset(content_size() + 1);
3111 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
3112 // Fill any rounding gaps with copies of the last record.
3113 last_pc[1] = last_pc[0];
3114 }
3115 // The following assert could fail if sizeof(PcDesc) is not
3116 // an integral multiple of oopSize (the rounding term).
3117 // If it fails, change the logic to always allocate a multiple
3118 // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
3119 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
3120 }
3121
3122 void nmethod::copy_scopes_data(u_char* buffer, int size) {
3123 assert(scopes_data_size() >= size, "oob");
3124 memcpy(scopes_data_begin(), buffer, size);
3125 }
3126
3127 #ifdef ASSERT
3128 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
3129 PcDesc* res = nullptr;
3130 assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
3131 "must start with a sentinel");
3132 // lower + 1 to exclude initial sentinel
3133 for (PcDesc* p = lower + 1; p < upper; p++) {
3134 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc
3135 if (match_desc(p, pc_offset, approximate)) {
3136 if (res == nullptr) {
3137 res = p;
3138 } else {
3139 res = (PcDesc*) badAddress;
3140 }
3141 }
3142 }
3143 return res;
3144 }
3145 #endif
3146
3147
3148 #ifndef PRODUCT
3149 // Version of method to collect statistic
3150 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
3151 PcDesc* lower, PcDesc* upper) {
3152 ++pc_nmethod_stats.pc_desc_queries;
3153 if (approximate) ++pc_nmethod_stats.pc_desc_approx;
3154
3155 PcDesc* desc = _pc_desc_cache.last_pc_desc();
3156 assert(desc != nullptr, "PcDesc cache should be initialized already");
3157 if (desc->pc_offset() == (pc - code_begin)) {
3158 // Cached value matched
3159 ++pc_nmethod_stats.pc_desc_tests;
3160 ++pc_nmethod_stats.pc_desc_repeats;
3161 return desc;
3162 }
3163 return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
3164 }
3165 #endif
3166
3167 // Finds a PcDesc with real-pc equal to "pc"
3168 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
3169 PcDesc* lower_incl, PcDesc* upper_incl) {
3170 if ((pc < code_begin) ||
3171 (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
3172 return nullptr; // PC is wildly out of range
3173 }
3174 int pc_offset = (int) (pc - code_begin);
3175
3176 // Check the PcDesc cache if it contains the desired PcDesc
3177 // (This as an almost 100% hit rate.)
3178 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
3179 if (res != nullptr) {
3180 assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
3181 return res;
3182 }
3183
3184 // Fallback algorithm: quasi-linear search for the PcDesc
3185 // Find the last pc_offset less than the given offset.
3186 // The successor must be the required match, if there is a match at all.
3187 // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
3188 PcDesc* lower = lower_incl; // this is initial sentinel
3189 PcDesc* upper = upper_incl - 1; // exclude final sentinel
3190 if (lower >= upper) return nullptr; // no PcDescs at all
3191
3192 #define assert_LU_OK \
3193 /* invariant on lower..upper during the following search: */ \
3194 assert(lower->pc_offset() < pc_offset, "sanity"); \
3195 assert(upper->pc_offset() >= pc_offset, "sanity")
3196 assert_LU_OK;
3197
3198 // Use the last successful return as a split point.
3199 PcDesc* mid = _pc_desc_cache.last_pc_desc();
3200 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3201 if (mid->pc_offset() < pc_offset) {
3202 lower = mid;
3203 } else {
3204 upper = mid;
3205 }
3206
3207 // Take giant steps at first (4096, then 256, then 16, then 1)
3208 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
3209 const int RADIX = (1 << LOG2_RADIX);
3210 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
3211 while ((mid = lower + step) < upper) {
3212 assert_LU_OK;
3213 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3214 if (mid->pc_offset() < pc_offset) {
3215 lower = mid;
3216 } else {
3217 upper = mid;
3218 break;
3219 }
3220 }
3221 assert_LU_OK;
3222 }
3223
3224 // Sneak up on the value with a linear search of length ~16.
3225 while (true) {
3226 assert_LU_OK;
3227 mid = lower + 1;
3228 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3229 if (mid->pc_offset() < pc_offset) {
3230 lower = mid;
3231 } else {
3232 upper = mid;
3233 break;
3234 }
3235 }
3236 #undef assert_LU_OK
3237
3238 if (match_desc(upper, pc_offset, approximate)) {
3239 assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3240 if (!Thread::current_in_asgct()) {
3241 // we don't want to modify the cache if we're in ASGCT
3242 // which is typically called in a signal handler
3243 _pc_desc_cache.add_pc_desc(upper);
3244 }
3245 return upper;
3246 } else {
3247 assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3248 return nullptr;
3249 }
3250 }
3251
3252 bool nmethod::check_dependency_on(DepChange& changes) {
3253 // What has happened:
3254 // 1) a new class dependee has been added
3255 // 2) dependee and all its super classes have been marked
3256 bool found_check = false; // set true if we are upset
3257 for (Dependencies::DepStream deps(this); deps.next(); ) {
3258 // Evaluate only relevant dependencies.
3259 if (deps.spot_check_dependency_at(changes) != nullptr) {
3260 found_check = true;
3261 NOT_DEBUG(break);
3262 }
3263 }
3264 return found_check;
3265 }
3266
3267 // Called from mark_for_deoptimization, when dependee is invalidated.
3268 bool nmethod::is_dependent_on_method(Method* dependee) {
3269 for (Dependencies::DepStream deps(this); deps.next(); ) {
3270 if (Dependencies::has_method_dep(deps.type())) {
3271 Method* method = deps.method_argument(0);
3272 if (method == dependee) return true;
3273 }
3274 }
3275 return false;
3276 }
3277
3278 void nmethod_init() {
3279 // make sure you didn't forget to adjust the filler fields
3280 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
3281 }
3282
3283 // -----------------------------------------------------------------------------
3284 // Verification
3285
3286 class VerifyOopsClosure: public OopClosure {
3287 nmethod* _nm;
3288 bool _ok;
3289 public:
3290 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
3291 bool ok() { return _ok; }
3292 virtual void do_oop(oop* p) {
3293 if (oopDesc::is_oop_or_null(*p)) return;
3294 // Print diagnostic information before calling print_nmethod().
3295 // Assertions therein might prevent call from returning.
3296 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
3297 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
3298 if (_ok) {
3299 _nm->print_nmethod(true);
3300 _ok = false;
3301 }
3302 }
3303 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3304 };
3305
3306 class VerifyMetadataClosure: public MetadataClosure {
3307 public:
3308 void do_metadata(Metadata* md) {
3309 if (md->is_method()) {
3310 Method* method = (Method*)md;
3311 assert(!method->is_old(), "Should not be installing old methods");
3312 }
3313 }
3314 };
3315
3316
3317 void nmethod::verify() {
3318 if (is_not_entrant())
3319 return;
3320
3321 // assert(oopDesc::is_oop(method()), "must be valid");
3322
3323 ResourceMark rm;
3324
3325 if (!CodeCache::contains(this)) {
3326 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
3327 }
3328
3329 if(is_native_method() )
3330 return;
3331
3332 nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
3333 if (nm != this) {
3334 fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
3335 }
3336
3337 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3338 if (! p->verify(this)) {
3339 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
3340 }
3341 }
3342
3343 #ifdef ASSERT
3344 #if INCLUDE_JVMCI
3345 {
3346 // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
3347 ImmutableOopMapSet* oms = oop_maps();
3348 ImplicitExceptionTable implicit_table(this);
3349 for (uint i = 0; i < implicit_table.len(); i++) {
3350 int exec_offset = (int) implicit_table.get_exec_offset(i);
3351 if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
3352 assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
3353 bool found = false;
3354 for (int i = 0, imax = oms->count(); i < imax; i++) {
3355 if (oms->pair_at(i)->pc_offset() == exec_offset) {
3356 found = true;
3357 break;
3358 }
3359 }
3360 assert(found, "missing oopmap");
3361 }
3362 }
3363 }
3364 #endif
3365 #endif
3366
3367 VerifyOopsClosure voc(this);
3368 oops_do(&voc);
3369 assert(voc.ok(), "embedded oops must be OK");
3370 Universe::heap()->verify_nmethod(this);
3371
3372 assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3373 nm->method()->external_name(), p2i(_oops_do_mark_link));
3374 verify_scopes();
3375
3376 CompiledICLocker nm_verify(this);
3377 VerifyMetadataClosure vmc;
3378 metadata_do(&vmc);
3379 }
3380
3381
3382 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3383
3384 // Verify IC only when nmethod installation is finished.
3385 if (!is_not_installed()) {
3386 if (CompiledICLocker::is_safe(this)) {
3387 if (is_inline_cache) {
3388 CompiledIC_at(this, call_site);
3389 } else {
3390 CompiledDirectCall::at(call_site);
3391 }
3392 } else {
3393 CompiledICLocker ml_verify(this);
3394 if (is_inline_cache) {
3395 CompiledIC_at(this, call_site);
3396 } else {
3397 CompiledDirectCall::at(call_site);
3398 }
3399 }
3400 }
3401
3402 HandleMark hm(Thread::current());
3403
3404 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3405 assert(pd != nullptr, "PcDesc must exist");
3406 for (ScopeDesc* sd = new ScopeDesc(this, pd);
3407 !sd->is_top(); sd = sd->sender()) {
3408 sd->verify();
3409 }
3410 }
3411
3412 void nmethod::verify_scopes() {
3413 if( !method() ) return; // Runtime stubs have no scope
3414 if (method()->is_native()) return; // Ignore stub methods.
3415 // iterate through all interrupt point
3416 // and verify the debug information is valid.
3417 RelocIterator iter(this);
3418 while (iter.next()) {
3419 address stub = nullptr;
3420 switch (iter.type()) {
3421 case relocInfo::virtual_call_type:
3422 verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3423 break;
3424 case relocInfo::opt_virtual_call_type:
3425 stub = iter.opt_virtual_call_reloc()->static_stub();
3426 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3427 break;
3428 case relocInfo::static_call_type:
3429 stub = iter.static_call_reloc()->static_stub();
3430 verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3431 break;
3432 case relocInfo::runtime_call_type:
3433 case relocInfo::runtime_call_w_cp_type: {
3434 address destination = iter.reloc()->value();
3435 // Right now there is no way to find out which entries support
3436 // an interrupt point. It would be nice if we had this
3437 // information in a table.
3438 break;
3439 }
3440 default:
3441 break;
3442 }
3443 assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3444 }
3445 }
3446
3447
3448 // -----------------------------------------------------------------------------
3449 // Printing operations
3450
3451 void nmethod::print_on_impl(outputStream* st) const {
3452 ResourceMark rm;
3453
3454 st->print("Compiled method ");
3455
3456 if (is_compiled_by_c1()) {
3457 st->print("(c1) ");
3458 } else if (is_compiled_by_c2()) {
3459 st->print("(c2) ");
3460 } else if (is_compiled_by_jvmci()) {
3461 st->print("(JVMCI) ");
3462 } else {
3463 st->print("(n/a) ");
3464 }
3465
3466 print_on_with_msg(st, nullptr);
3467
3468 if (WizardMode) {
3469 st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3470 st->print(" for method " INTPTR_FORMAT , p2i(method()));
3471 st->print(" { ");
3472 st->print_cr("%s ", state());
3473 st->print_cr("}:");
3474 }
3475 if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3476 p2i(this),
3477 p2i(this) + size(),
3478 size());
3479 if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3480 p2i(consts_begin()),
3481 p2i(consts_end()),
3482 consts_size());
3483 if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3484 p2i(insts_begin()),
3485 p2i(insts_end()),
3486 insts_size());
3487 if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3488 p2i(stub_begin()),
3489 p2i(stub_end()),
3490 stub_size());
3491 if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3492 p2i(oops_begin()),
3493 p2i(oops_end()),
3494 oops_size());
3495 if (mutable_data_size () > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3496 p2i(mutable_data_begin()),
3497 p2i(mutable_data_end()),
3498 mutable_data_size());
3499 if (relocation_size () > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3500 p2i(relocation_begin()),
3501 p2i(relocation_end()),
3502 relocation_size());
3503 if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3504 p2i(metadata_begin()),
3505 p2i(metadata_end()),
3506 metadata_size());
3507 #if INCLUDE_JVMCI
3508 if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3509 p2i(jvmci_data_begin()),
3510 p2i(jvmci_data_end()),
3511 jvmci_data_size());
3512 #endif
3513 if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3514 p2i(immutable_data_begin()),
3515 p2i(immutable_data_end()),
3516 immutable_data_size());
3517 if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3518 p2i(dependencies_begin()),
3519 p2i(dependencies_end()),
3520 dependencies_size());
3521 if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3522 p2i(nul_chk_table_begin()),
3523 p2i(nul_chk_table_end()),
3524 nul_chk_table_size());
3525 if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3526 p2i(handler_table_begin()),
3527 p2i(handler_table_end()),
3528 handler_table_size());
3529 if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3530 p2i(scopes_pcs_begin()),
3531 p2i(scopes_pcs_end()),
3532 scopes_pcs_size());
3533 if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3534 p2i(scopes_data_begin()),
3535 p2i(scopes_data_end()),
3536 scopes_data_size());
3537 #if INCLUDE_JVMCI
3538 if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3539 p2i(speculations_begin()),
3540 p2i(speculations_end()),
3541 speculations_size());
3542 #endif
3543 }
3544
3545 void nmethod::print_code() {
3546 ResourceMark m;
3547 ttyLocker ttyl;
3548 // Call the specialized decode method of this class.
3549 decode(tty);
3550 }
3551
3552 #ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3553
3554 void nmethod::print_dependencies_on(outputStream* out) {
3555 ResourceMark rm;
3556 stringStream st;
3557 st.print_cr("Dependencies:");
3558 for (Dependencies::DepStream deps(this); deps.next(); ) {
3559 deps.print_dependency(&st);
3560 InstanceKlass* ctxk = deps.context_type();
3561 if (ctxk != nullptr) {
3562 if (ctxk->is_dependent_nmethod(this)) {
3563 st.print_cr(" [nmethod<=klass]%s", ctxk->external_name());
3564 }
3565 }
3566 deps.log_dependency(); // put it into the xml log also
3567 }
3568 out->print_raw(st.as_string());
3569 }
3570 #endif
3571
3572 #if defined(SUPPORT_DATA_STRUCTS)
3573
3574 // Print the oops from the underlying CodeBlob.
3575 void nmethod::print_oops(outputStream* st) {
3576 ResourceMark m;
3577 st->print("Oops:");
3578 if (oops_begin() < oops_end()) {
3579 st->cr();
3580 for (oop* p = oops_begin(); p < oops_end(); p++) {
3581 Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3582 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3583 if (Universe::contains_non_oop_word(p)) {
3584 st->print_cr("NON_OOP");
3585 continue; // skip non-oops
3586 }
3587 if (*p == nullptr) {
3588 st->print_cr("nullptr-oop");
3589 continue; // skip non-oops
3590 }
3591 (*p)->print_value_on(st);
3592 st->cr();
3593 }
3594 } else {
3595 st->print_cr(" <list empty>");
3596 }
3597 }
3598
3599 // Print metadata pool.
3600 void nmethod::print_metadata(outputStream* st) {
3601 ResourceMark m;
3602 st->print("Metadata:");
3603 if (metadata_begin() < metadata_end()) {
3604 st->cr();
3605 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3606 Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3607 st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3608 if (*p && *p != Universe::non_oop_word()) {
3609 (*p)->print_value_on(st);
3610 }
3611 st->cr();
3612 }
3613 } else {
3614 st->print_cr(" <list empty>");
3615 }
3616 }
3617
3618 #ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3619 void nmethod::print_scopes_on(outputStream* st) {
3620 // Find the first pc desc for all scopes in the code and print it.
3621 ResourceMark rm;
3622 st->print("scopes:");
3623 if (scopes_pcs_begin() < scopes_pcs_end()) {
3624 st->cr();
3625 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3626 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3627 continue;
3628
3629 ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3630 while (sd != nullptr) {
3631 sd->print_on(st, p); // print output ends with a newline
3632 sd = sd->sender();
3633 }
3634 }
3635 } else {
3636 st->print_cr(" <list empty>");
3637 }
3638 }
3639 #endif
3640
3641 #ifndef PRODUCT // RelocIterator does support printing only then.
3642 void nmethod::print_relocations() {
3643 ResourceMark m; // in case methods get printed via the debugger
3644 tty->print_cr("relocations:");
3645 RelocIterator iter(this);
3646 iter.print_on(tty);
3647 }
3648 #endif
3649
3650 void nmethod::print_pcs_on(outputStream* st) {
3651 ResourceMark m; // in case methods get printed via debugger
3652 st->print("pc-bytecode offsets:");
3653 if (scopes_pcs_begin() < scopes_pcs_end()) {
3654 st->cr();
3655 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3656 p->print_on(st, this); // print output ends with a newline
3657 }
3658 } else {
3659 st->print_cr(" <list empty>");
3660 }
3661 }
3662
3663 void nmethod::print_handler_table() {
3664 ExceptionHandlerTable(this).print(code_begin());
3665 }
3666
3667 void nmethod::print_nul_chk_table() {
3668 ImplicitExceptionTable(this).print(code_begin());
3669 }
3670
3671 void nmethod::print_recorded_oop(int log_n, int i) {
3672 void* value;
3673
3674 if (i == 0) {
3675 value = nullptr;
3676 } else {
3677 // Be careful around non-oop words. Don't create an oop
3678 // with that value, or it will assert in verification code.
3679 if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3680 value = Universe::non_oop_word();
3681 } else {
3682 value = oop_at(i);
3683 }
3684 }
3685
3686 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3687
3688 if (value == Universe::non_oop_word()) {
3689 tty->print("non-oop word");
3690 } else {
3691 if (value == nullptr) {
3692 tty->print("nullptr-oop");
3693 } else {
3694 oop_at(i)->print_value_on(tty);
3695 }
3696 }
3697
3698 tty->cr();
3699 }
3700
3701 void nmethod::print_recorded_oops() {
3702 const int n = oops_count();
3703 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3704 tty->print("Recorded oops:");
3705 if (n > 0) {
3706 tty->cr();
3707 for (int i = 0; i < n; i++) {
3708 print_recorded_oop(log_n, i);
3709 }
3710 } else {
3711 tty->print_cr(" <list empty>");
3712 }
3713 }
3714
3715 void nmethod::print_recorded_metadata() {
3716 const int n = metadata_count();
3717 const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3718 tty->print("Recorded metadata:");
3719 if (n > 0) {
3720 tty->cr();
3721 for (int i = 0; i < n; i++) {
3722 Metadata* m = metadata_at(i);
3723 tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3724 if (m == (Metadata*)Universe::non_oop_word()) {
3725 tty->print("non-metadata word");
3726 } else if (m == nullptr) {
3727 tty->print("nullptr-oop");
3728 } else {
3729 Metadata::print_value_on_maybe_null(tty, m);
3730 }
3731 tty->cr();
3732 }
3733 } else {
3734 tty->print_cr(" <list empty>");
3735 }
3736 }
3737 #endif
3738
3739 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3740
3741 void nmethod::print_constant_pool(outputStream* st) {
3742 //-----------------------------------
3743 //---< Print the constant pool >---
3744 //-----------------------------------
3745 int consts_size = this->consts_size();
3746 if ( consts_size > 0 ) {
3747 unsigned char* cstart = this->consts_begin();
3748 unsigned char* cp = cstart;
3749 unsigned char* cend = cp + consts_size;
3750 unsigned int bytes_per_line = 4;
3751 unsigned int CP_alignment = 8;
3752 unsigned int n;
3753
3754 st->cr();
3755
3756 //---< print CP header to make clear what's printed >---
3757 if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3758 n = bytes_per_line;
3759 st->print_cr("[Constant Pool]");
3760 Disassembler::print_location(cp, cstart, cend, st, true, true);
3761 Disassembler::print_hexdata(cp, n, st, true);
3762 st->cr();
3763 } else {
3764 n = (int)((uintptr_t)cp & (bytes_per_line-1));
3765 st->print_cr("[Constant Pool (unaligned)]");
3766 }
3767
3768 //---< print CP contents, bytes_per_line at a time >---
3769 while (cp < cend) {
3770 Disassembler::print_location(cp, cstart, cend, st, true, false);
3771 Disassembler::print_hexdata(cp, n, st, false);
3772 cp += n;
3773 n = bytes_per_line;
3774 st->cr();
3775 }
3776
3777 //---< Show potential alignment gap between constant pool and code >---
3778 cend = code_begin();
3779 if( cp < cend ) {
3780 n = 4;
3781 st->print_cr("[Code entry alignment]");
3782 while (cp < cend) {
3783 Disassembler::print_location(cp, cstart, cend, st, false, false);
3784 cp += n;
3785 st->cr();
3786 }
3787 }
3788 } else {
3789 st->print_cr("[Constant Pool (empty)]");
3790 }
3791 st->cr();
3792 }
3793
3794 #endif
3795
3796 // Disassemble this nmethod.
3797 // Print additional debug information, if requested. This could be code
3798 // comments, block comments, profiling counters, etc.
3799 // The undisassembled format is useful no disassembler library is available.
3800 // The resulting hex dump (with markers) can be disassembled later, or on
3801 // another system, when/where a disassembler library is available.
3802 void nmethod::decode2(outputStream* ost) const {
3803
3804 // Called from frame::back_trace_with_decode without ResourceMark.
3805 ResourceMark rm;
3806
3807 // Make sure we have a valid stream to print on.
3808 outputStream* st = ost ? ost : tty;
3809
3810 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3811 const bool use_compressed_format = true;
3812 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3813 AbstractDisassembler::show_block_comment());
3814 #else
3815 const bool use_compressed_format = Disassembler::is_abstract();
3816 const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3817 AbstractDisassembler::show_block_comment());
3818 #endif
3819
3820 st->cr();
3821 this->print_on(st);
3822 st->cr();
3823
3824 #if defined(SUPPORT_ASSEMBLY)
3825 //----------------------------------
3826 //---< Print real disassembly >---
3827 //----------------------------------
3828 if (! use_compressed_format) {
3829 st->print_cr("[Disassembly]");
3830 Disassembler::decode(const_cast<nmethod*>(this), st);
3831 st->bol();
3832 st->print_cr("[/Disassembly]");
3833 return;
3834 }
3835 #endif
3836
3837 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3838
3839 // Compressed undisassembled disassembly format.
3840 // The following status values are defined/supported:
3841 // = 0 - currently at bol() position, nothing printed yet on current line.
3842 // = 1 - currently at position after print_location().
3843 // > 1 - in the midst of printing instruction stream bytes.
3844 int compressed_format_idx = 0;
3845 int code_comment_column = 0;
3846 const int instr_maxlen = Assembler::instr_maxlen();
3847 const uint tabspacing = 8;
3848 unsigned char* start = this->code_begin();
3849 unsigned char* p = this->code_begin();
3850 unsigned char* end = this->code_end();
3851 unsigned char* pss = p; // start of a code section (used for offsets)
3852
3853 if ((start == nullptr) || (end == nullptr)) {
3854 st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3855 return;
3856 }
3857 #endif
3858
3859 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3860 //---< plain abstract disassembly, no comments or anything, just section headers >---
3861 if (use_compressed_format && ! compressed_with_comments) {
3862 const_cast<nmethod*>(this)->print_constant_pool(st);
3863
3864 st->bol();
3865 st->cr();
3866 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3867 //---< Open the output (Marker for post-mortem disassembler) >---
3868 st->print_cr("[MachCode]");
3869 const char* header = nullptr;
3870 address p0 = p;
3871 while (p < end) {
3872 address pp = p;
3873 while ((p < end) && (header == nullptr)) {
3874 header = nmethod_section_label(p);
3875 pp = p;
3876 p += Assembler::instr_len(p);
3877 }
3878 if (pp > p0) {
3879 AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
3880 p0 = pp;
3881 p = pp;
3882 header = nullptr;
3883 } else if (header != nullptr) {
3884 st->bol();
3885 st->print_cr("%s", header);
3886 header = nullptr;
3887 }
3888 }
3889 //---< Close the output (Marker for post-mortem disassembler) >---
3890 st->bol();
3891 st->print_cr("[/MachCode]");
3892 return;
3893 }
3894 #endif
3895
3896 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3897 //---< abstract disassembly with comments and section headers merged in >---
3898 if (compressed_with_comments) {
3899 const_cast<nmethod*>(this)->print_constant_pool(st);
3900
3901 st->bol();
3902 st->cr();
3903 st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3904 //---< Open the output (Marker for post-mortem disassembler) >---
3905 st->print_cr("[MachCode]");
3906 while ((p < end) && (p != nullptr)) {
3907 const int instruction_size_in_bytes = Assembler::instr_len(p);
3908
3909 //---< Block comments for nmethod. Interrupts instruction stream, if any. >---
3910 // Outputs a bol() before and a cr() after, but only if a comment is printed.
3911 // Prints nmethod_section_label as well.
3912 if (AbstractDisassembler::show_block_comment()) {
3913 print_block_comment(st, p);
3914 if (st->position() == 0) {
3915 compressed_format_idx = 0;
3916 }
3917 }
3918
3919 //---< New location information after line break >---
3920 if (compressed_format_idx == 0) {
3921 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3922 compressed_format_idx = 1;
3923 }
3924
3925 //---< Code comment for current instruction. Address range [p..(p+len)) >---
3926 unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
3927 S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
3928
3929 if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
3930 //---< interrupt instruction byte stream for code comment >---
3931 if (compressed_format_idx > 1) {
3932 st->cr(); // interrupt byte stream
3933 st->cr(); // add an empty line
3934 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3935 }
3936 const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
3937 st->bol();
3938 compressed_format_idx = 0;
3939 }
3940
3941 //---< New location information after line break >---
3942 if (compressed_format_idx == 0) {
3943 code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3944 compressed_format_idx = 1;
3945 }
3946
3947 //---< Nicely align instructions for readability >---
3948 if (compressed_format_idx > 1) {
3949 Disassembler::print_delimiter(st);
3950 }
3951
3952 //---< Now, finally, print the actual instruction bytes >---
3953 unsigned char* p0 = p;
3954 p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
3955 compressed_format_idx += (int)(p - p0);
3956
3957 if (Disassembler::start_newline(compressed_format_idx-1)) {
3958 st->cr();
3959 compressed_format_idx = 0;
3960 }
3961 }
3962 //---< Close the output (Marker for post-mortem disassembler) >---
3963 st->bol();
3964 st->print_cr("[/MachCode]");
3965 return;
3966 }
3967 #endif
3968 }
3969
3970 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3971
3972 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3973 RelocIterator iter(this, begin, end);
3974 bool have_one = false;
3975 while (iter.next()) {
3976 have_one = true;
3977 switch (iter.type()) {
3978 case relocInfo::none: {
3979 // Skip it and check next
3980 break;
3981 }
3982 case relocInfo::oop_type: {
3983 // Get a non-resizable resource-allocated stringStream.
3984 // Our callees make use of (nested) ResourceMarks.
3985 stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
3986 oop_Relocation* r = iter.oop_reloc();
3987 oop obj = r->oop_value();
3988 st.print("oop(");
3989 if (obj == nullptr) st.print("nullptr");
3990 else obj->print_value_on(&st);
3991 st.print(")");
3992 return st.as_string();
3993 }
3994 case relocInfo::metadata_type: {
3995 stringStream st;
3996 metadata_Relocation* r = iter.metadata_reloc();
3997 Metadata* obj = r->metadata_value();
3998 st.print("metadata(");
3999 if (obj == nullptr) st.print("nullptr");
4000 else obj->print_value_on(&st);
4001 st.print(")");
4002 return st.as_string();
4003 }
4004 case relocInfo::runtime_call_type:
4005 case relocInfo::runtime_call_w_cp_type: {
4006 stringStream st;
4007 st.print("runtime_call");
4008 CallRelocation* r = (CallRelocation*)iter.reloc();
4009 address dest = r->destination();
4010 if (StubRoutines::contains(dest)) {
4011 StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
4012 if (desc == nullptr) {
4013 desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
4014 }
4015 if (desc != nullptr) {
4016 st.print(" Stub::%s", desc->name());
4017 return st.as_string();
4018 }
4019 }
4020 CodeBlob* cb = CodeCache::find_blob(dest);
4021 if (cb != nullptr) {
4022 st.print(" %s", cb->name());
4023 } else {
4024 ResourceMark rm;
4025 const int buflen = 1024;
4026 char* buf = NEW_RESOURCE_ARRAY(char, buflen);
4027 int offset;
4028 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
4029 st.print(" %s", buf);
4030 if (offset != 0) {
4031 st.print("+%d", offset);
4032 }
4033 }
4034 }
4035 return st.as_string();
4036 }
4037 case relocInfo::virtual_call_type: {
4038 stringStream st;
4039 st.print_raw("virtual_call");
4040 virtual_call_Relocation* r = iter.virtual_call_reloc();
4041 Method* m = r->method_value();
4042 if (m != nullptr) {
4043 assert(m->is_method(), "");
4044 m->print_short_name(&st);
4045 }
4046 return st.as_string();
4047 }
4048 case relocInfo::opt_virtual_call_type: {
4049 stringStream st;
4050 st.print_raw("optimized virtual_call");
4051 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
4052 Method* m = r->method_value();
4053 if (m != nullptr) {
4054 assert(m->is_method(), "");
4055 m->print_short_name(&st);
4056 }
4057 return st.as_string();
4058 }
4059 case relocInfo::static_call_type: {
4060 stringStream st;
4061 st.print_raw("static_call");
4062 static_call_Relocation* r = iter.static_call_reloc();
4063 Method* m = r->method_value();
4064 if (m != nullptr) {
4065 assert(m->is_method(), "");
4066 m->print_short_name(&st);
4067 }
4068 return st.as_string();
4069 }
4070 case relocInfo::static_stub_type: return "static_stub";
4071 case relocInfo::external_word_type: return "external_word";
4072 case relocInfo::internal_word_type: return "internal_word";
4073 case relocInfo::section_word_type: return "section_word";
4074 case relocInfo::poll_type: return "poll";
4075 case relocInfo::poll_return_type: return "poll_return";
4076 case relocInfo::trampoline_stub_type: return "trampoline_stub";
4077 case relocInfo::entry_guard_type: return "entry_guard";
4078 case relocInfo::post_call_nop_type: return "post_call_nop";
4079 case relocInfo::barrier_type: {
4080 barrier_Relocation* const reloc = iter.barrier_reloc();
4081 stringStream st;
4082 st.print("barrier format=%d", reloc->format());
4083 return st.as_string();
4084 }
4085
4086 case relocInfo::type_mask: return "type_bit_mask";
4087
4088 default: {
4089 stringStream st;
4090 st.print("unknown relocInfo=%d", (int) iter.type());
4091 return st.as_string();
4092 }
4093 }
4094 }
4095 return have_one ? "other" : nullptr;
4096 }
4097
4098 // Return the last scope in (begin..end]
4099 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
4100 PcDesc* p = pc_desc_near(begin+1);
4101 if (p != nullptr && p->real_pc(this) <= end) {
4102 return new ScopeDesc(this, p);
4103 }
4104 return nullptr;
4105 }
4106
4107 const char* nmethod::nmethod_section_label(address pos) const {
4108 const char* label = nullptr;
4109 if (pos == code_begin()) label = "[Instructions begin]";
4110 if (pos == entry_point()) label = "[Entry Point]";
4111 if (pos == inline_entry_point()) label = "[Inline Entry Point]";
4112 if (pos == verified_entry_point()) label = "[Verified Entry Point]";
4113 if (pos == verified_inline_entry_point()) label = "[Verified Inline Entry Point]";
4114 if (pos == verified_inline_ro_entry_point()) label = "[Verified Inline Entry Point (RO)]";
4115 if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]";
4116 // Check stub_code before checking exception_handler or deopt_handler.
4117 if (pos == this->stub_begin()) label = "[Stub Code]";
4118 if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]";
4119 if (JVMCI_ONLY(_deopt_handler_entry_offset != -1 &&) pos == deopt_handler_entry()) label = "[Deopt Handler Entry Point]";
4120 return label;
4121 }
4122
4123 static int maybe_print_entry_label(outputStream* stream, address pos, address entry, const char* label) {
4124 if (pos == entry) {
4125 stream->bol();
4126 stream->print_cr("%s", label);
4127 return 1;
4128 } else {
4129 return 0;
4130 }
4131 }
4132
4133 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
4134 if (print_section_labels) {
4135 int n = 0;
4136 // Multiple entry points may be at the same position. Print them all.
4137 n += maybe_print_entry_label(stream, block_begin, entry_point(), "[Entry Point]");
4138 n += maybe_print_entry_label(stream, block_begin, inline_entry_point(), "[Inline Entry Point]");
4139 n += maybe_print_entry_label(stream, block_begin, verified_entry_point(), "[Verified Entry Point]");
4140 n += maybe_print_entry_label(stream, block_begin, verified_inline_entry_point(), "[Verified Inline Entry Point]");
4141 n += maybe_print_entry_label(stream, block_begin, verified_inline_ro_entry_point(), "[Verified Inline Entry Point (RO)]");
4142 if (n == 0) {
4143 const char* label = nmethod_section_label(block_begin);
4144 if (label != nullptr) {
4145 stream->bol();
4146 stream->print_cr("%s", label);
4147 }
4148 }
4149 }
4150
4151 Method* m = method();
4152 if (m == nullptr || is_osr_method()) {
4153 return;
4154 }
4155
4156 // Print the name of the method (only once)
4157 address low = MIN3(entry_point(),
4158 verified_entry_point(),
4159 inline_entry_point());
4160 // The verified inline entry point and verified inline RO entry point are not always
4161 // used. When they are unused. CodeOffsets::Verified_Inline_Entry(_RO) is -1. Hence,
4162 // the calculated entry point is smaller than the block they are offsetting into.
4163 if (verified_inline_entry_point() >= block_begin) {
4164 low = MIN2(low, verified_inline_entry_point());
4165 }
4166 if (verified_inline_ro_entry_point() >= block_begin) {
4167 low = MIN2(low, verified_inline_ro_entry_point());
4168 }
4169 assert(low != nullptr, "sanity");
4170 if (block_begin == low) {
4171 stream->print(" # ");
4172 m->print_value_on(stream);
4173 stream->cr();
4174 }
4175
4176 // Print the arguments for the 3 types of verified entry points
4177 CompiledEntrySignature ces(m);
4178 ces.compute_calling_conventions(false);
4179 const GrowableArray<SigEntry>* sig_cc;
4180 const VMRegPair* regs;
4181 if (block_begin == verified_entry_point()) {
4182 sig_cc = ces.sig_cc();
4183 regs = ces.regs_cc();
4184 } else if (block_begin == verified_inline_entry_point()) {
4185 sig_cc = ces.sig();
4186 regs = ces.regs();
4187 } else if (block_begin == verified_inline_ro_entry_point()) {
4188 sig_cc = ces.sig_cc_ro();
4189 regs = ces.regs_cc_ro();
4190 } else {
4191 return;
4192 }
4193
4194 bool has_this = !m->is_static();
4195 if (ces.has_inline_recv() && block_begin == verified_entry_point()) {
4196 // <this> argument is scalarized for verified_entry_point()
4197 has_this = false;
4198 }
4199 const char* spname = "sp"; // make arch-specific?
4200 int stack_slot_offset = this->frame_size() * wordSize;
4201 int tab1 = 14, tab2 = 24;
4202 int sig_index = 0;
4203 int arg_index = has_this ? -1 : 0;
4204 bool did_old_sp = false;
4205 for (ExtendedSignature sig = ExtendedSignature(sig_cc, SigEntryFilter()); !sig.at_end(); ++sig) {
4206 bool at_this = (arg_index == -1);
4207 bool at_old_sp = false;
4208 BasicType t = (*sig)._bt;
4209 if (at_this) {
4210 stream->print(" # this: ");
4211 } else {
4212 stream->print(" # parm%d: ", arg_index);
4213 }
4214 stream->move_to(tab1);
4215 VMReg fst = regs[sig_index].first();
4216 VMReg snd = regs[sig_index].second();
4217 if (fst->is_reg()) {
4218 stream->print("%s", fst->name());
4219 if (snd->is_valid()) {
4220 stream->print(":%s", snd->name());
4221 }
4222 } else if (fst->is_stack()) {
4223 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
4224 if (offset == stack_slot_offset) at_old_sp = true;
4225 stream->print("[%s+0x%x]", spname, offset);
4226 } else {
4227 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
4228 }
4229 stream->print(" ");
4230 stream->move_to(tab2);
4231 stream->print("= ");
4232 if (at_this) {
4233 m->method_holder()->print_value_on(stream);
4234 } else {
4235 bool did_name = false;
4236 if (is_reference_type(t) && !(*sig)._vt_oop) {
4237 Symbol* name = (*sig)._name;
4238 name->print_value_on(stream);
4239 did_name = true;
4240 }
4241 if (!did_name)
4242 stream->print("%s", type2name(t));
4243 if ((*sig)._null_marker) {
4244 stream->print(" (null marker)");
4245 }
4246 if ((*sig)._vt_oop) {
4247 stream->print(" (VT OOP)");
4248 }
4249 }
4250 if (at_old_sp) {
4251 stream->print(" (%s of caller)", spname);
4252 did_old_sp = true;
4253 }
4254 stream->cr();
4255 sig_index += type2size[t];
4256 arg_index += 1;
4257 }
4258 if (!did_old_sp) {
4259 stream->print(" # ");
4260 stream->move_to(tab1);
4261 stream->print("[%s+0x%x]", spname, stack_slot_offset);
4262 stream->print(" (%s of caller)", spname);
4263 stream->cr();
4264 }
4265 }
4266
4267 // Returns whether this nmethod has code comments.
4268 bool nmethod::has_code_comment(address begin, address end) {
4269 // scopes?
4270 ScopeDesc* sd = scope_desc_in(begin, end);
4271 if (sd != nullptr) return true;
4272
4273 // relocations?
4274 const char* str = reloc_string_for(begin, end);
4275 if (str != nullptr) return true;
4276
4277 // implicit exceptions?
4278 int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
4279 if (cont_offset != 0) return true;
4280
4281 return false;
4282 }
4283
4284 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
4285 ImplicitExceptionTable implicit_table(this);
4286 int pc_offset = (int)(begin - code_begin());
4287 int cont_offset = implicit_table.continuation_offset(pc_offset);
4288 bool oop_map_required = false;
4289 if (cont_offset != 0) {
4290 st->move_to(column, 6, 0);
4291 if (pc_offset == cont_offset) {
4292 st->print("; implicit exception: deoptimizes");
4293 oop_map_required = true;
4294 } else {
4295 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
4296 }
4297 }
4298
4299 // Find an oopmap in (begin, end]. We use the odd half-closed
4300 // interval so that oop maps and scope descs which are tied to the
4301 // byte after a call are printed with the call itself. OopMaps
4302 // associated with implicit exceptions are printed with the implicit
4303 // instruction.
4304 address base = code_begin();
4305 ImmutableOopMapSet* oms = oop_maps();
4306 if (oms != nullptr) {
4307 for (int i = 0, imax = oms->count(); i < imax; i++) {
4308 const ImmutableOopMapPair* pair = oms->pair_at(i);
4309 const ImmutableOopMap* om = pair->get_from(oms);
4310 address pc = base + pair->pc_offset();
4311 if (pc >= begin) {
4312 #if INCLUDE_JVMCI
4313 bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
4314 #else
4315 bool is_implicit_deopt = false;
4316 #endif
4317 if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
4318 st->move_to(column, 6, 0);
4319 st->print("; ");
4320 om->print_on(st);
4321 oop_map_required = false;
4322 }
4323 }
4324 if (pc > end) {
4325 break;
4326 }
4327 }
4328 }
4329 assert(!oop_map_required, "missed oopmap");
4330
4331 Thread* thread = Thread::current();
4332
4333 // Print any debug info present at this pc.
4334 ScopeDesc* sd = scope_desc_in(begin, end);
4335 if (sd != nullptr) {
4336 st->move_to(column, 6, 0);
4337 if (sd->bci() == SynchronizationEntryBCI) {
4338 st->print(";*synchronization entry");
4339 } else if (sd->bci() == AfterBci) {
4340 st->print(";* method exit (unlocked if synchronized)");
4341 } else if (sd->bci() == UnwindBci) {
4342 st->print(";* unwind (locked if synchronized)");
4343 } else if (sd->bci() == AfterExceptionBci) {
4344 st->print(";* unwind (unlocked if synchronized)");
4345 } else if (sd->bci() == UnknownBci) {
4346 st->print(";* unknown");
4347 } else if (sd->bci() == InvalidFrameStateBci) {
4348 st->print(";* invalid frame state");
4349 } else {
4350 if (sd->method() == nullptr) {
4351 st->print("method is nullptr");
4352 } else if (sd->method()->is_native()) {
4353 st->print("method is native");
4354 } else {
4355 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
4356 st->print(";*%s", Bytecodes::name(bc));
4357 switch (bc) {
4358 case Bytecodes::_invokevirtual:
4359 case Bytecodes::_invokespecial:
4360 case Bytecodes::_invokestatic:
4361 case Bytecodes::_invokeinterface:
4362 {
4363 Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
4364 st->print(" ");
4365 if (invoke.name() != nullptr)
4366 invoke.name()->print_symbol_on(st);
4367 else
4368 st->print("<UNKNOWN>");
4369 break;
4370 }
4371 case Bytecodes::_getfield:
4372 case Bytecodes::_putfield:
4373 case Bytecodes::_getstatic:
4374 case Bytecodes::_putstatic:
4375 {
4376 Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4377 st->print(" ");
4378 if (field.name() != nullptr)
4379 field.name()->print_symbol_on(st);
4380 else
4381 st->print("<UNKNOWN>");
4382 }
4383 default:
4384 break;
4385 }
4386 }
4387 st->print(" {reexecute=%d rethrow=%d return_oop=%d return_scalarized=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop(), sd->return_scalarized());
4388 }
4389
4390 // Print all scopes
4391 for (;sd != nullptr; sd = sd->sender()) {
4392 st->move_to(column, 6, 0);
4393 st->print("; -");
4394 if (sd->should_reexecute()) {
4395 st->print(" (reexecute)");
4396 }
4397 if (sd->method() == nullptr) {
4398 st->print("method is nullptr");
4399 } else {
4400 sd->method()->print_short_name(st);
4401 }
4402 int lineno = sd->method()->line_number_from_bci(sd->bci());
4403 if (lineno != -1) {
4404 st->print("@%d (line %d)", sd->bci(), lineno);
4405 } else {
4406 st->print("@%d", sd->bci());
4407 }
4408 st->cr();
4409 }
4410 }
4411
4412 // Print relocation information
4413 // Prevent memory leak: allocating without ResourceMark.
4414 ResourceMark rm;
4415 const char* str = reloc_string_for(begin, end);
4416 if (str != nullptr) {
4417 if (sd != nullptr) st->cr();
4418 st->move_to(column, 6, 0);
4419 st->print("; {%s}", str);
4420 }
4421 }
4422
4423 #endif
4424
4425 address nmethod::call_instruction_address(address pc) const {
4426 if (NativeCall::is_call_before(pc)) {
4427 NativeCall *ncall = nativeCall_before(pc);
4428 return ncall->instruction_address();
4429 }
4430 return nullptr;
4431 }
4432
4433 void nmethod::print_value_on_impl(outputStream* st) const {
4434 st->print_cr("nmethod");
4435 #if defined(SUPPORT_DATA_STRUCTS)
4436 print_on_with_msg(st, nullptr);
4437 #endif
4438 }
4439
4440 void nmethod::print_code_snippet(outputStream* st, address addr) const {
4441 if (entry_point() <= addr && addr < code_end()) {
4442 // Pointing into the nmethod's code. Try to disassemble some instructions around addr.
4443 // Determine conservative start and end points.
4444 address start;
4445 if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
4446 addr >= code_begin() + frame_complete_offset()) {
4447 start = code_begin() + frame_complete_offset();
4448 } else {
4449 start = (addr < verified_entry_point()) ? entry_point() : verified_entry_point();
4450 }
4451 address start_for_hex_dump = start; // We can choose a different starting point for hex dump, below.
4452 address end = code_end();
4453
4454 // Try using relocations to find closer instruction start and end points.
4455 // (Some platforms have variable length instructions and can only
4456 // disassemble correctly at instruction start addresses.)
4457 RelocIterator iter((nmethod*)this, start);
4458 while (iter.next() && iter.addr() < addr) { // find relocation before addr
4459 // Note: There's a relocation which doesn't point to an instruction start:
4460 // ZBarrierRelocationFormatStoreGoodAfterMov with ZGC on x86_64
4461 // We could detect and skip it, but hex dump is still usable when
4462 // disassembler produces garbage in such a very rare case.
4463 start = iter.addr();
4464 // We want at least 64 Bytes ahead in hex dump.
4465 if (iter.addr() <= (addr - 64)) start_for_hex_dump = iter.addr();
4466 }
4467 if (iter.has_current()) {
4468 if (iter.addr() == addr) iter.next(); // find relocation after addr
4469 if (iter.has_current()) end = iter.addr();
4470 }
4471
4472 // Always print hex. Disassembler may still have problems when hitting an incorrect instruction start.
4473 os::print_hex_dump(st, start_for_hex_dump, end, 1, /* print_ascii=*/false);
4474 if (!Disassembler::is_abstract()) {
4475 Disassembler::decode(start, end, st);
4476 }
4477 }
4478 }
4479
4480 #ifndef PRODUCT
4481
4482 void nmethod::print_calls(outputStream* st) {
4483 RelocIterator iter(this);
4484 while (iter.next()) {
4485 switch (iter.type()) {
4486 case relocInfo::virtual_call_type: {
4487 CompiledICLocker ml_verify(this);
4488 CompiledIC_at(&iter)->print();
4489 break;
4490 }
4491 case relocInfo::static_call_type:
4492 case relocInfo::opt_virtual_call_type:
4493 st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4494 CompiledDirectCall::at(iter.reloc())->print();
4495 break;
4496 default:
4497 break;
4498 }
4499 }
4500 }
4501
4502 void nmethod::print_statistics() {
4503 ttyLocker ttyl;
4504 if (xtty != nullptr) xtty->head("statistics type='nmethod'");
4505 native_nmethod_stats.print_native_nmethod_stats();
4506 #ifdef COMPILER1
4507 c1_java_nmethod_stats.print_nmethod_stats("C1");
4508 #endif
4509 #ifdef COMPILER2
4510 c2_java_nmethod_stats.print_nmethod_stats("C2");
4511 #endif
4512 #if INCLUDE_JVMCI
4513 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4514 #endif
4515 unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4516 DebugInformationRecorder::print_statistics();
4517 pc_nmethod_stats.print_pc_stats();
4518 Dependencies::print_statistics();
4519 ExternalsRecorder::print_statistics();
4520 if (xtty != nullptr) xtty->tail("statistics");
4521 }
4522
4523 #endif // !PRODUCT
4524
4525 #if INCLUDE_JVMCI
4526 void nmethod::update_speculation(JavaThread* thread) {
4527 jlong speculation = thread->pending_failed_speculation();
4528 if (speculation != 0) {
4529 guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4530 jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4531 thread->set_pending_failed_speculation(0);
4532 }
4533 }
4534
4535 const char* nmethod::jvmci_name() {
4536 if (jvmci_nmethod_data() != nullptr) {
4537 return jvmci_nmethod_data()->name();
4538 }
4539 return nullptr;
4540 }
4541
4542 bool nmethod::jvmci_skip_profile_deopt() const {
4543 return jvmci_nmethod_data() != nullptr && !jvmci_nmethod_data()->profile_deopt();
4544 }
4545 #endif