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