Thu, 24 May 2018 17:06:56 +0800
Merge
1 /*
2 * Copyright (c) 1997, 2014, 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 */
25 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/compiledIC.hpp"
34 #include "code/dependencies.hpp"
35 #include "code/nmethod.hpp"
36 #include "code/scopeDesc.hpp"
37 #include "compiler/abstractCompiler.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compileLog.hpp"
40 #include "compiler/compilerOracle.hpp"
41 #include "compiler/disassembler.hpp"
42 #include "interpreter/bytecode.hpp"
43 #include "oops/methodData.hpp"
44 #include "prims/jvmtiRedefineClassesTrace.hpp"
45 #include "prims/jvmtiImpl.hpp"
46 #include "runtime/orderAccess.inline.hpp"
47 #include "runtime/sharedRuntime.hpp"
48 #include "runtime/sweeper.hpp"
49 #include "utilities/dtrace.hpp"
50 #include "utilities/events.hpp"
51 #include "utilities/xmlstream.hpp"
52 #ifdef SHARK
53 #include "shark/sharkCompiler.hpp"
54 #endif
56 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
58 unsigned char nmethod::_global_unloading_clock = 0;
60 #ifdef DTRACE_ENABLED
62 // Only bother with this argument setup if dtrace is available
64 #ifndef USDT2
65 HS_DTRACE_PROBE_DECL8(hotspot, compiled__method__load,
66 const char*, int, const char*, int, const char*, int, void*, size_t);
68 HS_DTRACE_PROBE_DECL6(hotspot, compiled__method__unload,
69 char*, int, char*, int, char*, int);
71 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
72 { \
73 Method* m = (method); \
74 if (m != NULL) { \
75 Symbol* klass_name = m->klass_name(); \
76 Symbol* name = m->name(); \
77 Symbol* signature = m->signature(); \
78 HS_DTRACE_PROBE6(hotspot, compiled__method__unload, \
79 klass_name->bytes(), klass_name->utf8_length(), \
80 name->bytes(), name->utf8_length(), \
81 signature->bytes(), signature->utf8_length()); \
82 } \
83 }
84 #else /* USDT2 */
85 #define DTRACE_METHOD_UNLOAD_PROBE(method) \
86 { \
87 Method* m = (method); \
88 if (m != NULL) { \
89 Symbol* klass_name = m->klass_name(); \
90 Symbol* name = m->name(); \
91 Symbol* signature = m->signature(); \
92 HOTSPOT_COMPILED_METHOD_UNLOAD( \
93 (char *) klass_name->bytes(), klass_name->utf8_length(), \
94 (char *) name->bytes(), name->utf8_length(), \
95 (char *) signature->bytes(), signature->utf8_length()); \
96 } \
97 }
98 #endif /* USDT2 */
100 #else // ndef DTRACE_ENABLED
102 #define DTRACE_METHOD_UNLOAD_PROBE(method)
104 #endif
106 bool nmethod::is_compiled_by_c1() const {
107 if (compiler() == NULL) {
108 return false;
109 }
110 return compiler()->is_c1();
111 }
112 bool nmethod::is_compiled_by_c2() const {
113 if (compiler() == NULL) {
114 return false;
115 }
116 return compiler()->is_c2();
117 }
118 bool nmethod::is_compiled_by_shark() const {
119 if (compiler() == NULL) {
120 return false;
121 }
122 return compiler()->is_shark();
123 }
127 //---------------------------------------------------------------------------------
128 // NMethod statistics
129 // They are printed under various flags, including:
130 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
131 // (In the latter two cases, they like other stats are printed to the log only.)
133 #ifndef PRODUCT
134 // These variables are put into one block to reduce relocations
135 // and make it simpler to print from the debugger.
136 static
137 struct nmethod_stats_struct {
138 int nmethod_count;
139 int total_size;
140 int relocation_size;
141 int consts_size;
142 int insts_size;
143 int stub_size;
144 int scopes_data_size;
145 int scopes_pcs_size;
146 int dependencies_size;
147 int handler_table_size;
148 int nul_chk_table_size;
149 int oops_size;
151 void note_nmethod(nmethod* nm) {
152 nmethod_count += 1;
153 total_size += nm->size();
154 relocation_size += nm->relocation_size();
155 consts_size += nm->consts_size();
156 insts_size += nm->insts_size();
157 stub_size += nm->stub_size();
158 oops_size += nm->oops_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 }
165 void print_nmethod_stats() {
166 if (nmethod_count == 0) return;
167 tty->print_cr("Statistics for %d bytecoded nmethods:", nmethod_count);
168 if (total_size != 0) tty->print_cr(" total in heap = %d", total_size);
169 if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size);
170 if (consts_size != 0) tty->print_cr(" constants = %d", consts_size);
171 if (insts_size != 0) tty->print_cr(" main code = %d", insts_size);
172 if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size);
173 if (oops_size != 0) tty->print_cr(" oops = %d", oops_size);
174 if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size);
175 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size);
176 if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size);
177 if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size);
178 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size);
179 }
181 int native_nmethod_count;
182 int native_total_size;
183 int native_relocation_size;
184 int native_insts_size;
185 int native_oops_size;
186 void note_native_nmethod(nmethod* nm) {
187 native_nmethod_count += 1;
188 native_total_size += nm->size();
189 native_relocation_size += nm->relocation_size();
190 native_insts_size += nm->insts_size();
191 native_oops_size += nm->oops_size();
192 }
193 void print_native_nmethod_stats() {
194 if (native_nmethod_count == 0) return;
195 tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
196 if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size);
197 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size);
198 if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size);
199 if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size);
200 }
202 int pc_desc_resets; // number of resets (= number of caches)
203 int pc_desc_queries; // queries to nmethod::find_pc_desc
204 int pc_desc_approx; // number of those which have approximate true
205 int pc_desc_repeats; // number of _pc_descs[0] hits
206 int pc_desc_hits; // number of LRU cache hits
207 int pc_desc_tests; // total number of PcDesc examinations
208 int pc_desc_searches; // total number of quasi-binary search steps
209 int pc_desc_adds; // number of LUR cache insertions
211 void print_pc_stats() {
212 tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query",
213 pc_desc_queries,
214 (double)(pc_desc_tests + pc_desc_searches)
215 / pc_desc_queries);
216 tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
217 pc_desc_resets,
218 pc_desc_queries, pc_desc_approx,
219 pc_desc_repeats, pc_desc_hits,
220 pc_desc_tests, pc_desc_searches, pc_desc_adds);
221 }
222 } nmethod_stats;
223 #endif //PRODUCT
226 //---------------------------------------------------------------------------------
229 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
230 assert(pc != NULL, "Must be non null");
231 assert(exception.not_null(), "Must be non null");
232 assert(handler != NULL, "Must be non null");
234 _count = 0;
235 _exception_type = exception->klass();
236 _next = NULL;
238 add_address_and_handler(pc,handler);
239 }
242 address ExceptionCache::match(Handle exception, address pc) {
243 assert(pc != NULL,"Must be non null");
244 assert(exception.not_null(),"Must be non null");
245 if (exception->klass() == exception_type()) {
246 return (test_address(pc));
247 }
249 return NULL;
250 }
253 bool ExceptionCache::match_exception_with_space(Handle exception) {
254 assert(exception.not_null(),"Must be non null");
255 if (exception->klass() == exception_type() && count() < cache_size) {
256 return true;
257 }
258 return false;
259 }
262 address ExceptionCache::test_address(address addr) {
263 for (int i=0; i<count(); i++) {
264 if (pc_at(i) == addr) {
265 return handler_at(i);
266 }
267 }
268 return NULL;
269 }
272 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
273 if (test_address(addr) == handler) return true;
274 if (count() < cache_size) {
275 set_pc_at(count(),addr);
276 set_handler_at(count(), handler);
277 increment_count();
278 return true;
279 }
280 return false;
281 }
284 // private method for handling exception cache
285 // These methods are private, and used to manipulate the exception cache
286 // directly.
287 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
288 ExceptionCache* ec = exception_cache();
289 while (ec != NULL) {
290 if (ec->match_exception_with_space(exception)) {
291 return ec;
292 }
293 ec = ec->next();
294 }
295 return NULL;
296 }
299 //-----------------------------------------------------------------------------
302 // Helper used by both find_pc_desc methods.
303 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
304 NOT_PRODUCT(++nmethod_stats.pc_desc_tests);
305 if (!approximate)
306 return pc->pc_offset() == pc_offset;
307 else
308 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
309 }
311 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
312 if (initial_pc_desc == NULL) {
313 _pc_descs[0] = NULL; // native method; no PcDescs at all
314 return;
315 }
316 NOT_PRODUCT(++nmethod_stats.pc_desc_resets);
317 // reset the cache by filling it with benign (non-null) values
318 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
319 for (int i = 0; i < cache_size; i++)
320 _pc_descs[i] = initial_pc_desc;
321 }
323 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
324 NOT_PRODUCT(++nmethod_stats.pc_desc_queries);
325 NOT_PRODUCT(if (approximate) ++nmethod_stats.pc_desc_approx);
327 // Note: one might think that caching the most recently
328 // read value separately would be a win, but one would be
329 // wrong. When many threads are updating it, the cache
330 // line it's in would bounce between caches, negating
331 // any benefit.
333 // In order to prevent race conditions do not load cache elements
334 // repeatedly, but use a local copy:
335 PcDesc* res;
337 // Step one: Check the most recently added value.
338 res = _pc_descs[0];
339 if (res == NULL) return NULL; // native method; no PcDescs at all
340 if (match_desc(res, pc_offset, approximate)) {
341 NOT_PRODUCT(++nmethod_stats.pc_desc_repeats);
342 return res;
343 }
345 // Step two: Check the rest of the LRU cache.
346 for (int i = 1; i < cache_size; ++i) {
347 res = _pc_descs[i];
348 if (res->pc_offset() < 0) break; // optimization: skip empty cache
349 if (match_desc(res, pc_offset, approximate)) {
350 NOT_PRODUCT(++nmethod_stats.pc_desc_hits);
351 return res;
352 }
353 }
355 // Report failure.
356 return NULL;
357 }
359 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
360 NOT_PRODUCT(++nmethod_stats.pc_desc_adds);
361 // Update the LRU cache by shifting pc_desc forward.
362 for (int i = 0; i < cache_size; i++) {
363 PcDesc* next = _pc_descs[i];
364 _pc_descs[i] = pc_desc;
365 pc_desc = next;
366 }
367 }
369 // adjust pcs_size so that it is a multiple of both oopSize and
370 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
371 // of oopSize, then 2*sizeof(PcDesc) is)
372 static int adjust_pcs_size(int pcs_size) {
373 int nsize = round_to(pcs_size, oopSize);
374 if ((nsize % sizeof(PcDesc)) != 0) {
375 nsize = pcs_size + sizeof(PcDesc);
376 }
377 assert((nsize % oopSize) == 0, "correct alignment");
378 return nsize;
379 }
381 //-----------------------------------------------------------------------------
384 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
385 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
386 assert(new_entry != NULL,"Must be non null");
387 assert(new_entry->next() == NULL, "Must be null");
389 if (exception_cache() != NULL) {
390 new_entry->set_next(exception_cache());
391 }
392 set_exception_cache(new_entry);
393 }
395 void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
396 ExceptionCache* prev = NULL;
397 ExceptionCache* curr = exception_cache();
399 while (curr != NULL) {
400 ExceptionCache* next = curr->next();
402 Klass* ex_klass = curr->exception_type();
403 if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
404 if (prev == NULL) {
405 set_exception_cache(next);
406 } else {
407 prev->set_next(next);
408 }
409 delete curr;
410 // prev stays the same.
411 } else {
412 prev = curr;
413 }
415 curr = next;
416 }
417 }
419 // public method for accessing the exception cache
420 // These are the public access methods.
421 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
422 // We never grab a lock to read the exception cache, so we may
423 // have false negatives. This is okay, as it can only happen during
424 // the first few exception lookups for a given nmethod.
425 ExceptionCache* ec = exception_cache();
426 while (ec != NULL) {
427 address ret_val;
428 if ((ret_val = ec->match(exception,pc)) != NULL) {
429 return ret_val;
430 }
431 ec = ec->next();
432 }
433 return NULL;
434 }
437 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
438 // There are potential race conditions during exception cache updates, so we
439 // must own the ExceptionCache_lock before doing ANY modifications. Because
440 // we don't lock during reads, it is possible to have several threads attempt
441 // to update the cache with the same data. We need to check for already inserted
442 // copies of the current data before adding it.
444 MutexLocker ml(ExceptionCache_lock);
445 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
447 if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
448 target_entry = new ExceptionCache(exception,pc,handler);
449 add_exception_cache_entry(target_entry);
450 }
451 }
454 //-------------end of code for ExceptionCache--------------
457 int nmethod::total_size() const {
458 return
459 consts_size() +
460 insts_size() +
461 stub_size() +
462 scopes_data_size() +
463 scopes_pcs_size() +
464 handler_table_size() +
465 nul_chk_table_size();
466 }
468 const char* nmethod::compile_kind() const {
469 if (is_osr_method()) return "osr";
470 if (method() != NULL && is_native_method()) return "c2n";
471 return NULL;
472 }
474 // Fill in default values for various flag fields
475 void nmethod::init_defaults() {
476 _state = in_use;
477 _unloading_clock = 0;
478 _marked_for_reclamation = 0;
479 _has_flushed_dependencies = 0;
480 _has_unsafe_access = 0;
481 _has_method_handle_invokes = 0;
482 _lazy_critical_native = 0;
483 _has_wide_vectors = 0;
484 _marked_for_deoptimization = 0;
485 _lock_count = 0;
486 _stack_traversal_mark = 0;
487 _unload_reported = false; // jvmti state
489 #ifdef ASSERT
490 _oops_are_stale = false;
491 #endif
493 _oops_do_mark_link = NULL;
494 _jmethod_id = NULL;
495 _osr_link = NULL;
496 if (UseG1GC) {
497 _unloading_next = NULL;
498 } else {
499 _scavenge_root_link = NULL;
500 }
501 _scavenge_root_state = 0;
502 _compiler = NULL;
503 #if INCLUDE_RTM_OPT
504 _rtm_state = NoRTM;
505 #endif
506 #ifdef HAVE_DTRACE_H
507 _trap_offset = 0;
508 #endif // def HAVE_DTRACE_H
509 }
511 nmethod* nmethod::new_native_nmethod(methodHandle method,
512 int compile_id,
513 CodeBuffer *code_buffer,
514 int vep_offset,
515 int frame_complete,
516 int frame_size,
517 ByteSize basic_lock_owner_sp_offset,
518 ByteSize basic_lock_sp_offset,
519 OopMapSet* oop_maps) {
520 code_buffer->finalize_oop_references(method);
521 // create nmethod
522 nmethod* nm = NULL;
523 {
524 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
525 int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
526 CodeOffsets offsets;
527 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
528 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
529 nm = new (native_nmethod_size) nmethod(method(), native_nmethod_size,
530 compile_id, &offsets,
531 code_buffer, frame_size,
532 basic_lock_owner_sp_offset,
533 basic_lock_sp_offset, oop_maps);
534 NOT_PRODUCT(if (nm != NULL) nmethod_stats.note_native_nmethod(nm));
535 if (PrintAssembly && nm != NULL) {
536 Disassembler::decode(nm);
537 }
538 }
539 // verify nmethod
540 debug_only(if (nm) nm->verify();) // might block
542 if (nm != NULL) {
543 nm->log_new_nmethod();
544 }
546 return nm;
547 }
549 #ifdef HAVE_DTRACE_H
550 nmethod* nmethod::new_dtrace_nmethod(methodHandle method,
551 CodeBuffer *code_buffer,
552 int vep_offset,
553 int trap_offset,
554 int frame_complete,
555 int frame_size) {
556 code_buffer->finalize_oop_references(method);
557 // create nmethod
558 nmethod* nm = NULL;
559 {
560 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
561 int nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
562 CodeOffsets offsets;
563 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
564 offsets.set_value(CodeOffsets::Dtrace_trap, trap_offset);
565 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
567 nm = new (nmethod_size) nmethod(method(), nmethod_size,
568 &offsets, code_buffer, frame_size);
570 NOT_PRODUCT(if (nm != NULL) nmethod_stats.note_nmethod(nm));
571 if (PrintAssembly && nm != NULL) {
572 Disassembler::decode(nm);
573 }
574 }
575 // verify nmethod
576 debug_only(if (nm) nm->verify();) // might block
578 if (nm != NULL) {
579 nm->log_new_nmethod();
580 }
582 return nm;
583 }
585 #endif // def HAVE_DTRACE_H
587 nmethod* nmethod::new_nmethod(methodHandle method,
588 int compile_id,
589 int entry_bci,
590 CodeOffsets* offsets,
591 int orig_pc_offset,
592 DebugInformationRecorder* debug_info,
593 Dependencies* dependencies,
594 CodeBuffer* code_buffer, int frame_size,
595 OopMapSet* oop_maps,
596 ExceptionHandlerTable* handler_table,
597 ImplicitExceptionTable* nul_chk_table,
598 AbstractCompiler* compiler,
599 int comp_level
600 )
601 {
602 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
603 code_buffer->finalize_oop_references(method);
604 // create nmethod
605 nmethod* nm = NULL;
606 { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
607 int nmethod_size =
608 allocation_size(code_buffer, sizeof(nmethod))
609 + adjust_pcs_size(debug_info->pcs_size())
610 + round_to(dependencies->size_in_bytes() , oopSize)
611 + round_to(handler_table->size_in_bytes(), oopSize)
612 + round_to(nul_chk_table->size_in_bytes(), oopSize)
613 + round_to(debug_info->data_size() , oopSize);
615 nm = new (nmethod_size)
616 nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
617 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
618 oop_maps,
619 handler_table,
620 nul_chk_table,
621 compiler,
622 comp_level);
624 if (nm != NULL) {
625 // To make dependency checking during class loading fast, record
626 // the nmethod dependencies in the classes it is dependent on.
627 // This allows the dependency checking code to simply walk the
628 // class hierarchy above the loaded class, checking only nmethods
629 // which are dependent on those classes. The slow way is to
630 // check every nmethod for dependencies which makes it linear in
631 // the number of methods compiled. For applications with a lot
632 // classes the slow way is too slow.
633 for (Dependencies::DepStream deps(nm); deps.next(); ) {
634 Klass* klass = deps.context_type();
635 if (klass == NULL) {
636 continue; // ignore things like evol_method
637 }
639 // record this nmethod as dependent on this klass
640 InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
641 }
642 NOT_PRODUCT(nmethod_stats.note_nmethod(nm));
643 if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
644 Disassembler::decode(nm);
645 }
646 }
647 }
648 // Do verification and logging outside CodeCache_lock.
649 if (nm != NULL) {
650 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
651 DEBUG_ONLY(nm->verify();)
652 nm->log_new_nmethod();
653 }
654 return nm;
655 }
658 // For native wrappers
659 nmethod::nmethod(
660 Method* method,
661 int nmethod_size,
662 int compile_id,
663 CodeOffsets* offsets,
664 CodeBuffer* code_buffer,
665 int frame_size,
666 ByteSize basic_lock_owner_sp_offset,
667 ByteSize basic_lock_sp_offset,
668 OopMapSet* oop_maps )
669 : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
670 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
671 _native_receiver_sp_offset(basic_lock_owner_sp_offset),
672 _native_basic_lock_sp_offset(basic_lock_sp_offset)
673 {
674 {
675 debug_only(No_Safepoint_Verifier nsv;)
676 assert_locked_or_safepoint(CodeCache_lock);
678 init_defaults();
679 _method = method;
680 _entry_bci = InvocationEntryBci;
681 // We have no exception handler or deopt handler make the
682 // values something that will never match a pc like the nmethod vtable entry
683 _exception_offset = 0;
684 _deoptimize_offset = 0;
685 _deoptimize_mh_offset = 0;
686 _orig_pc_offset = 0;
688 _consts_offset = data_offset();
689 _stub_offset = data_offset();
690 _oops_offset = data_offset();
691 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
692 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
693 _scopes_pcs_offset = _scopes_data_offset;
694 _dependencies_offset = _scopes_pcs_offset;
695 _handler_table_offset = _dependencies_offset;
696 _nul_chk_table_offset = _handler_table_offset;
697 _nmethod_end_offset = _nul_chk_table_offset;
698 _compile_id = compile_id;
699 _comp_level = CompLevel_none;
700 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
701 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
702 _osr_entry_point = NULL;
703 _exception_cache = NULL;
704 _pc_desc_cache.reset_to(NULL);
705 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
707 code_buffer->copy_values_to(this);
708 if (ScavengeRootsInCode) {
709 if (detect_scavenge_root_oops()) {
710 CodeCache::add_scavenge_root_nmethod(this);
711 }
712 Universe::heap()->register_nmethod(this);
713 }
714 debug_only(verify_scavenge_root_oops());
715 CodeCache::commit(this);
716 }
718 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
719 ttyLocker ttyl; // keep the following output all in one block
720 // This output goes directly to the tty, not the compiler log.
721 // To enable tools to match it up with the compilation activity,
722 // be sure to tag this tty output with the compile ID.
723 if (xtty != NULL) {
724 xtty->begin_head("print_native_nmethod");
725 xtty->method(_method);
726 xtty->stamp();
727 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
728 }
729 // print the header part first
730 print();
731 // then print the requested information
732 if (PrintNativeNMethods) {
733 print_code();
734 if (oop_maps != NULL) {
735 oop_maps->print();
736 }
737 }
738 if (PrintRelocations) {
739 print_relocations();
740 }
741 if (xtty != NULL) {
742 xtty->tail("print_native_nmethod");
743 }
744 }
745 }
747 // For dtrace wrappers
748 #ifdef HAVE_DTRACE_H
749 nmethod::nmethod(
750 Method* method,
751 int nmethod_size,
752 CodeOffsets* offsets,
753 CodeBuffer* code_buffer,
754 int frame_size)
755 : CodeBlob("dtrace nmethod", code_buffer, sizeof(nmethod),
756 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, NULL),
757 _native_receiver_sp_offset(in_ByteSize(-1)),
758 _native_basic_lock_sp_offset(in_ByteSize(-1))
759 {
760 {
761 debug_only(No_Safepoint_Verifier nsv;)
762 assert_locked_or_safepoint(CodeCache_lock);
764 init_defaults();
765 _method = method;
766 _entry_bci = InvocationEntryBci;
767 // We have no exception handler or deopt handler make the
768 // values something that will never match a pc like the nmethod vtable entry
769 _exception_offset = 0;
770 _deoptimize_offset = 0;
771 _deoptimize_mh_offset = 0;
772 _unwind_handler_offset = -1;
773 _trap_offset = offsets->value(CodeOffsets::Dtrace_trap);
774 _orig_pc_offset = 0;
775 _consts_offset = data_offset();
776 _stub_offset = data_offset();
777 _oops_offset = data_offset();
778 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
779 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
780 _scopes_pcs_offset = _scopes_data_offset;
781 _dependencies_offset = _scopes_pcs_offset;
782 _handler_table_offset = _dependencies_offset;
783 _nul_chk_table_offset = _handler_table_offset;
784 _nmethod_end_offset = _nul_chk_table_offset;
785 _compile_id = 0; // default
786 _comp_level = CompLevel_none;
787 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
788 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
789 _osr_entry_point = NULL;
790 _exception_cache = NULL;
791 _pc_desc_cache.reset_to(NULL);
792 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
794 code_buffer->copy_values_to(this);
795 if (ScavengeRootsInCode) {
796 if (detect_scavenge_root_oops()) {
797 CodeCache::add_scavenge_root_nmethod(this);
798 }
799 Universe::heap()->register_nmethod(this);
800 }
801 DEBUG_ONLY(verify_scavenge_root_oops();)
802 CodeCache::commit(this);
803 }
805 if (PrintNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
806 ttyLocker ttyl; // keep the following output all in one block
807 // This output goes directly to the tty, not the compiler log.
808 // To enable tools to match it up with the compilation activity,
809 // be sure to tag this tty output with the compile ID.
810 if (xtty != NULL) {
811 xtty->begin_head("print_dtrace_nmethod");
812 xtty->method(_method);
813 xtty->stamp();
814 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
815 }
816 // print the header part first
817 print();
818 // then print the requested information
819 if (PrintNMethods) {
820 print_code();
821 }
822 if (PrintRelocations) {
823 print_relocations();
824 }
825 if (xtty != NULL) {
826 xtty->tail("print_dtrace_nmethod");
827 }
828 }
829 }
830 #endif // def HAVE_DTRACE_H
832 void* nmethod::operator new(size_t size, int nmethod_size) throw() {
833 // Not critical, may return null if there is too little continuous memory
834 return CodeCache::allocate(nmethod_size);
835 }
837 nmethod::nmethod(
838 Method* method,
839 int nmethod_size,
840 int compile_id,
841 int entry_bci,
842 CodeOffsets* offsets,
843 int orig_pc_offset,
844 DebugInformationRecorder* debug_info,
845 Dependencies* dependencies,
846 CodeBuffer *code_buffer,
847 int frame_size,
848 OopMapSet* oop_maps,
849 ExceptionHandlerTable* handler_table,
850 ImplicitExceptionTable* nul_chk_table,
851 AbstractCompiler* compiler,
852 int comp_level
853 )
854 : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
855 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
856 _native_receiver_sp_offset(in_ByteSize(-1)),
857 _native_basic_lock_sp_offset(in_ByteSize(-1))
858 {
859 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
860 {
861 debug_only(No_Safepoint_Verifier nsv;)
862 assert_locked_or_safepoint(CodeCache_lock);
864 init_defaults();
865 _method = method;
866 _entry_bci = entry_bci;
867 _compile_id = compile_id;
868 _comp_level = comp_level;
869 _compiler = compiler;
870 _orig_pc_offset = orig_pc_offset;
871 _hotness_counter = NMethodSweeper::hotness_counter_reset_val();
873 // Section offsets
874 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts());
875 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
877 // Exception handler and deopt handler are in the stub section
878 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
879 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");
880 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);
881 _deoptimize_offset = _stub_offset + offsets->value(CodeOffsets::Deopt);
882 if (offsets->value(CodeOffsets::DeoptMH) != -1) {
883 _deoptimize_mh_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH);
884 } else {
885 _deoptimize_mh_offset = -1;
886 }
887 if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
888 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
889 } else {
890 _unwind_handler_offset = -1;
891 }
893 _oops_offset = data_offset();
894 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize);
895 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize);
897 _scopes_pcs_offset = _scopes_data_offset + round_to(debug_info->data_size (), oopSize);
898 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());
899 _handler_table_offset = _dependencies_offset + round_to(dependencies->size_in_bytes (), oopSize);
900 _nul_chk_table_offset = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
901 _nmethod_end_offset = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);
903 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry);
904 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);
905 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
906 _exception_cache = NULL;
907 _pc_desc_cache.reset_to(scopes_pcs_begin());
909 // Copy contents of ScopeDescRecorder to nmethod
910 code_buffer->copy_values_to(this);
911 debug_info->copy_to(this);
912 dependencies->copy_to(this);
913 if (ScavengeRootsInCode) {
914 if (detect_scavenge_root_oops()) {
915 CodeCache::add_scavenge_root_nmethod(this);
916 }
917 Universe::heap()->register_nmethod(this);
918 }
919 debug_only(verify_scavenge_root_oops());
921 CodeCache::commit(this);
923 // Copy contents of ExceptionHandlerTable to nmethod
924 handler_table->copy_to(this);
925 nul_chk_table->copy_to(this);
927 // we use the information of entry points to find out if a method is
928 // static or non static
929 assert(compiler->is_c2() ||
930 _method->is_static() == (entry_point() == _verified_entry_point),
931 " entry points must be same for static methods and vice versa");
932 }
934 bool printnmethods = PrintNMethods
935 || CompilerOracle::should_print(_method)
936 || CompilerOracle::has_option_string(_method, "PrintNMethods");
937 if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
938 print_nmethod(printnmethods);
939 }
940 }
943 // Print a short set of xml attributes to identify this nmethod. The
944 // output should be embedded in some other element.
945 void nmethod::log_identity(xmlStream* log) const {
946 log->print(" compile_id='%d'", compile_id());
947 const char* nm_kind = compile_kind();
948 if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind);
949 if (compiler() != NULL) {
950 log->print(" compiler='%s'", compiler()->name());
951 }
952 if (TieredCompilation) {
953 log->print(" level='%d'", comp_level());
954 }
955 }
958 #define LOG_OFFSET(log, name) \
959 if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
960 log->print(" " XSTR(name) "_offset='%d'" , \
961 (intptr_t)name##_begin() - (intptr_t)this)
964 void nmethod::log_new_nmethod() const {
965 if (LogCompilation && xtty != NULL) {
966 ttyLocker ttyl;
967 HandleMark hm;
968 xtty->begin_elem("nmethod");
969 log_identity(xtty);
970 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
971 xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);
973 LOG_OFFSET(xtty, relocation);
974 LOG_OFFSET(xtty, consts);
975 LOG_OFFSET(xtty, insts);
976 LOG_OFFSET(xtty, stub);
977 LOG_OFFSET(xtty, scopes_data);
978 LOG_OFFSET(xtty, scopes_pcs);
979 LOG_OFFSET(xtty, dependencies);
980 LOG_OFFSET(xtty, handler_table);
981 LOG_OFFSET(xtty, nul_chk_table);
982 LOG_OFFSET(xtty, oops);
984 xtty->method(method());
985 xtty->stamp();
986 xtty->end_elem();
987 }
988 }
990 #undef LOG_OFFSET
993 // Print out more verbose output usually for a newly created nmethod.
994 void nmethod::print_on(outputStream* st, const char* msg) const {
995 if (st != NULL) {
996 ttyLocker ttyl;
997 if (WizardMode) {
998 CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
999 st->print_cr(" (" INTPTR_FORMAT ")", this);
1000 } else {
1001 CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
1002 }
1003 }
1004 }
1007 void nmethod::print_nmethod(bool printmethod) {
1008 ttyLocker ttyl; // keep the following output all in one block
1009 if (xtty != NULL) {
1010 xtty->begin_head("print_nmethod");
1011 xtty->stamp();
1012 xtty->end_head();
1013 }
1014 // print the header part first
1015 print();
1016 // then print the requested information
1017 if (printmethod) {
1018 print_code();
1019 print_pcs();
1020 if (oop_maps()) {
1021 oop_maps()->print();
1022 }
1023 }
1024 if (PrintDebugInfo) {
1025 print_scopes();
1026 }
1027 if (PrintRelocations) {
1028 print_relocations();
1029 }
1030 if (PrintDependencies) {
1031 print_dependencies();
1032 }
1033 if (PrintExceptionHandlers) {
1034 print_handler_table();
1035 print_nul_chk_table();
1036 }
1037 if (xtty != NULL) {
1038 xtty->tail("print_nmethod");
1039 }
1040 }
1043 // Promote one word from an assembly-time handle to a live embedded oop.
1044 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1045 if (handle == NULL ||
1046 // As a special case, IC oops are initialized to 1 or -1.
1047 handle == (jobject) Universe::non_oop_word()) {
1048 (*dest) = (oop) handle;
1049 } else {
1050 (*dest) = JNIHandles::resolve_non_null(handle);
1051 }
1052 }
1055 // Have to have the same name because it's called by a template
1056 void nmethod::copy_values(GrowableArray<jobject>* array) {
1057 int length = array->length();
1058 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1059 oop* dest = oops_begin();
1060 for (int index = 0 ; index < length; index++) {
1061 initialize_immediate_oop(&dest[index], array->at(index));
1062 }
1064 // Now we can fix up all the oops in the code. We need to do this
1065 // in the code because the assembler uses jobjects as placeholders.
1066 // The code and relocations have already been initialized by the
1067 // CodeBlob constructor, so it is valid even at this early point to
1068 // iterate over relocations and patch the code.
1069 fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);
1070 }
1072 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1073 int length = array->length();
1074 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1075 Metadata** dest = metadata_begin();
1076 for (int index = 0 ; index < length; index++) {
1077 dest[index] = array->at(index);
1078 }
1079 }
1081 bool nmethod::is_at_poll_return(address pc) {
1082 RelocIterator iter(this, pc, pc+1);
1083 while (iter.next()) {
1084 if (iter.type() == relocInfo::poll_return_type)
1085 return true;
1086 }
1087 return false;
1088 }
1091 bool nmethod::is_at_poll_or_poll_return(address pc) {
1092 RelocIterator iter(this, pc, pc+1);
1093 while (iter.next()) {
1094 relocInfo::relocType t = iter.type();
1095 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
1096 return true;
1097 }
1098 return false;
1099 }
1102 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1103 // re-patch all oop-bearing instructions, just in case some oops moved
1104 RelocIterator iter(this, begin, end);
1105 while (iter.next()) {
1106 if (iter.type() == relocInfo::oop_type) {
1107 oop_Relocation* reloc = iter.oop_reloc();
1108 if (initialize_immediates && reloc->oop_is_immediate()) {
1109 oop* dest = reloc->oop_addr();
1110 initialize_immediate_oop(dest, (jobject) *dest);
1111 }
1112 // Refresh the oop-related bits of this instruction.
1113 reloc->fix_oop_relocation();
1114 } else if (iter.type() == relocInfo::metadata_type) {
1115 metadata_Relocation* reloc = iter.metadata_reloc();
1116 reloc->fix_metadata_relocation();
1117 }
1118 }
1119 }
1122 void nmethod::verify_oop_relocations() {
1123 // Ensure sure that the code matches the current oop values
1124 RelocIterator iter(this, NULL, NULL);
1125 while (iter.next()) {
1126 if (iter.type() == relocInfo::oop_type) {
1127 oop_Relocation* reloc = iter.oop_reloc();
1128 if (!reloc->oop_is_immediate()) {
1129 reloc->verify_oop_relocation();
1130 }
1131 }
1132 }
1133 }
1136 ScopeDesc* nmethod::scope_desc_at(address pc) {
1137 PcDesc* pd = pc_desc_at(pc);
1138 guarantee(pd != NULL, "scope must be present");
1139 return new ScopeDesc(this, pd->scope_decode_offset(),
1140 pd->obj_decode_offset(), pd->should_reexecute(),
1141 pd->return_oop());
1142 }
1145 void nmethod::clear_inline_caches() {
1146 assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
1147 if (is_zombie()) {
1148 return;
1149 }
1151 RelocIterator iter(this);
1152 while (iter.next()) {
1153 iter.reloc()->clear_inline_cache();
1154 }
1155 }
1157 // Clear ICStubs of all compiled ICs
1158 void nmethod::clear_ic_stubs() {
1159 assert_locked_or_safepoint(CompiledIC_lock);
1160 RelocIterator iter(this);
1161 while(iter.next()) {
1162 if (iter.type() == relocInfo::virtual_call_type) {
1163 CompiledIC* ic = CompiledIC_at(&iter);
1164 ic->clear_ic_stub();
1165 }
1166 }
1167 }
1170 void nmethod::cleanup_inline_caches() {
1171 assert_locked_or_safepoint(CompiledIC_lock);
1173 // If the method is not entrant or zombie then a JMP is plastered over the
1174 // first few bytes. If an oop in the old code was there, that oop
1175 // should not get GC'd. Skip the first few bytes of oops on
1176 // not-entrant methods.
1177 address low_boundary = verified_entry_point();
1178 if (!is_in_use()) {
1179 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1180 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1181 // This means that the low_boundary is going to be a little too high.
1182 // This shouldn't matter, since oops of non-entrant methods are never used.
1183 // In fact, why are we bothering to look at oops in a non-entrant method??
1184 }
1186 // Find all calls in an nmethod and clear the ones that point to non-entrant,
1187 // zombie and unloaded nmethods.
1188 ResourceMark rm;
1189 RelocIterator iter(this, low_boundary);
1190 while(iter.next()) {
1191 switch(iter.type()) {
1192 case relocInfo::virtual_call_type:
1193 case relocInfo::opt_virtual_call_type: {
1194 CompiledIC *ic = CompiledIC_at(&iter);
1195 // Ok, to lookup references to zombies here
1196 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1197 if( cb != NULL && cb->is_nmethod() ) {
1198 nmethod* nm = (nmethod*)cb;
1199 // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1200 if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean(is_alive());
1201 }
1202 break;
1203 }
1204 case relocInfo::static_call_type: {
1205 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1206 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1207 if( cb != NULL && cb->is_nmethod() ) {
1208 nmethod* nm = (nmethod*)cb;
1209 // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1210 if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean();
1211 }
1212 break;
1213 }
1214 }
1215 }
1216 }
1218 void nmethod::verify_clean_inline_caches() {
1219 assert_locked_or_safepoint(CompiledIC_lock);
1221 // If the method is not entrant or zombie then a JMP is plastered over the
1222 // first few bytes. If an oop in the old code was there, that oop
1223 // should not get GC'd. Skip the first few bytes of oops on
1224 // not-entrant methods.
1225 address low_boundary = verified_entry_point();
1226 if (!is_in_use()) {
1227 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1228 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1229 // This means that the low_boundary is going to be a little too high.
1230 // This shouldn't matter, since oops of non-entrant methods are never used.
1231 // In fact, why are we bothering to look at oops in a non-entrant method??
1232 }
1234 ResourceMark rm;
1235 RelocIterator iter(this, low_boundary);
1236 while(iter.next()) {
1237 switch(iter.type()) {
1238 case relocInfo::virtual_call_type:
1239 case relocInfo::opt_virtual_call_type: {
1240 CompiledIC *ic = CompiledIC_at(&iter);
1241 // Ok, to lookup references to zombies here
1242 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1243 if( cb != NULL && cb->is_nmethod() ) {
1244 nmethod* nm = (nmethod*)cb;
1245 // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1246 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1247 assert(ic->is_clean(), "IC should be clean");
1248 }
1249 }
1250 break;
1251 }
1252 case relocInfo::static_call_type: {
1253 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1254 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1255 if( cb != NULL && cb->is_nmethod() ) {
1256 nmethod* nm = (nmethod*)cb;
1257 // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1258 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1259 assert(csc->is_clean(), "IC should be clean");
1260 }
1261 }
1262 break;
1263 }
1264 }
1265 }
1266 }
1268 int nmethod::verify_icholder_relocations() {
1269 int count = 0;
1271 RelocIterator iter(this);
1272 while(iter.next()) {
1273 if (iter.type() == relocInfo::virtual_call_type) {
1274 if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
1275 CompiledIC *ic = CompiledIC_at(&iter);
1276 if (TraceCompiledIC) {
1277 tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
1278 ic->print();
1279 }
1280 assert(ic->cached_icholder() != NULL, "must be non-NULL");
1281 count++;
1282 }
1283 }
1284 }
1286 return count;
1287 }
1289 // This is a private interface with the sweeper.
1290 void nmethod::mark_as_seen_on_stack() {
1291 assert(is_alive(), "Must be an alive method");
1292 // Set the traversal mark to ensure that the sweeper does 2
1293 // cleaning passes before moving to zombie.
1294 set_stack_traversal_mark(NMethodSweeper::traversal_count());
1295 }
1297 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1298 // there are no activations on the stack, not in use by the VM,
1299 // and not in use by the ServiceThread)
1300 bool nmethod::can_convert_to_zombie() {
1301 assert(is_not_entrant(), "must be a non-entrant method");
1303 // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1304 // count can be greater than the stack traversal count before it hits the
1305 // nmethod for the second time.
1306 return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1307 !is_locked_by_vm();
1308 }
1310 void nmethod::inc_decompile_count() {
1311 if (!is_compiled_by_c2()) return;
1312 // Could be gated by ProfileTraps, but do not bother...
1313 Method* m = method();
1314 if (m == NULL) return;
1315 MethodData* mdo = m->method_data();
1316 if (mdo == NULL) return;
1317 // There is a benign race here. See comments in methodData.hpp.
1318 mdo->inc_decompile_count();
1319 }
1321 void nmethod::increase_unloading_clock() {
1322 _global_unloading_clock++;
1323 if (_global_unloading_clock == 0) {
1324 // _nmethods are allocated with _unloading_clock == 0,
1325 // so 0 is never used as a clock value.
1326 _global_unloading_clock = 1;
1327 }
1328 }
1330 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1331 OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
1332 }
1334 unsigned char nmethod::unloading_clock() {
1335 return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
1336 }
1338 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {
1340 post_compiled_method_unload();
1342 // Since this nmethod is being unloaded, make sure that dependencies
1343 // recorded in instanceKlasses get flushed and pass non-NULL closure to
1344 // indicate that this work is being done during a GC.
1345 assert(Universe::heap()->is_gc_active(), "should only be called during gc");
1346 assert(is_alive != NULL, "Should be non-NULL");
1347 // A non-NULL is_alive closure indicates that this is being called during GC.
1348 flush_dependencies(is_alive);
1350 // Break cycle between nmethod & method
1351 if (TraceClassUnloading && WizardMode) {
1352 tty->print_cr("[Class unloading: Making nmethod " INTPTR_FORMAT
1353 " unloadable], Method*(" INTPTR_FORMAT
1354 "), cause(" INTPTR_FORMAT ")",
1355 this, (address)_method, (address)cause);
1356 if (!Universe::heap()->is_gc_active())
1357 cause->klass()->print();
1358 }
1359 // Unlink the osr method, so we do not look this up again
1360 if (is_osr_method()) {
1361 invalidate_osr_method();
1362 }
1363 // If _method is already NULL the Method* is about to be unloaded,
1364 // so we don't have to break the cycle. Note that it is possible to
1365 // have the Method* live here, in case we unload the nmethod because
1366 // it is pointing to some oop (other than the Method*) being unloaded.
1367 if (_method != NULL) {
1368 // OSR methods point to the Method*, but the Method* does not
1369 // point back!
1370 if (_method->code() == this) {
1371 _method->clear_code(); // Break a cycle
1372 }
1373 _method = NULL; // Clear the method of this dead nmethod
1374 }
1375 // Make the class unloaded - i.e., change state and notify sweeper
1376 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1377 if (is_in_use()) {
1378 // Transitioning directly from live to unloaded -- so
1379 // we need to force a cache clean-up; remember this
1380 // for later on.
1381 CodeCache::set_needs_cache_clean(true);
1382 }
1384 // Unregister must be done before the state change
1385 Universe::heap()->unregister_nmethod(this);
1387 _state = unloaded;
1389 // Log the unloading.
1390 log_state_change();
1392 // The Method* is gone at this point
1393 assert(_method == NULL, "Tautology");
1395 set_osr_link(NULL);
1396 //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1397 NMethodSweeper::report_state_change(this);
1398 }
1400 void nmethod::invalidate_osr_method() {
1401 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1402 // Remove from list of active nmethods
1403 if (method() != NULL)
1404 method()->method_holder()->remove_osr_nmethod(this);
1405 // Set entry as invalid
1406 _entry_bci = InvalidOSREntryBci;
1407 }
1409 void nmethod::log_state_change() const {
1410 if (LogCompilation) {
1411 if (xtty != NULL) {
1412 ttyLocker ttyl; // keep the following output all in one block
1413 if (_state == unloaded) {
1414 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1415 os::current_thread_id());
1416 } else {
1417 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1418 os::current_thread_id(),
1419 (_state == zombie ? " zombie='1'" : ""));
1420 }
1421 log_identity(xtty);
1422 xtty->stamp();
1423 xtty->end_elem();
1424 }
1425 }
1426 if (PrintCompilation && _state != unloaded) {
1427 print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1428 }
1429 }
1431 /**
1432 * Common functionality for both make_not_entrant and make_zombie
1433 */
1434 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1435 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1436 assert(!is_zombie(), "should not already be a zombie");
1438 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1439 nmethodLocker nml(this);
1440 methodHandle the_method(method());
1441 No_Safepoint_Verifier nsv;
1443 // during patching, depending on the nmethod state we must notify the GC that
1444 // code has been unloaded, unregistering it. We cannot do this right while
1445 // holding the Patching_lock because we need to use the CodeCache_lock. This
1446 // would be prone to deadlocks.
1447 // This flag is used to remember whether we need to later lock and unregister.
1448 bool nmethod_needs_unregister = false;
1450 {
1451 // invalidate osr nmethod before acquiring the patching lock since
1452 // they both acquire leaf locks and we don't want a deadlock.
1453 // This logic is equivalent to the logic below for patching the
1454 // verified entry point of regular methods.
1455 if (is_osr_method()) {
1456 // this effectively makes the osr nmethod not entrant
1457 invalidate_osr_method();
1458 }
1460 // Enter critical section. Does not block for safepoint.
1461 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1463 if (_state == state) {
1464 // another thread already performed this transition so nothing
1465 // to do, but return false to indicate this.
1466 return false;
1467 }
1469 // The caller can be calling the method statically or through an inline
1470 // cache call.
1471 if (!is_osr_method() && !is_not_entrant()) {
1472 NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::patch_verified_entry(entry_point(), verified_entry_point(),
1473 SharedRuntime::get_handle_wrong_method_stub());
1474 }
1476 if (is_in_use()) {
1477 // It's a true state change, so mark the method as decompiled.
1478 // Do it only for transition from alive.
1479 inc_decompile_count();
1480 }
1482 // If the state is becoming a zombie, signal to unregister the nmethod with
1483 // the heap.
1484 // This nmethod may have already been unloaded during a full GC.
1485 if ((state == zombie) && !is_unloaded()) {
1486 nmethod_needs_unregister = true;
1487 }
1489 // Must happen before state change. Otherwise we have a race condition in
1490 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1491 // transition its state from 'not_entrant' to 'zombie' without having to wait
1492 // for stack scanning.
1493 if (state == not_entrant) {
1494 mark_as_seen_on_stack();
1495 OrderAccess::storestore();
1496 }
1498 // Change state
1499 _state = state;
1501 // Log the transition once
1502 log_state_change();
1504 // Remove nmethod from method.
1505 // We need to check if both the _code and _from_compiled_code_entry_point
1506 // refer to this nmethod because there is a race in setting these two fields
1507 // in Method* as seen in bugid 4947125.
1508 // If the vep() points to the zombie nmethod, the memory for the nmethod
1509 // could be flushed and the compiler and vtable stubs could still call
1510 // through it.
1511 if (method() != NULL && (method()->code() == this ||
1512 method()->from_compiled_entry() == verified_entry_point())) {
1513 HandleMark hm;
1514 method()->clear_code();
1515 }
1516 } // leave critical region under Patching_lock
1518 // When the nmethod becomes zombie it is no longer alive so the
1519 // dependencies must be flushed. nmethods in the not_entrant
1520 // state will be flushed later when the transition to zombie
1521 // happens or they get unloaded.
1522 if (state == zombie) {
1523 {
1524 // Flushing dependecies must be done before any possible
1525 // safepoint can sneak in, otherwise the oops used by the
1526 // dependency logic could have become stale.
1527 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1528 if (nmethod_needs_unregister) {
1529 Universe::heap()->unregister_nmethod(this);
1530 }
1531 flush_dependencies(NULL);
1532 }
1534 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1535 // event and it hasn't already been reported for this nmethod then
1536 // report it now. The event may have been reported earilier if the GC
1537 // marked it for unloading). JvmtiDeferredEventQueue support means
1538 // we no longer go to a safepoint here.
1539 post_compiled_method_unload();
1541 #ifdef ASSERT
1542 // It's no longer safe to access the oops section since zombie
1543 // nmethods aren't scanned for GC.
1544 _oops_are_stale = true;
1545 #endif
1546 // the Method may be reclaimed by class unloading now that the
1547 // nmethod is in zombie state
1548 set_method(NULL);
1549 } else {
1550 assert(state == not_entrant, "other cases may need to be handled differently");
1551 }
1553 if (TraceCreateZombies) {
1554 tty->print_cr("nmethod <" INTPTR_FORMAT "> code made %s", this, (state == not_entrant) ? "not entrant" : "zombie");
1555 }
1557 NMethodSweeper::report_state_change(this);
1558 return true;
1559 }
1561 void nmethod::flush() {
1562 // Note that there are no valid oops in the nmethod anymore.
1563 assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1564 assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1566 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1567 assert_locked_or_safepoint(CodeCache_lock);
1569 // completely deallocate this method
1570 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1571 if (PrintMethodFlushing) {
1572 tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1573 _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity()/1024);
1574 }
1576 // We need to deallocate any ExceptionCache data.
1577 // Note that we do not need to grab the nmethod lock for this, it
1578 // better be thread safe if we're disposing of it!
1579 ExceptionCache* ec = exception_cache();
1580 set_exception_cache(NULL);
1581 while(ec != NULL) {
1582 ExceptionCache* next = ec->next();
1583 delete ec;
1584 ec = next;
1585 }
1587 if (on_scavenge_root_list()) {
1588 CodeCache::drop_scavenge_root_nmethod(this);
1589 }
1591 #ifdef SHARK
1592 ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1593 #endif // SHARK
1595 ((CodeBlob*)(this))->flush();
1597 CodeCache::free(this);
1598 }
1601 //
1602 // Notify all classes this nmethod is dependent on that it is no
1603 // longer dependent. This should only be called in two situations.
1604 // First, when a nmethod transitions to a zombie all dependents need
1605 // to be clear. Since zombification happens at a safepoint there's no
1606 // synchronization issues. The second place is a little more tricky.
1607 // During phase 1 of mark sweep class unloading may happen and as a
1608 // result some nmethods may get unloaded. In this case the flushing
1609 // of dependencies must happen during phase 1 since after GC any
1610 // dependencies in the unloaded nmethod won't be updated, so
1611 // traversing the dependency information in unsafe. In that case this
1612 // function is called with a non-NULL argument and this function only
1613 // notifies instanceKlasses that are reachable
1615 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1616 assert_locked_or_safepoint(CodeCache_lock);
1617 assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1618 "is_alive is non-NULL if and only if we are called during GC");
1619 if (!has_flushed_dependencies()) {
1620 set_has_flushed_dependencies();
1621 for (Dependencies::DepStream deps(this); deps.next(); ) {
1622 Klass* klass = deps.context_type();
1623 if (klass == NULL) continue; // ignore things like evol_method
1625 // During GC the is_alive closure is non-NULL, and is used to
1626 // determine liveness of dependees that need to be updated.
1627 if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1628 // The GC defers deletion of this entry, since there might be multiple threads
1629 // iterating over the _dependencies graph. Other call paths are single-threaded
1630 // and may delete it immediately.
1631 bool delete_immediately = is_alive == NULL;
1632 InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately);
1633 }
1634 }
1635 }
1636 }
1639 // If this oop is not live, the nmethod can be unloaded.
1640 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1641 assert(root != NULL, "just checking");
1642 oop obj = *root;
1643 if (obj == NULL || is_alive->do_object_b(obj)) {
1644 return false;
1645 }
1647 // If ScavengeRootsInCode is true, an nmethod might be unloaded
1648 // simply because one of its constant oops has gone dead.
1649 // No actual classes need to be unloaded in order for this to occur.
1650 assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1651 make_unloaded(is_alive, obj);
1652 return true;
1653 }
1655 // ------------------------------------------------------------------
1656 // post_compiled_method_load_event
1657 // new method for install_code() path
1658 // Transfer information from compilation to jvmti
1659 void nmethod::post_compiled_method_load_event() {
1661 Method* moop = method();
1662 #ifndef USDT2
1663 HS_DTRACE_PROBE8(hotspot, compiled__method__load,
1664 moop->klass_name()->bytes(),
1665 moop->klass_name()->utf8_length(),
1666 moop->name()->bytes(),
1667 moop->name()->utf8_length(),
1668 moop->signature()->bytes(),
1669 moop->signature()->utf8_length(),
1670 insts_begin(), insts_size());
1671 #else /* USDT2 */
1672 HOTSPOT_COMPILED_METHOD_LOAD(
1673 (char *) moop->klass_name()->bytes(),
1674 moop->klass_name()->utf8_length(),
1675 (char *) moop->name()->bytes(),
1676 moop->name()->utf8_length(),
1677 (char *) moop->signature()->bytes(),
1678 moop->signature()->utf8_length(),
1679 insts_begin(), insts_size());
1680 #endif /* USDT2 */
1682 if (JvmtiExport::should_post_compiled_method_load() ||
1683 JvmtiExport::should_post_compiled_method_unload()) {
1684 get_and_cache_jmethod_id();
1685 }
1687 if (JvmtiExport::should_post_compiled_method_load()) {
1688 // Let the Service thread (which is a real Java thread) post the event
1689 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1690 JvmtiDeferredEventQueue::enqueue(
1691 JvmtiDeferredEvent::compiled_method_load_event(this));
1692 }
1693 }
1695 jmethodID nmethod::get_and_cache_jmethod_id() {
1696 if (_jmethod_id == NULL) {
1697 // Cache the jmethod_id since it can no longer be looked up once the
1698 // method itself has been marked for unloading.
1699 _jmethod_id = method()->jmethod_id();
1700 }
1701 return _jmethod_id;
1702 }
1704 void nmethod::post_compiled_method_unload() {
1705 if (unload_reported()) {
1706 // During unloading we transition to unloaded and then to zombie
1707 // and the unloading is reported during the first transition.
1708 return;
1709 }
1711 assert(_method != NULL && !is_unloaded(), "just checking");
1712 DTRACE_METHOD_UNLOAD_PROBE(method());
1714 // If a JVMTI agent has enabled the CompiledMethodUnload event then
1715 // post the event. Sometime later this nmethod will be made a zombie
1716 // by the sweeper but the Method* will not be valid at that point.
1717 // If the _jmethod_id is null then no load event was ever requested
1718 // so don't bother posting the unload. The main reason for this is
1719 // that the jmethodID is a weak reference to the Method* so if
1720 // it's being unloaded there's no way to look it up since the weak
1721 // ref will have been cleared.
1722 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1723 assert(!unload_reported(), "already unloaded");
1724 JvmtiDeferredEvent event =
1725 JvmtiDeferredEvent::compiled_method_unload_event(this,
1726 _jmethod_id, insts_begin());
1727 if (SafepointSynchronize::is_at_safepoint()) {
1728 // Don't want to take the queueing lock. Add it as pending and
1729 // it will get enqueued later.
1730 JvmtiDeferredEventQueue::add_pending_event(event);
1731 } else {
1732 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1733 JvmtiDeferredEventQueue::enqueue(event);
1734 }
1735 }
1737 // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1738 // any time. As the nmethod is being unloaded now we mark it has
1739 // having the unload event reported - this will ensure that we don't
1740 // attempt to report the event in the unlikely scenario where the
1741 // event is enabled at the time the nmethod is made a zombie.
1742 set_unload_reported();
1743 }
1745 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive, bool mark_on_stack) {
1746 if (ic->is_icholder_call()) {
1747 // The only exception is compiledICHolder oops which may
1748 // yet be marked below. (We check this further below).
1749 CompiledICHolder* cichk_oop = ic->cached_icholder();
1751 if (mark_on_stack) {
1752 Metadata::mark_on_stack(cichk_oop->holder_method());
1753 Metadata::mark_on_stack(cichk_oop->holder_klass());
1754 }
1756 if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1757 cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1758 return;
1759 }
1760 } else {
1761 Metadata* ic_oop = ic->cached_metadata();
1762 if (ic_oop != NULL) {
1763 if (mark_on_stack) {
1764 Metadata::mark_on_stack(ic_oop);
1765 }
1767 if (ic_oop->is_klass()) {
1768 if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1769 return;
1770 }
1771 } else if (ic_oop->is_method()) {
1772 if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1773 return;
1774 }
1775 } else {
1776 ShouldNotReachHere();
1777 }
1778 }
1779 }
1781 ic->set_to_clean();
1782 }
1784 // This is called at the end of the strong tracing/marking phase of a
1785 // GC to unload an nmethod if it contains otherwise unreachable
1786 // oops.
1788 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1789 // Make sure the oop's ready to receive visitors
1790 assert(!is_zombie() && !is_unloaded(),
1791 "should not call follow on zombie or unloaded nmethod");
1793 // If the method is not entrant then a JMP is plastered over the
1794 // first few bytes. If an oop in the old code was there, that oop
1795 // should not get GC'd. Skip the first few bytes of oops on
1796 // not-entrant methods.
1797 address low_boundary = verified_entry_point();
1798 if (is_not_entrant()) {
1799 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1800 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1801 // (See comment above.)
1802 }
1804 // The RedefineClasses() API can cause the class unloading invariant
1805 // to no longer be true. See jvmtiExport.hpp for details.
1806 // Also, leave a debugging breadcrumb in local flag.
1807 bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1808 if (a_class_was_redefined) {
1809 // This set of the unloading_occurred flag is done before the
1810 // call to post_compiled_method_unload() so that the unloading
1811 // of this nmethod is reported.
1812 unloading_occurred = true;
1813 }
1815 // Exception cache
1816 clean_exception_cache(is_alive);
1818 // If class unloading occurred we first iterate over all inline caches and
1819 // clear ICs where the cached oop is referring to an unloaded klass or method.
1820 // The remaining live cached oops will be traversed in the relocInfo::oop_type
1821 // iteration below.
1822 if (unloading_occurred) {
1823 RelocIterator iter(this, low_boundary);
1824 while(iter.next()) {
1825 if (iter.type() == relocInfo::virtual_call_type) {
1826 CompiledIC *ic = CompiledIC_at(&iter);
1827 clean_ic_if_metadata_is_dead(ic, is_alive, false);
1828 }
1829 }
1830 }
1832 // Compiled code
1833 {
1834 RelocIterator iter(this, low_boundary);
1835 while (iter.next()) {
1836 if (iter.type() == relocInfo::oop_type) {
1837 oop_Relocation* r = iter.oop_reloc();
1838 // In this loop, we must only traverse those oops directly embedded in
1839 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
1840 assert(1 == (r->oop_is_immediate()) +
1841 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1842 "oop must be found in exactly one place");
1843 if (r->oop_is_immediate() && r->oop_value() != NULL) {
1844 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1845 return;
1846 }
1847 }
1848 }
1849 }
1850 }
1853 // Scopes
1854 for (oop* p = oops_begin(); p < oops_end(); p++) {
1855 if (*p == Universe::non_oop_word()) continue; // skip non-oops
1856 if (can_unload(is_alive, p, unloading_occurred)) {
1857 return;
1858 }
1859 }
1861 // Ensure that all metadata is still alive
1862 verify_metadata_loaders(low_boundary, is_alive);
1863 }
1865 template <class CompiledICorStaticCall>
1866 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1867 // Ok, to lookup references to zombies here
1868 CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1869 if (cb != NULL && cb->is_nmethod()) {
1870 nmethod* nm = (nmethod*)cb;
1872 if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1873 // The nmethod has not been processed yet.
1874 return true;
1875 }
1877 // Clean inline caches pointing to both zombie and not_entrant methods
1878 if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1879 ic->set_to_clean();
1880 assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
1881 }
1882 }
1884 return false;
1885 }
1887 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1888 return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1889 }
1891 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1892 return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1893 }
1895 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
1896 assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");
1898 oop_Relocation* r = iter_at_oop->oop_reloc();
1899 // Traverse those oops directly embedded in the code.
1900 // Other oops (oop_index>0) are seen as part of scopes_oops.
1901 assert(1 == (r->oop_is_immediate()) +
1902 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1903 "oop must be found in exactly one place");
1904 if (r->oop_is_immediate() && r->oop_value() != NULL) {
1905 // Unload this nmethod if the oop is dead.
1906 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1907 return true;;
1908 }
1909 }
1911 return false;
1912 }
1914 void nmethod::mark_metadata_on_stack_at(RelocIterator* iter_at_metadata) {
1915 assert(iter_at_metadata->type() == relocInfo::metadata_type, "Wrong relocation type");
1917 metadata_Relocation* r = iter_at_metadata->metadata_reloc();
1918 // In this metadata, we must only follow those metadatas directly embedded in
1919 // the code. Other metadatas (oop_index>0) are seen as part of
1920 // the metadata section below.
1921 assert(1 == (r->metadata_is_immediate()) +
1922 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
1923 "metadata must be found in exactly one place");
1924 if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
1925 Metadata* md = r->metadata_value();
1926 if (md != _method) Metadata::mark_on_stack(md);
1927 }
1928 }
1930 void nmethod::mark_metadata_on_stack_non_relocs() {
1931 // Visit the metadata section
1932 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
1933 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops
1934 Metadata* md = *p;
1935 Metadata::mark_on_stack(md);
1936 }
1938 // Visit metadata not embedded in the other places.
1939 if (_method != NULL) Metadata::mark_on_stack(_method);
1940 }
1942 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1943 ResourceMark rm;
1945 // Make sure the oop's ready to receive visitors
1946 assert(!is_zombie() && !is_unloaded(),
1947 "should not call follow on zombie or unloaded nmethod");
1949 // If the method is not entrant then a JMP is plastered over the
1950 // first few bytes. If an oop in the old code was there, that oop
1951 // should not get GC'd. Skip the first few bytes of oops on
1952 // not-entrant methods.
1953 address low_boundary = verified_entry_point();
1954 if (is_not_entrant()) {
1955 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
1956 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
1957 // (See comment above.)
1958 }
1960 // The RedefineClasses() API can cause the class unloading invariant
1961 // to no longer be true. See jvmtiExport.hpp for details.
1962 // Also, leave a debugging breadcrumb in local flag.
1963 bool a_class_was_redefined = JvmtiExport::has_redefined_a_class();
1964 if (a_class_was_redefined) {
1965 // This set of the unloading_occurred flag is done before the
1966 // call to post_compiled_method_unload() so that the unloading
1967 // of this nmethod is reported.
1968 unloading_occurred = true;
1969 }
1971 // When class redefinition is used all metadata in the CodeCache has to be recorded,
1972 // so that unused "previous versions" can be purged. Since walking the CodeCache can
1973 // be expensive, the "mark on stack" is piggy-backed on this parallel unloading code.
1974 bool mark_metadata_on_stack = a_class_was_redefined;
1976 // Exception cache
1977 clean_exception_cache(is_alive);
1979 bool is_unloaded = false;
1980 bool postponed = false;
1982 RelocIterator iter(this, low_boundary);
1983 while(iter.next()) {
1985 switch (iter.type()) {
1987 case relocInfo::virtual_call_type:
1988 if (unloading_occurred) {
1989 // If class unloading occurred we first iterate over all inline caches and
1990 // clear ICs where the cached oop is referring to an unloaded klass or method.
1991 clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive, mark_metadata_on_stack);
1992 }
1994 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1995 break;
1997 case relocInfo::opt_virtual_call_type:
1998 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1999 break;
2001 case relocInfo::static_call_type:
2002 postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2003 break;
2005 case relocInfo::oop_type:
2006 if (!is_unloaded) {
2007 is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
2008 }
2009 break;
2011 case relocInfo::metadata_type:
2012 if (mark_metadata_on_stack) {
2013 mark_metadata_on_stack_at(&iter);
2014 }
2015 }
2016 }
2018 if (mark_metadata_on_stack) {
2019 mark_metadata_on_stack_non_relocs();
2020 }
2022 if (is_unloaded) {
2023 return postponed;
2024 }
2026 // Scopes
2027 for (oop* p = oops_begin(); p < oops_end(); p++) {
2028 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2029 if (can_unload(is_alive, p, unloading_occurred)) {
2030 is_unloaded = true;
2031 break;
2032 }
2033 }
2035 if (is_unloaded) {
2036 return postponed;
2037 }
2039 // Ensure that all metadata is still alive
2040 verify_metadata_loaders(low_boundary, is_alive);
2042 return postponed;
2043 }
2045 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2046 ResourceMark rm;
2048 // Make sure the oop's ready to receive visitors
2049 assert(!is_zombie(),
2050 "should not call follow on zombie nmethod");
2052 // If the method is not entrant then a JMP is plastered over the
2053 // first few bytes. If an oop in the old code was there, that oop
2054 // should not get GC'd. Skip the first few bytes of oops on
2055 // not-entrant methods.
2056 address low_boundary = verified_entry_point();
2057 if (is_not_entrant()) {
2058 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2059 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2060 // (See comment above.)
2061 }
2063 RelocIterator iter(this, low_boundary);
2064 while(iter.next()) {
2066 switch (iter.type()) {
2068 case relocInfo::virtual_call_type:
2069 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2070 break;
2072 case relocInfo::opt_virtual_call_type:
2073 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2074 break;
2076 case relocInfo::static_call_type:
2077 clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2078 break;
2079 }
2080 }
2081 }
2083 #ifdef ASSERT
2085 class CheckClass : AllStatic {
2086 static BoolObjectClosure* _is_alive;
2088 // Check class_loader is alive for this bit of metadata.
2089 static void check_class(Metadata* md) {
2090 Klass* klass = NULL;
2091 if (md->is_klass()) {
2092 klass = ((Klass*)md);
2093 } else if (md->is_method()) {
2094 klass = ((Method*)md)->method_holder();
2095 } else if (md->is_methodData()) {
2096 klass = ((MethodData*)md)->method()->method_holder();
2097 } else {
2098 md->print();
2099 ShouldNotReachHere();
2100 }
2101 assert(klass->is_loader_alive(_is_alive), "must be alive");
2102 }
2103 public:
2104 static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2105 assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2106 _is_alive = is_alive;
2107 nm->metadata_do(check_class);
2108 }
2109 };
2111 // This is called during a safepoint so can use static data
2112 BoolObjectClosure* CheckClass::_is_alive = NULL;
2113 #endif // ASSERT
2116 // Processing of oop references should have been sufficient to keep
2117 // all strong references alive. Any weak references should have been
2118 // cleared as well. Visit all the metadata and ensure that it's
2119 // really alive.
2120 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2121 #ifdef ASSERT
2122 RelocIterator iter(this, low_boundary);
2123 while (iter.next()) {
2124 // static_stub_Relocations may have dangling references to
2125 // Method*s so trim them out here. Otherwise it looks like
2126 // compiled code is maintaining a link to dead metadata.
2127 address static_call_addr = NULL;
2128 if (iter.type() == relocInfo::opt_virtual_call_type) {
2129 CompiledIC* cic = CompiledIC_at(&iter);
2130 if (!cic->is_call_to_interpreted()) {
2131 static_call_addr = iter.addr();
2132 }
2133 } else if (iter.type() == relocInfo::static_call_type) {
2134 CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2135 if (!csc->is_call_to_interpreted()) {
2136 static_call_addr = iter.addr();
2137 }
2138 }
2139 if (static_call_addr != NULL) {
2140 RelocIterator sciter(this, low_boundary);
2141 while (sciter.next()) {
2142 if (sciter.type() == relocInfo::static_stub_type &&
2143 sciter.static_stub_reloc()->static_call() == static_call_addr) {
2144 sciter.static_stub_reloc()->clear_inline_cache();
2145 }
2146 }
2147 }
2148 }
2149 // Check that the metadata embedded in the nmethod is alive
2150 CheckClass::do_check_class(is_alive, this);
2151 #endif
2152 }
2155 // Iterate over metadata calling this function. Used by RedefineClasses
2156 void nmethod::metadata_do(void f(Metadata*)) {
2157 address low_boundary = verified_entry_point();
2158 if (is_not_entrant()) {
2159 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2160 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2161 // (See comment above.)
2162 }
2163 {
2164 // Visit all immediate references that are embedded in the instruction stream.
2165 RelocIterator iter(this, low_boundary);
2166 while (iter.next()) {
2167 if (iter.type() == relocInfo::metadata_type ) {
2168 metadata_Relocation* r = iter.metadata_reloc();
2169 // In this metadata, we must only follow those metadatas directly embedded in
2170 // the code. Other metadatas (oop_index>0) are seen as part of
2171 // the metadata section below.
2172 assert(1 == (r->metadata_is_immediate()) +
2173 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2174 "metadata must be found in exactly one place");
2175 if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2176 Metadata* md = r->metadata_value();
2177 f(md);
2178 }
2179 } else if (iter.type() == relocInfo::virtual_call_type) {
2180 // Check compiledIC holders associated with this nmethod
2181 CompiledIC *ic = CompiledIC_at(&iter);
2182 if (ic->is_icholder_call()) {
2183 CompiledICHolder* cichk = ic->cached_icholder();
2184 f(cichk->holder_method());
2185 f(cichk->holder_klass());
2186 } else {
2187 Metadata* ic_oop = ic->cached_metadata();
2188 if (ic_oop != NULL) {
2189 f(ic_oop);
2190 }
2191 }
2192 }
2193 }
2194 }
2196 // Visit the metadata section
2197 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2198 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops
2199 Metadata* md = *p;
2200 f(md);
2201 }
2203 // Visit metadata not embedded in the other places.
2204 if (_method != NULL) f(_method);
2205 }
2207 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2208 // make sure the oops ready to receive visitors
2209 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2210 assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2212 // If the method is not entrant or zombie then a JMP is plastered over the
2213 // first few bytes. If an oop in the old code was there, that oop
2214 // should not get GC'd. Skip the first few bytes of oops on
2215 // not-entrant methods.
2216 address low_boundary = verified_entry_point();
2217 if (is_not_entrant()) {
2218 low_boundary += NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::instruction_size;
2219 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
2220 // (See comment above.)
2221 }
2223 RelocIterator iter(this, low_boundary);
2225 while (iter.next()) {
2226 if (iter.type() == relocInfo::oop_type ) {
2227 oop_Relocation* r = iter.oop_reloc();
2228 // In this loop, we must only follow those oops directly embedded in
2229 // the code. Other oops (oop_index>0) are seen as part of scopes_oops.
2230 assert(1 == (r->oop_is_immediate()) +
2231 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2232 "oop must be found in exactly one place");
2233 if (r->oop_is_immediate() && r->oop_value() != NULL) {
2234 f->do_oop(r->oop_addr());
2235 }
2236 }
2237 }
2239 // Scopes
2240 // This includes oop constants not inlined in the code stream.
2241 for (oop* p = oops_begin(); p < oops_end(); p++) {
2242 if (*p == Universe::non_oop_word()) continue; // skip non-oops
2243 f->do_oop(p);
2244 }
2245 }
2247 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2249 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2251 // An nmethod is "marked" if its _mark_link is set non-null.
2252 // Even if it is the end of the linked list, it will have a non-null link value,
2253 // as long as it is on the list.
2254 // This code must be MP safe, because it is used from parallel GC passes.
2255 bool nmethod::test_set_oops_do_mark() {
2256 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2257 nmethod* observed_mark_link = _oops_do_mark_link;
2258 if (observed_mark_link == NULL) {
2259 // Claim this nmethod for this thread to mark.
2260 observed_mark_link = (nmethod*)
2261 Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2262 if (observed_mark_link == NULL) {
2264 // Atomically append this nmethod (now claimed) to the head of the list:
2265 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2266 for (;;) {
2267 nmethod* required_mark_nmethods = observed_mark_nmethods;
2268 _oops_do_mark_link = required_mark_nmethods;
2269 observed_mark_nmethods = (nmethod*)
2270 Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2271 if (observed_mark_nmethods == required_mark_nmethods)
2272 break;
2273 }
2274 // Mark was clear when we first saw this guy.
2275 NOT_PRODUCT(if (TraceScavenge) print_on(tty, "oops_do, mark"));
2276 return false;
2277 }
2278 }
2279 // On fall through, another racing thread marked this nmethod before we did.
2280 return true;
2281 }
2283 void nmethod::oops_do_marking_prologue() {
2284 NOT_PRODUCT(if (TraceScavenge) tty->print_cr("[oops_do_marking_prologue"));
2285 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2286 // We use cmpxchg_ptr instead of regular assignment here because the user
2287 // may fork a bunch of threads, and we need them all to see the same state.
2288 void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2289 guarantee(observed == NULL, "no races in this sequential code");
2290 }
2292 void nmethod::oops_do_marking_epilogue() {
2293 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2294 nmethod* cur = _oops_do_mark_nmethods;
2295 while (cur != NMETHOD_SENTINEL) {
2296 assert(cur != NULL, "not NULL-terminated");
2297 nmethod* next = cur->_oops_do_mark_link;
2298 cur->_oops_do_mark_link = NULL;
2299 cur->verify_oop_relocations();
2300 NOT_PRODUCT(if (TraceScavenge) cur->print_on(tty, "oops_do, unmark"));
2301 cur = next;
2302 }
2303 void* required = _oops_do_mark_nmethods;
2304 void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2305 guarantee(observed == required, "no races in this sequential code");
2306 NOT_PRODUCT(if (TraceScavenge) tty->print_cr("oops_do_marking_epilogue]"));
2307 }
2309 class DetectScavengeRoot: public OopClosure {
2310 bool _detected_scavenge_root;
2311 public:
2312 DetectScavengeRoot() : _detected_scavenge_root(false)
2313 { NOT_PRODUCT(_print_nm = NULL); }
2314 bool detected_scavenge_root() { return _detected_scavenge_root; }
2315 virtual void do_oop(oop* p) {
2316 if ((*p) != NULL && (*p)->is_scavengable()) {
2317 NOT_PRODUCT(maybe_print(p));
2318 _detected_scavenge_root = true;
2319 }
2320 }
2321 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2323 #ifndef PRODUCT
2324 nmethod* _print_nm;
2325 void maybe_print(oop* p) {
2326 if (_print_nm == NULL) return;
2327 if (!_detected_scavenge_root) _print_nm->print_on(tty, "new scavenge root");
2328 tty->print_cr(""PTR_FORMAT"[offset=%d] detected scavengable oop "PTR_FORMAT" (found at "PTR_FORMAT")",
2329 _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2330 (void *)(*p), (intptr_t)p);
2331 (*p)->print();
2332 }
2333 #endif //PRODUCT
2334 };
2336 bool nmethod::detect_scavenge_root_oops() {
2337 DetectScavengeRoot detect_scavenge_root;
2338 NOT_PRODUCT(if (TraceScavenge) detect_scavenge_root._print_nm = this);
2339 oops_do(&detect_scavenge_root);
2340 return detect_scavenge_root.detected_scavenge_root();
2341 }
2343 // Method that knows how to preserve outgoing arguments at call. This method must be
2344 // called with a frame corresponding to a Java invoke
2345 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2346 #ifndef SHARK
2347 if (!method()->is_native()) {
2348 SimpleScopeDesc ssd(this, fr.pc());
2349 Bytecode_invoke call(ssd.method(), ssd.bci());
2350 bool has_receiver = call.has_receiver();
2351 bool has_appendix = call.has_appendix();
2352 Symbol* signature = call.signature();
2353 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2354 }
2355 #endif // !SHARK
2356 }
2359 oop nmethod::embeddedOop_at(u_char* p) {
2360 RelocIterator iter(this, p, p + 1);
2361 while (iter.next())
2362 if (iter.type() == relocInfo::oop_type) {
2363 return iter.oop_reloc()->oop_value();
2364 }
2365 return NULL;
2366 }
2369 inline bool includes(void* p, void* from, void* to) {
2370 return from <= p && p < to;
2371 }
2374 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2375 assert(count >= 2, "must be sentinel values, at least");
2377 #ifdef ASSERT
2378 // must be sorted and unique; we do a binary search in find_pc_desc()
2379 int prev_offset = pcs[0].pc_offset();
2380 assert(prev_offset == PcDesc::lower_offset_limit,
2381 "must start with a sentinel");
2382 for (int i = 1; i < count; i++) {
2383 int this_offset = pcs[i].pc_offset();
2384 assert(this_offset > prev_offset, "offsets must be sorted");
2385 prev_offset = this_offset;
2386 }
2387 assert(prev_offset == PcDesc::upper_offset_limit,
2388 "must end with a sentinel");
2389 #endif //ASSERT
2391 // Search for MethodHandle invokes and tag the nmethod.
2392 for (int i = 0; i < count; i++) {
2393 if (pcs[i].is_method_handle_invoke()) {
2394 set_has_method_handle_invokes(true);
2395 break;
2396 }
2397 }
2398 assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2400 int size = count * sizeof(PcDesc);
2401 assert(scopes_pcs_size() >= size, "oob");
2402 memcpy(scopes_pcs_begin(), pcs, size);
2404 // Adjust the final sentinel downward.
2405 PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2406 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2407 last_pc->set_pc_offset(content_size() + 1);
2408 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2409 // Fill any rounding gaps with copies of the last record.
2410 last_pc[1] = last_pc[0];
2411 }
2412 // The following assert could fail if sizeof(PcDesc) is not
2413 // an integral multiple of oopSize (the rounding term).
2414 // If it fails, change the logic to always allocate a multiple
2415 // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2416 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2417 }
2419 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2420 assert(scopes_data_size() >= size, "oob");
2421 memcpy(scopes_data_begin(), buffer, size);
2422 }
2425 #ifdef ASSERT
2426 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2427 PcDesc* lower = nm->scopes_pcs_begin();
2428 PcDesc* upper = nm->scopes_pcs_end();
2429 lower += 1; // exclude initial sentinel
2430 PcDesc* res = NULL;
2431 for (PcDesc* p = lower; p < upper; p++) {
2432 NOT_PRODUCT(--nmethod_stats.pc_desc_tests); // don't count this call to match_desc
2433 if (match_desc(p, pc_offset, approximate)) {
2434 if (res == NULL)
2435 res = p;
2436 else
2437 res = (PcDesc*) badAddress;
2438 }
2439 }
2440 return res;
2441 }
2442 #endif
2445 // Finds a PcDesc with real-pc equal to "pc"
2446 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2447 address base_address = code_begin();
2448 if ((pc < base_address) ||
2449 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2450 return NULL; // PC is wildly out of range
2451 }
2452 int pc_offset = (int) (pc - base_address);
2454 // Check the PcDesc cache if it contains the desired PcDesc
2455 // (This as an almost 100% hit rate.)
2456 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2457 if (res != NULL) {
2458 assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2459 return res;
2460 }
2462 // Fallback algorithm: quasi-linear search for the PcDesc
2463 // Find the last pc_offset less than the given offset.
2464 // The successor must be the required match, if there is a match at all.
2465 // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2466 PcDesc* lower = scopes_pcs_begin();
2467 PcDesc* upper = scopes_pcs_end();
2468 upper -= 1; // exclude final sentinel
2469 if (lower >= upper) return NULL; // native method; no PcDescs at all
2471 #define assert_LU_OK \
2472 /* invariant on lower..upper during the following search: */ \
2473 assert(lower->pc_offset() < pc_offset, "sanity"); \
2474 assert(upper->pc_offset() >= pc_offset, "sanity")
2475 assert_LU_OK;
2477 // Use the last successful return as a split point.
2478 PcDesc* mid = _pc_desc_cache.last_pc_desc();
2479 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2480 if (mid->pc_offset() < pc_offset) {
2481 lower = mid;
2482 } else {
2483 upper = mid;
2484 }
2486 // Take giant steps at first (4096, then 256, then 16, then 1)
2487 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2488 const int RADIX = (1 << LOG2_RADIX);
2489 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2490 while ((mid = lower + step) < upper) {
2491 assert_LU_OK;
2492 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2493 if (mid->pc_offset() < pc_offset) {
2494 lower = mid;
2495 } else {
2496 upper = mid;
2497 break;
2498 }
2499 }
2500 assert_LU_OK;
2501 }
2503 // Sneak up on the value with a linear search of length ~16.
2504 while (true) {
2505 assert_LU_OK;
2506 mid = lower + 1;
2507 NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2508 if (mid->pc_offset() < pc_offset) {
2509 lower = mid;
2510 } else {
2511 upper = mid;
2512 break;
2513 }
2514 }
2515 #undef assert_LU_OK
2517 if (match_desc(upper, pc_offset, approximate)) {
2518 assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2519 _pc_desc_cache.add_pc_desc(upper);
2520 return upper;
2521 } else {
2522 assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2523 return NULL;
2524 }
2525 }
2528 bool nmethod::check_all_dependencies() {
2529 bool found_check = false;
2530 // wholesale check of all dependencies
2531 for (Dependencies::DepStream deps(this); deps.next(); ) {
2532 if (deps.check_dependency() != NULL) {
2533 found_check = true;
2534 NOT_DEBUG(break);
2535 }
2536 }
2537 return found_check; // tell caller if we found anything
2538 }
2540 bool nmethod::check_dependency_on(DepChange& changes) {
2541 // What has happened:
2542 // 1) a new class dependee has been added
2543 // 2) dependee and all its super classes have been marked
2544 bool found_check = false; // set true if we are upset
2545 for (Dependencies::DepStream deps(this); deps.next(); ) {
2546 // Evaluate only relevant dependencies.
2547 if (deps.spot_check_dependency_at(changes) != NULL) {
2548 found_check = true;
2549 NOT_DEBUG(break);
2550 }
2551 }
2552 return found_check;
2553 }
2555 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2556 InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2557 Array<Method*>* dependee_methods = dependee_ik->methods();
2558 for (Dependencies::DepStream deps(this); deps.next(); ) {
2559 if (deps.type() == Dependencies::evol_method) {
2560 Method* method = deps.method_argument(0);
2561 for (int j = 0; j < dependee_methods->length(); j++) {
2562 if (dependee_methods->at(j) == method) {
2563 // RC_TRACE macro has an embedded ResourceMark
2564 RC_TRACE(0x01000000,
2565 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2566 _method->method_holder()->external_name(),
2567 _method->name()->as_C_string(),
2568 _method->signature()->as_C_string(), compile_id(),
2569 method->method_holder()->external_name(),
2570 method->name()->as_C_string(),
2571 method->signature()->as_C_string()));
2572 if (TraceDependencies || LogCompilation)
2573 deps.log_dependency(dependee);
2574 return true;
2575 }
2576 }
2577 }
2578 }
2579 return false;
2580 }
2582 // Called from mark_for_deoptimization, when dependee is invalidated.
2583 bool nmethod::is_dependent_on_method(Method* dependee) {
2584 for (Dependencies::DepStream deps(this); deps.next(); ) {
2585 if (deps.type() != Dependencies::evol_method)
2586 continue;
2587 Method* method = deps.method_argument(0);
2588 if (method == dependee) return true;
2589 }
2590 return false;
2591 }
2594 bool nmethod::is_patchable_at(address instr_addr) {
2595 assert(insts_contains(instr_addr), "wrong nmethod used");
2596 if (is_zombie()) {
2597 // a zombie may never be patched
2598 return false;
2599 }
2600 return true;
2601 }
2604 address nmethod::continuation_for_implicit_exception(address pc) {
2605 // Exception happened outside inline-cache check code => we are inside
2606 // an active nmethod => use cpc to determine a return address
2607 int exception_offset = pc - code_begin();
2608 int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2609 #ifdef ASSERT
2610 if (cont_offset == 0) {
2611 Thread* thread = ThreadLocalStorage::get_thread_slow();
2612 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2613 HandleMark hm(thread);
2614 ResourceMark rm(thread);
2615 CodeBlob* cb = CodeCache::find_blob(pc);
2616 assert(cb != NULL && cb == this, "");
2617 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, pc);
2618 print();
2619 method()->print_codes();
2620 print_code();
2621 print_pcs();
2622 }
2623 #endif
2624 if (cont_offset == 0) {
2625 // Let the normal error handling report the exception
2626 return NULL;
2627 }
2628 return code_begin() + cont_offset;
2629 }
2633 void nmethod_init() {
2634 // make sure you didn't forget to adjust the filler fields
2635 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2636 }
2639 //-------------------------------------------------------------------------------------------
2642 // QQQ might we make this work from a frame??
2643 nmethodLocker::nmethodLocker(address pc) {
2644 CodeBlob* cb = CodeCache::find_blob(pc);
2645 guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2646 _nm = (nmethod*)cb;
2647 lock_nmethod(_nm);
2648 }
2650 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2651 // should pass zombie_ok == true.
2652 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2653 if (nm == NULL) return;
2654 Atomic::inc(&nm->_lock_count);
2655 guarantee(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2656 }
2658 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2659 if (nm == NULL) return;
2660 Atomic::dec(&nm->_lock_count);
2661 guarantee(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2662 }
2665 // -----------------------------------------------------------------------------
2666 // nmethod::get_deopt_original_pc
2667 //
2668 // Return the original PC for the given PC if:
2669 // (a) the given PC belongs to a nmethod and
2670 // (b) it is a deopt PC
2671 address nmethod::get_deopt_original_pc(const frame* fr) {
2672 if (fr->cb() == NULL) return NULL;
2674 nmethod* nm = fr->cb()->as_nmethod_or_null();
2675 if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2676 return nm->get_original_pc(fr);
2678 return NULL;
2679 }
2682 // -----------------------------------------------------------------------------
2683 // MethodHandle
2685 bool nmethod::is_method_handle_return(address return_pc) {
2686 if (!has_method_handle_invokes()) return false;
2687 PcDesc* pd = pc_desc_at(return_pc);
2688 if (pd == NULL)
2689 return false;
2690 return pd->is_method_handle_invoke();
2691 }
2694 // -----------------------------------------------------------------------------
2695 // Verification
2697 class VerifyOopsClosure: public OopClosure {
2698 nmethod* _nm;
2699 bool _ok;
2700 public:
2701 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2702 bool ok() { return _ok; }
2703 virtual void do_oop(oop* p) {
2704 if ((*p) == NULL || (*p)->is_oop()) return;
2705 if (_ok) {
2706 _nm->print_nmethod(true);
2707 _ok = false;
2708 }
2709 tty->print_cr("*** non-oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2710 (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2711 }
2712 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2713 };
2715 void nmethod::verify() {
2717 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2718 // seems odd.
2720 if (is_zombie() || is_not_entrant() || is_unloaded())
2721 return;
2723 // Make sure all the entry points are correctly aligned for patching.
2724 NOT_MIPS64(NativeJump)MIPS64_ONLY(NativeGeneralJump)::check_verified_entry_alignment(entry_point(), verified_entry_point());
2726 // assert(method()->is_oop(), "must be valid");
2728 ResourceMark rm;
2730 if (!CodeCache::contains(this)) {
2731 fatal(err_msg("nmethod at " INTPTR_FORMAT " not in zone", this));
2732 }
2734 if(is_native_method() )
2735 return;
2737 nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2738 if (nm != this) {
2739 fatal(err_msg("findNMethod did not find this nmethod (" INTPTR_FORMAT ")",
2740 this));
2741 }
2743 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2744 if (! p->verify(this)) {
2745 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", this);
2746 }
2747 }
2749 VerifyOopsClosure voc(this);
2750 oops_do(&voc);
2751 assert(voc.ok(), "embedded oops must be OK");
2752 verify_scavenge_root_oops();
2754 verify_scopes();
2755 }
2758 void nmethod::verify_interrupt_point(address call_site) {
2759 // Verify IC only when nmethod installation is finished.
2760 bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2761 || !this->is_in_use(); // nmethod is installed, but not in 'in_use' state
2762 if (is_installed) {
2763 Thread *cur = Thread::current();
2764 if (CompiledIC_lock->owner() == cur ||
2765 ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2766 SafepointSynchronize::is_at_safepoint())) {
2767 CompiledIC_at(this, call_site);
2768 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2769 } else {
2770 MutexLocker ml_verify (CompiledIC_lock);
2771 CompiledIC_at(this, call_site);
2772 }
2773 }
2775 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2776 assert(pd != NULL, "PcDesc must exist");
2777 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2778 pd->obj_decode_offset(), pd->should_reexecute(),
2779 pd->return_oop());
2780 !sd->is_top(); sd = sd->sender()) {
2781 sd->verify();
2782 }
2783 }
2785 void nmethod::verify_scopes() {
2786 if( !method() ) return; // Runtime stubs have no scope
2787 if (method()->is_native()) return; // Ignore stub methods.
2788 // iterate through all interrupt point
2789 // and verify the debug information is valid.
2790 RelocIterator iter((nmethod*)this);
2791 while (iter.next()) {
2792 address stub = NULL;
2793 switch (iter.type()) {
2794 case relocInfo::virtual_call_type:
2795 verify_interrupt_point(iter.addr());
2796 break;
2797 case relocInfo::opt_virtual_call_type:
2798 stub = iter.opt_virtual_call_reloc()->static_stub();
2799 verify_interrupt_point(iter.addr());
2800 break;
2801 case relocInfo::static_call_type:
2802 stub = iter.static_call_reloc()->static_stub();
2803 //verify_interrupt_point(iter.addr());
2804 break;
2805 case relocInfo::runtime_call_type:
2806 address destination = iter.reloc()->value();
2807 // Right now there is no way to find out which entries support
2808 // an interrupt point. It would be nice if we had this
2809 // information in a table.
2810 break;
2811 }
2812 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2813 }
2814 }
2817 // -----------------------------------------------------------------------------
2818 // Non-product code
2819 #ifndef PRODUCT
2821 class DebugScavengeRoot: public OopClosure {
2822 nmethod* _nm;
2823 bool _ok;
2824 public:
2825 DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2826 bool ok() { return _ok; }
2827 virtual void do_oop(oop* p) {
2828 if ((*p) == NULL || !(*p)->is_scavengable()) return;
2829 if (_ok) {
2830 _nm->print_nmethod(true);
2831 _ok = false;
2832 }
2833 tty->print_cr("*** scavengable oop "PTR_FORMAT" found at "PTR_FORMAT" (offset %d)",
2834 (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2835 (*p)->print();
2836 }
2837 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2838 };
2840 void nmethod::verify_scavenge_root_oops() {
2841 if (UseG1GC) {
2842 return;
2843 }
2845 if (!on_scavenge_root_list()) {
2846 // Actually look inside, to verify the claim that it's clean.
2847 DebugScavengeRoot debug_scavenge_root(this);
2848 oops_do(&debug_scavenge_root);
2849 if (!debug_scavenge_root.ok())
2850 fatal("found an unadvertised bad scavengable oop in the code cache");
2851 }
2852 assert(scavenge_root_not_marked(), "");
2853 }
2855 #endif // PRODUCT
2857 // Printing operations
2859 void nmethod::print() const {
2860 ResourceMark rm;
2861 ttyLocker ttyl; // keep the following output all in one block
2863 tty->print("Compiled method ");
2865 if (is_compiled_by_c1()) {
2866 tty->print("(c1) ");
2867 } else if (is_compiled_by_c2()) {
2868 tty->print("(c2) ");
2869 } else if (is_compiled_by_shark()) {
2870 tty->print("(shark) ");
2871 } else {
2872 tty->print("(nm) ");
2873 }
2875 print_on(tty, NULL);
2877 if (WizardMode) {
2878 tty->print("((nmethod*) "INTPTR_FORMAT ") ", this);
2879 tty->print(" for method " INTPTR_FORMAT , (address)method());
2880 tty->print(" { ");
2881 if (is_in_use()) tty->print("in_use ");
2882 if (is_not_entrant()) tty->print("not_entrant ");
2883 if (is_zombie()) tty->print("zombie ");
2884 if (is_unloaded()) tty->print("unloaded ");
2885 if (on_scavenge_root_list()) tty->print("scavenge_root ");
2886 tty->print_cr("}:");
2887 }
2888 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2889 (address)this,
2890 (address)this + size(),
2891 size());
2892 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2893 relocation_begin(),
2894 relocation_end(),
2895 relocation_size());
2896 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2897 consts_begin(),
2898 consts_end(),
2899 consts_size());
2900 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2901 insts_begin(),
2902 insts_end(),
2903 insts_size());
2904 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2905 stub_begin(),
2906 stub_end(),
2907 stub_size());
2908 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2909 oops_begin(),
2910 oops_end(),
2911 oops_size());
2912 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2913 metadata_begin(),
2914 metadata_end(),
2915 metadata_size());
2916 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2917 scopes_data_begin(),
2918 scopes_data_end(),
2919 scopes_data_size());
2920 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2921 scopes_pcs_begin(),
2922 scopes_pcs_end(),
2923 scopes_pcs_size());
2924 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2925 dependencies_begin(),
2926 dependencies_end(),
2927 dependencies_size());
2928 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2929 handler_table_begin(),
2930 handler_table_end(),
2931 handler_table_size());
2932 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2933 nul_chk_table_begin(),
2934 nul_chk_table_end(),
2935 nul_chk_table_size());
2936 }
2938 void nmethod::print_code() {
2939 HandleMark hm;
2940 ResourceMark m;
2941 Disassembler::decode(this);
2942 }
2945 #ifndef PRODUCT
2947 void nmethod::print_scopes() {
2948 // Find the first pc desc for all scopes in the code and print it.
2949 ResourceMark rm;
2950 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2951 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2952 continue;
2954 ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2955 sd->print_on(tty, p);
2956 }
2957 }
2959 void nmethod::print_dependencies() {
2960 ResourceMark rm;
2961 ttyLocker ttyl; // keep the following output all in one block
2962 tty->print_cr("Dependencies:");
2963 for (Dependencies::DepStream deps(this); deps.next(); ) {
2964 deps.print_dependency();
2965 Klass* ctxk = deps.context_type();
2966 if (ctxk != NULL) {
2967 if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
2968 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name());
2969 }
2970 }
2971 deps.log_dependency(); // put it into the xml log also
2972 }
2973 }
2976 void nmethod::print_relocations() {
2977 ResourceMark m; // in case methods get printed via the debugger
2978 tty->print_cr("relocations:");
2979 RelocIterator iter(this);
2980 iter.print();
2981 if (UseRelocIndex) {
2982 jint* index_end = (jint*)relocation_end() - 1;
2983 jint index_size = *index_end;
2984 jint* index_start = (jint*)( (address)index_end - index_size );
2985 tty->print_cr(" index @" INTPTR_FORMAT ": index_size=%d", index_start, index_size);
2986 if (index_size > 0) {
2987 jint* ip;
2988 for (ip = index_start; ip+2 <= index_end; ip += 2)
2989 tty->print_cr(" (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
2990 ip[0],
2991 ip[1],
2992 header_end()+ip[0],
2993 relocation_begin()-1+ip[1]);
2994 for (; ip < index_end; ip++)
2995 tty->print_cr(" (%d ?)", ip[0]);
2996 tty->print_cr(" @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
2997 ip++;
2998 tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
2999 }
3000 }
3001 }
3004 void nmethod::print_pcs() {
3005 ResourceMark m; // in case methods get printed via debugger
3006 tty->print_cr("pc-bytecode offsets:");
3007 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3008 p->print(this);
3009 }
3010 }
3012 #endif // PRODUCT
3014 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3015 RelocIterator iter(this, begin, end);
3016 bool have_one = false;
3017 while (iter.next()) {
3018 have_one = true;
3019 switch (iter.type()) {
3020 case relocInfo::none: return "no_reloc";
3021 case relocInfo::oop_type: {
3022 stringStream st;
3023 oop_Relocation* r = iter.oop_reloc();
3024 oop obj = r->oop_value();
3025 st.print("oop(");
3026 if (obj == NULL) st.print("NULL");
3027 else obj->print_value_on(&st);
3028 st.print(")");
3029 return st.as_string();
3030 }
3031 case relocInfo::metadata_type: {
3032 stringStream st;
3033 metadata_Relocation* r = iter.metadata_reloc();
3034 Metadata* obj = r->metadata_value();
3035 st.print("metadata(");
3036 if (obj == NULL) st.print("NULL");
3037 else obj->print_value_on(&st);
3038 st.print(")");
3039 return st.as_string();
3040 }
3041 case relocInfo::virtual_call_type: return "virtual_call";
3042 case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
3043 case relocInfo::static_call_type: return "static_call";
3044 case relocInfo::static_stub_type: return "static_stub";
3045 case relocInfo::runtime_call_type: return "runtime_call";
3046 case relocInfo::external_word_type: return "external_word";
3047 case relocInfo::internal_word_type: return "internal_word";
3048 case relocInfo::section_word_type: return "section_word";
3049 case relocInfo::poll_type: return "poll";
3050 case relocInfo::poll_return_type: return "poll_return";
3051 case relocInfo::type_mask: return "type_bit_mask";
3052 }
3053 }
3054 return have_one ? "other" : NULL;
3055 }
3057 // Return a the last scope in (begin..end]
3058 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3059 PcDesc* p = pc_desc_near(begin+1);
3060 if (p != NULL && p->real_pc(this) <= end) {
3061 return new ScopeDesc(this, p->scope_decode_offset(),
3062 p->obj_decode_offset(), p->should_reexecute(),
3063 p->return_oop());
3064 }
3065 return NULL;
3066 }
3068 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3069 if (block_begin == entry_point()) stream->print_cr("[Entry Point]");
3070 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]");
3071 if (block_begin == exception_begin()) stream->print_cr("[Exception Handler]");
3072 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]");
3073 if (block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]");
3075 if (has_method_handle_invokes())
3076 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]");
3078 if (block_begin == consts_begin()) stream->print_cr("[Constants]");
3080 if (block_begin == entry_point()) {
3081 methodHandle m = method();
3082 if (m.not_null()) {
3083 stream->print(" # ");
3084 m->print_value_on(stream);
3085 stream->cr();
3086 }
3087 if (m.not_null() && !is_osr_method()) {
3088 ResourceMark rm;
3089 int sizeargs = m->size_of_parameters();
3090 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3091 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3092 {
3093 int sig_index = 0;
3094 if (!m->is_static())
3095 sig_bt[sig_index++] = T_OBJECT; // 'this'
3096 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3097 BasicType t = ss.type();
3098 sig_bt[sig_index++] = t;
3099 if (type2size[t] == 2) {
3100 sig_bt[sig_index++] = T_VOID;
3101 } else {
3102 assert(type2size[t] == 1, "size is 1 or 2");
3103 }
3104 }
3105 assert(sig_index == sizeargs, "");
3106 }
3107 const char* spname = "sp"; // make arch-specific?
3108 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3109 int stack_slot_offset = this->frame_size() * wordSize;
3110 int tab1 = 14, tab2 = 24;
3111 int sig_index = 0;
3112 int arg_index = (m->is_static() ? 0 : -1);
3113 bool did_old_sp = false;
3114 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3115 bool at_this = (arg_index == -1);
3116 bool at_old_sp = false;
3117 BasicType t = (at_this ? T_OBJECT : ss.type());
3118 assert(t == sig_bt[sig_index], "sigs in sync");
3119 if (at_this)
3120 stream->print(" # this: ");
3121 else
3122 stream->print(" # parm%d: ", arg_index);
3123 stream->move_to(tab1);
3124 VMReg fst = regs[sig_index].first();
3125 VMReg snd = regs[sig_index].second();
3126 if (fst->is_reg()) {
3127 stream->print("%s", fst->name());
3128 if (snd->is_valid()) {
3129 stream->print(":%s", snd->name());
3130 }
3131 } else if (fst->is_stack()) {
3132 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3133 if (offset == stack_slot_offset) at_old_sp = true;
3134 stream->print("[%s+0x%x]", spname, offset);
3135 } else {
3136 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3137 }
3138 stream->print(" ");
3139 stream->move_to(tab2);
3140 stream->print("= ");
3141 if (at_this) {
3142 m->method_holder()->print_value_on(stream);
3143 } else {
3144 bool did_name = false;
3145 if (!at_this && ss.is_object()) {
3146 Symbol* name = ss.as_symbol_or_null();
3147 if (name != NULL) {
3148 name->print_value_on(stream);
3149 did_name = true;
3150 }
3151 }
3152 if (!did_name)
3153 stream->print("%s", type2name(t));
3154 }
3155 if (at_old_sp) {
3156 stream->print(" (%s of caller)", spname);
3157 did_old_sp = true;
3158 }
3159 stream->cr();
3160 sig_index += type2size[t];
3161 arg_index += 1;
3162 if (!at_this) ss.next();
3163 }
3164 if (!did_old_sp) {
3165 stream->print(" # ");
3166 stream->move_to(tab1);
3167 stream->print("[%s+0x%x]", spname, stack_slot_offset);
3168 stream->print(" (%s of caller)", spname);
3169 stream->cr();
3170 }
3171 }
3172 }
3173 }
3175 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3176 // First, find an oopmap in (begin, end].
3177 // We use the odd half-closed interval so that oop maps and scope descs
3178 // which are tied to the byte after a call are printed with the call itself.
3179 address base = code_begin();
3180 OopMapSet* oms = oop_maps();
3181 if (oms != NULL) {
3182 for (int i = 0, imax = oms->size(); i < imax; i++) {
3183 OopMap* om = oms->at(i);
3184 address pc = base + om->offset();
3185 if (pc > begin) {
3186 if (pc <= end) {
3187 st->move_to(column);
3188 st->print("; ");
3189 om->print_on(st);
3190 }
3191 break;
3192 }
3193 }
3194 }
3196 // Print any debug info present at this pc.
3197 ScopeDesc* sd = scope_desc_in(begin, end);
3198 if (sd != NULL) {
3199 st->move_to(column);
3200 if (sd->bci() == SynchronizationEntryBCI) {
3201 st->print(";*synchronization entry");
3202 } else {
3203 if (sd->method() == NULL) {
3204 st->print("method is NULL");
3205 } else if (sd->method()->is_native()) {
3206 st->print("method is native");
3207 } else {
3208 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3209 st->print(";*%s", Bytecodes::name(bc));
3210 switch (bc) {
3211 case Bytecodes::_invokevirtual:
3212 case Bytecodes::_invokespecial:
3213 case Bytecodes::_invokestatic:
3214 case Bytecodes::_invokeinterface:
3215 {
3216 Bytecode_invoke invoke(sd->method(), sd->bci());
3217 st->print(" ");
3218 if (invoke.name() != NULL)
3219 invoke.name()->print_symbol_on(st);
3220 else
3221 st->print("<UNKNOWN>");
3222 break;
3223 }
3224 case Bytecodes::_getfield:
3225 case Bytecodes::_putfield:
3226 case Bytecodes::_getstatic:
3227 case Bytecodes::_putstatic:
3228 {
3229 Bytecode_field field(sd->method(), sd->bci());
3230 st->print(" ");
3231 if (field.name() != NULL)
3232 field.name()->print_symbol_on(st);
3233 else
3234 st->print("<UNKNOWN>");
3235 }
3236 }
3237 }
3238 }
3240 // Print all scopes
3241 for (;sd != NULL; sd = sd->sender()) {
3242 st->move_to(column);
3243 st->print("; -");
3244 if (sd->method() == NULL) {
3245 st->print("method is NULL");
3246 } else {
3247 sd->method()->print_short_name(st);
3248 }
3249 int lineno = sd->method()->line_number_from_bci(sd->bci());
3250 if (lineno != -1) {
3251 st->print("@%d (line %d)", sd->bci(), lineno);
3252 } else {
3253 st->print("@%d", sd->bci());
3254 }
3255 st->cr();
3256 }
3257 }
3259 // Print relocation information
3260 const char* str = reloc_string_for(begin, end);
3261 if (str != NULL) {
3262 if (sd != NULL) st->cr();
3263 st->move_to(column);
3264 st->print("; {%s}", str);
3265 }
3266 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3267 if (cont_offset != 0) {
3268 st->move_to(column);
3269 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, code_begin() + cont_offset);
3270 }
3272 }
3274 #ifndef PRODUCT
3276 void nmethod::print_value_on(outputStream* st) const {
3277 st->print("nmethod");
3278 print_on(st, NULL);
3279 }
3281 void nmethod::print_calls(outputStream* st) {
3282 RelocIterator iter(this);
3283 while (iter.next()) {
3284 switch (iter.type()) {
3285 case relocInfo::virtual_call_type:
3286 case relocInfo::opt_virtual_call_type: {
3287 VerifyMutexLocker mc(CompiledIC_lock);
3288 CompiledIC_at(&iter)->print();
3289 break;
3290 }
3291 case relocInfo::static_call_type:
3292 st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3293 compiledStaticCall_at(iter.reloc())->print();
3294 break;
3295 }
3296 }
3297 }
3299 void nmethod::print_handler_table() {
3300 ExceptionHandlerTable(this).print();
3301 }
3303 void nmethod::print_nul_chk_table() {
3304 ImplicitExceptionTable(this).print(code_begin());
3305 }
3307 void nmethod::print_statistics() {
3308 ttyLocker ttyl;
3309 if (xtty != NULL) xtty->head("statistics type='nmethod'");
3310 nmethod_stats.print_native_nmethod_stats();
3311 nmethod_stats.print_nmethod_stats();
3312 DebugInformationRecorder::print_statistics();
3313 nmethod_stats.print_pc_stats();
3314 Dependencies::print_statistics();
3315 if (xtty != NULL) xtty->tail("statistics");
3316 }
3318 #endif // PRODUCT