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