1 /*
2 * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #ifndef SHARE_CODE_NMETHOD_HPP
26 #define SHARE_CODE_NMETHOD_HPP
27
28 #include "code/codeBlob.hpp"
29 #include "code/pcDesc.hpp"
30 #include "compiler/compilerDefinitions.hpp"
31 #include "oops/metadata.hpp"
32 #include "oops/method.hpp"
33 #include "runtime/mutexLocker.hpp"
34
35 class AbstractCompiler;
36 class CompiledDirectCall;
37 class CompiledIC;
38 class CompiledICData;
39 class CompileTask;
40 class DepChange;
41 class Dependencies;
42 class DirectiveSet;
43 class DebugInformationRecorder;
44 class ExceptionHandlerTable;
45 class ImplicitExceptionTable;
46 class JvmtiThreadState;
47 class MetadataClosure;
48 class NativeCallWrapper;
49 class OopIterateClosure;
50 class ScopeDesc;
51 class xmlStream;
52
53 // This class is used internally by nmethods, to cache
54 // exception/pc/handler information.
55
56 class ExceptionCache : public CHeapObj<mtCode> {
57 friend class VMStructs;
58 private:
59 enum { cache_size = 16 };
60 Klass* _exception_type;
61 address _pc[cache_size];
62 address _handler[cache_size];
63 volatile int _count;
64 ExceptionCache* volatile _next;
65 ExceptionCache* _purge_list_next;
66
67 inline address pc_at(int index);
68 void set_pc_at(int index, address a) { assert(index >= 0 && index < cache_size,""); _pc[index] = a; }
69
70 inline address handler_at(int index);
71 void set_handler_at(int index, address a) { assert(index >= 0 && index < cache_size,""); _handler[index] = a; }
72
73 inline int count();
74 // increment_count is only called under lock, but there may be concurrent readers.
75 void increment_count();
76
77 public:
78
79 ExceptionCache(Handle exception, address pc, address handler);
80
81 Klass* exception_type() { return _exception_type; }
82 ExceptionCache* next();
83 void set_next(ExceptionCache *ec);
84 ExceptionCache* purge_list_next() { return _purge_list_next; }
85 void set_purge_list_next(ExceptionCache *ec) { _purge_list_next = ec; }
86
87 address match(Handle exception, address pc);
88 bool match_exception_with_space(Handle exception) ;
89 address test_address(address addr);
90 bool add_address_and_handler(address addr, address handler) ;
91 };
92
93 // cache pc descs found in earlier inquiries
94 class PcDescCache {
95 private:
96 enum { cache_size = 4 };
97 // The array elements MUST be volatile! Several threads may modify
98 // and read from the cache concurrently. find_pc_desc_internal has
99 // returned wrong results. C++ compiler (namely xlC12) may duplicate
100 // C++ field accesses if the elements are not volatile.
101 typedef PcDesc* PcDescPtr;
102 volatile PcDescPtr _pc_descs[cache_size]; // last cache_size pc_descs found
103 public:
104 PcDescCache() { DEBUG_ONLY(_pc_descs[0] = nullptr); }
105 void init_to(PcDesc* initial_pc_desc);
106 PcDesc* find_pc_desc(int pc_offset, bool approximate);
107 void add_pc_desc(PcDesc* pc_desc);
108 PcDesc* last_pc_desc() { return _pc_descs[0]; }
109 };
110
111 class PcDescContainer : public CHeapObj<mtCode> {
112 private:
113 PcDescCache _pc_desc_cache;
114 public:
115 PcDescContainer(PcDesc* initial_pc_desc) { _pc_desc_cache.init_to(initial_pc_desc); }
116
117 PcDesc* find_pc_desc_internal(address pc, bool approximate, address code_begin,
118 PcDesc* lower, PcDesc* upper);
119
120 PcDesc* find_pc_desc(address pc, bool approximate, address code_begin, PcDesc* lower, PcDesc* upper)
121 #ifdef PRODUCT
122 {
123 PcDesc* desc = _pc_desc_cache.last_pc_desc();
124 assert(desc != nullptr, "PcDesc cache should be initialized already");
125 if (desc->pc_offset() == (pc - code_begin)) {
126 // Cached value matched
127 return desc;
128 }
129 return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
130 }
131 #endif
132 ;
133 };
134
135 // nmethods (native methods) are the compiled code versions of Java methods.
136 //
137 // An nmethod contains:
138 // - Header (the nmethod structure)
139 // - Constant part (doubles, longs and floats used in nmethod)
140 // - Code part:
141 // - Code body
142 // - Exception handler
143 // - Stub code
144 // - OOP table
145 //
146 // As a CodeBlob, an nmethod references [mutable data] allocated on the C heap:
147 // - CodeBlob relocation data
148 // - Metainfo
149 // - JVMCI data
150 //
151 // An nmethod references [immutable data] allocated on C heap:
152 // - Dependency assertions data
153 // - Implicit null table array
154 // - Handler entry point array
155 // - Debugging information:
156 // - Scopes data array
157 // - Scopes pcs array
158 // - JVMCI speculations array
159 // - Nmethod reference counter
160
161 #if INCLUDE_JVMCI
162 class FailedSpeculation;
163 class JVMCINMethodData;
164 #endif
165
166 class nmethod : public CodeBlob {
167 friend class VMStructs;
168 friend class JVMCIVMStructs;
169 friend class CodeCache; // scavengable oops
170 friend class JVMCINMethodData;
171 friend class DeoptimizationScope;
172
173 #define ImmutableDataRefCountSize ((int)sizeof(int))
174
175 private:
176
177 // Used to track in which deoptimize handshake this method will be deoptimized.
178 uint64_t _deoptimization_generation;
179
180 uint64_t _gc_epoch;
181
182 Method* _method;
183
184 // To reduce header size union fields which usages do not overlap.
185 union {
186 // To support simple linked-list chaining of nmethods:
187 nmethod* _osr_link; // from InstanceKlass::osr_nmethods_head
188 struct {
189 // These are used for compiled synchronized native methods to
190 // locate the owner and stack slot for the BasicLock. They are
191 // needed because there is no debug information for compiled native
192 // wrappers and the oop maps are insufficient to allow
193 // frame::retrieve_receiver() to work. Currently they are expected
194 // to be byte offsets from the Java stack pointer for maximum code
195 // sharing between platforms. JVMTI's GetLocalInstance() uses these
196 // offsets to find the receiver for non-static native wrapper frames.
197 ByteSize _native_receiver_sp_offset;
198 ByteSize _native_basic_lock_sp_offset;
199 };
200 };
201
202 // nmethod's read-only data
203 address _immutable_data;
204
205 PcDescContainer* _pc_desc_container;
206 ExceptionCache* volatile _exception_cache;
207
208 void* _gc_data;
209
210 struct oops_do_mark_link; // Opaque data type.
211 static nmethod* volatile _oops_do_mark_nmethods;
212 oops_do_mark_link* volatile _oops_do_mark_link;
213
214 CompiledICData* _compiled_ic_data;
215
216 // offsets for entry points
217 address _osr_entry_point; // entry point for on stack replacement
218 uint16_t _entry_offset; // entry point with class check
219 uint16_t _verified_entry_offset; // entry point without class check
220 uint16_t _inline_entry_offset; // inline type entry point (unpack all inline type args) with class check
221 uint16_t _verified_inline_entry_offset; // inline type entry point (unpack all inline type args) without class check
222 uint16_t _verified_inline_ro_entry_offset; // inline type entry point (unpack receiver only) without class check
223 int _entry_bci; // != InvocationEntryBci if this nmethod is an on-stack replacement method
224 int _immutable_data_size;
225
226 // _consts_offset == _content_offset because SECT_CONSTS is first in code buffer
227
228 int _skipped_instructions_size;
229
230 int _stub_offset;
231
232 // Offsets for different stubs section parts
233 int _exception_offset;
234 // All deoptee's will resume execution at this location described by
235 // this offset.
236 int _deopt_handler_entry_offset;
237 // Offset (from insts_end) of the unwind handler if it exists
238 int16_t _unwind_handler_offset;
239 // Number of arguments passed on the stack
240 uint16_t _num_stack_arg_slots;
241
242 uint16_t _oops_size;
243 #if INCLUDE_JVMCI
244 // _metadata_size is not specific to JVMCI. In the non-JVMCI case, it can be derived as:
245 // _metadata_size = mutable_data_size - relocation_size
246 uint16_t _metadata_size;
247 #endif
248
249 // Offset in immutable data section
250 // _dependencies_offset == 0
251 uint16_t _nul_chk_table_offset;
252 uint16_t _handler_table_offset; // This table could be big in C1 code
253 int _scopes_pcs_offset;
254 int _scopes_data_offset;
255 #if INCLUDE_JVMCI
256 int _speculations_offset;
257 #endif
258 int _immutable_data_ref_count_offset;
259
260 // location in frame (offset for sp) that deopt can store the original
261 // pc during a deopt.
262 int _orig_pc_offset;
263
264 int _compile_id; // which compilation made this nmethod
265 CompLevel _comp_level; // compilation level (s1)
266 CompilerType _compiler_type; // which compiler made this nmethod (u1)
267
268 // Local state used to keep track of whether unloading is happening or not
269 volatile uint8_t _is_unloading_state;
270
271 // Protected by NMethodState_lock
272 volatile signed char _state; // {not_installed, in_use, not_entrant}
273
274 // set during construction
275 uint8_t _has_unsafe_access:1, // May fault due to unsafe access.
276 _has_wide_vectors:1, // Preserve wide vectors at safepoints
277 _has_monitors:1, // Fastpath monitor detection for continuations
278 _has_scoped_access:1, // used by for shared scope closure (scopedMemoryAccess.cpp)
279 _has_flushed_dependencies:1, // Used for maintenance of dependencies (under CodeCache_lock)
280 _is_unlinked:1, // mark during class unloading
281 _load_reported:1; // used by jvmti to track if an event has been posted for this nmethod
282
283 enum DeoptimizationStatus : u1 {
284 not_marked,
285 deoptimize,
286 deoptimize_noupdate,
287 deoptimize_done
288 };
289
290 volatile DeoptimizationStatus _deoptimization_status; // Used for stack deoptimization
291
292 DeoptimizationStatus deoptimization_status() const {
293 return AtomicAccess::load(&_deoptimization_status);
294 }
295
296 // Initialize fields to their default values
297 void init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets);
298
299 // Post initialization
300 void post_init();
301
302 // For native wrappers
303 nmethod(Method* method,
304 CompilerType type,
305 int nmethod_size,
306 int compile_id,
307 CodeOffsets* offsets,
308 CodeBuffer *code_buffer,
309 int frame_size,
310 ByteSize basic_lock_owner_sp_offset, /* synchronized natives only */
311 ByteSize basic_lock_sp_offset, /* synchronized natives only */
312 OopMapSet* oop_maps,
313 int mutable_data_size);
314
315 // For normal JIT compiled code
316 nmethod(Method* method,
317 CompilerType type,
318 int nmethod_size,
319 int immutable_data_size,
320 int mutable_data_size,
321 int compile_id,
322 int entry_bci,
323 address immutable_data,
324 CodeOffsets* offsets,
325 int orig_pc_offset,
326 DebugInformationRecorder *recorder,
327 Dependencies* dependencies,
328 CodeBuffer *code_buffer,
329 int frame_size,
330 OopMapSet* oop_maps,
331 ExceptionHandlerTable* handler_table,
332 ImplicitExceptionTable* nul_chk_table,
333 AbstractCompiler* compiler,
334 CompLevel comp_level
335 #if INCLUDE_JVMCI
336 , char* speculations = nullptr,
337 int speculations_len = 0,
338 JVMCINMethodData* jvmci_data = nullptr
339 #endif
340 );
341
342 nmethod(const nmethod &nm);
343
344 // helper methods
345 void* operator new(size_t size, int nmethod_size, int comp_level) throw();
346 void* operator new(size_t size, int nmethod_size, CodeBlobType code_blob_type) throw();
347
348 // For method handle intrinsics: Try MethodNonProfiled, MethodProfiled and NonNMethod.
349 // Attention: Only allow NonNMethod space for special nmethods which don't need to be
350 // findable by nmethod iterators! In particular, they must not contain oops!
351 void* operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw();
352
353 const char* reloc_string_for(u_char* begin, u_char* end);
354
355 bool try_transition(signed char new_state);
356
357 // Returns true if this thread changed the state of the nmethod or
358 // false if another thread performed the transition.
359 bool make_entrant() { Unimplemented(); return false; }
360 void inc_decompile_count();
361
362 // Inform external interfaces that a compiled method has been unloaded
363 void post_compiled_method_unload();
364
365 PcDesc* find_pc_desc(address pc, bool approximate) {
366 if (_pc_desc_container == nullptr) return nullptr; // native method
367 return _pc_desc_container->find_pc_desc(pc, approximate, code_begin(), scopes_pcs_begin(), scopes_pcs_end());
368 }
369
370 // STW two-phase nmethod root processing helpers.
371 //
372 // When determining liveness of a given nmethod to do code cache unloading,
373 // some collectors need to do different things depending on whether the nmethods
374 // need to absolutely be kept alive during root processing; "strong"ly reachable
375 // nmethods are known to be kept alive at root processing, but the liveness of
376 // "weak"ly reachable ones is to be determined later.
377 //
378 // We want to allow strong and weak processing of nmethods by different threads
379 // at the same time without heavy synchronization. Additional constraints are
380 // to make sure that every nmethod is processed a minimal amount of time, and
381 // nmethods themselves are always iterated at most once at a particular time.
382 //
383 // Note that strong processing work must be a superset of weak processing work
384 // for this code to work.
385 //
386 // We store state and claim information in the _oops_do_mark_link member, using
387 // the two LSBs for the state and the remaining upper bits for linking together
388 // nmethods that were already visited.
389 // The last element is self-looped, i.e. points to itself to avoid some special
390 // "end-of-list" sentinel value.
391 //
392 // _oops_do_mark_link special values:
393 //
394 // _oops_do_mark_link == nullptr: the nmethod has not been visited at all yet, i.e.
395 // is Unclaimed.
396 //
397 // For other values, its lowest two bits indicate the following states of the nmethod:
398 //
399 // weak_request (WR): the nmethod has been claimed by a thread for weak processing
400 // weak_done (WD): weak processing has been completed for this nmethod.
401 // strong_request (SR): the nmethod has been found to need strong processing while
402 // being weak processed.
403 // strong_done (SD): strong processing has been completed for this nmethod .
404 //
405 // The following shows the _only_ possible progressions of the _oops_do_mark_link
406 // pointer.
407 //
408 // Given
409 // N as the nmethod
410 // X the current next value of _oops_do_mark_link
411 //
412 // Unclaimed (C)-> N|WR (C)-> X|WD: the nmethod has been processed weakly by
413 // a single thread.
414 // Unclaimed (C)-> N|WR (C)-> X|WD (O)-> X|SD: after weak processing has been
415 // completed (as above) another thread found that the nmethod needs strong
416 // processing after all.
417 // Unclaimed (C)-> N|WR (O)-> N|SR (C)-> X|SD: during weak processing another
418 // thread finds that the nmethod needs strong processing, marks it as such and
419 // terminates. The original thread completes strong processing.
420 // Unclaimed (C)-> N|SD (C)-> X|SD: the nmethod has been processed strongly from
421 // the beginning by a single thread.
422 //
423 // "|" describes the concatenation of bits in _oops_do_mark_link.
424 //
425 // The diagram also describes the threads responsible for changing the nmethod to
426 // the next state by marking the _transition_ with (C) and (O), which mean "current"
427 // and "other" thread respectively.
428 //
429
430 // States used for claiming nmethods during root processing.
431 static const uint claim_weak_request_tag = 0;
432 static const uint claim_weak_done_tag = 1;
433 static const uint claim_strong_request_tag = 2;
434 static const uint claim_strong_done_tag = 3;
435
436 static oops_do_mark_link* mark_link(nmethod* nm, uint tag) {
437 assert(tag <= claim_strong_done_tag, "invalid tag %u", tag);
438 assert(is_aligned(nm, 4), "nmethod pointer must have zero lower two LSB");
439 return (oops_do_mark_link*)(((uintptr_t)nm & ~0x3) | tag);
440 }
441
442 static uint extract_state(oops_do_mark_link* link) {
443 return (uint)((uintptr_t)link & 0x3);
444 }
445
446 static nmethod* extract_nmethod(oops_do_mark_link* link) {
447 return (nmethod*)((uintptr_t)link & ~0x3);
448 }
449
450 void oops_do_log_change(const char* state);
451
452 static bool oops_do_has_weak_request(oops_do_mark_link* next) {
453 return extract_state(next) == claim_weak_request_tag;
454 }
455
456 static bool oops_do_has_any_strong_state(oops_do_mark_link* next) {
457 return extract_state(next) >= claim_strong_request_tag;
458 }
459
460 // Attempt Unclaimed -> N|WR transition. Returns true if successful.
461 bool oops_do_try_claim_weak_request();
462
463 // Attempt Unclaimed -> N|SD transition. Returns the current link.
464 oops_do_mark_link* oops_do_try_claim_strong_done();
465 // Attempt N|WR -> X|WD transition. Returns nullptr if successful, X otherwise.
466 nmethod* oops_do_try_add_to_list_as_weak_done();
467
468 // Attempt X|WD -> N|SR transition. Returns the current link.
469 oops_do_mark_link* oops_do_try_add_strong_request(oops_do_mark_link* next);
470 // Attempt X|WD -> X|SD transition. Returns true if successful.
471 bool oops_do_try_claim_weak_done_as_strong_done(oops_do_mark_link* next);
472
473 // Do the N|SD -> X|SD transition.
474 void oops_do_add_to_list_as_strong_done();
475
476 // Sets this nmethod as strongly claimed (as part of N|SD -> X|SD and N|SR -> X|SD
477 // transitions).
478 void oops_do_set_strong_done(nmethod* old_head);
479
480 public:
481 // If you change anything in this enum please patch
482 // vmStructs_jvmci.cpp accordingly.
483 enum class InvalidationReason : s1 {
484 NOT_INVALIDATED = -1,
485 C1_CODEPATCH,
486 C1_DEOPTIMIZE,
487 C1_DEOPTIMIZE_FOR_PATCHING,
488 C1_PREDICATE_FAILED_TRAP,
489 CI_REPLAY,
490 UNLOADING,
491 UNLOADING_COLD,
492 JVMCI_INVALIDATE,
493 JVMCI_MATERIALIZE_VIRTUAL_OBJECT,
494 JVMCI_REPLACED_WITH_NEW_CODE,
495 JVMCI_REPROFILE,
496 MARKED_FOR_DEOPTIMIZATION,
497 MISSING_EXCEPTION_HANDLER,
498 NOT_USED,
499 OSR_INVALIDATION_BACK_BRANCH,
500 OSR_INVALIDATION_FOR_COMPILING_WITH_C1,
501 OSR_INVALIDATION_OF_LOWER_LEVEL,
502 SET_NATIVE_FUNCTION,
503 UNCOMMON_TRAP,
504 WHITEBOX_DEOPTIMIZATION,
505 ZOMBIE,
506 RELOCATED,
507 INVALIDATION_REASONS_COUNT
508 };
509
510
511 static const char* invalidation_reason_to_string(InvalidationReason invalidation_reason) {
512 switch (invalidation_reason) {
513 case InvalidationReason::C1_CODEPATCH:
514 return "C1 code patch";
515 case InvalidationReason::C1_DEOPTIMIZE:
516 return "C1 deoptimized";
517 case InvalidationReason::C1_DEOPTIMIZE_FOR_PATCHING:
518 return "C1 deoptimize for patching";
519 case InvalidationReason::C1_PREDICATE_FAILED_TRAP:
520 return "C1 predicate failed trap";
521 case InvalidationReason::CI_REPLAY:
522 return "CI replay";
523 case InvalidationReason::JVMCI_INVALIDATE:
524 return "JVMCI invalidate";
525 case InvalidationReason::JVMCI_MATERIALIZE_VIRTUAL_OBJECT:
526 return "JVMCI materialize virtual object";
527 case InvalidationReason::JVMCI_REPLACED_WITH_NEW_CODE:
528 return "JVMCI replaced with new code";
529 case InvalidationReason::JVMCI_REPROFILE:
530 return "JVMCI reprofile";
531 case InvalidationReason::MARKED_FOR_DEOPTIMIZATION:
532 return "marked for deoptimization";
533 case InvalidationReason::MISSING_EXCEPTION_HANDLER:
534 return "missing exception handler";
535 case InvalidationReason::NOT_USED:
536 return "not used";
537 case InvalidationReason::OSR_INVALIDATION_BACK_BRANCH:
538 return "OSR invalidation back branch";
539 case InvalidationReason::OSR_INVALIDATION_FOR_COMPILING_WITH_C1:
540 return "OSR invalidation for compiling with C1";
541 case InvalidationReason::OSR_INVALIDATION_OF_LOWER_LEVEL:
542 return "OSR invalidation of lower level";
543 case InvalidationReason::SET_NATIVE_FUNCTION:
544 return "set native function";
545 case InvalidationReason::UNCOMMON_TRAP:
546 return "uncommon trap";
547 case InvalidationReason::WHITEBOX_DEOPTIMIZATION:
548 return "whitebox deoptimization";
549 case InvalidationReason::ZOMBIE:
550 return "zombie";
551 case InvalidationReason::RELOCATED:
552 return "relocated";
553 default: {
554 assert(false, "Unhandled reason");
555 return "Unknown";
556 }
557 }
558 }
559
560 // create nmethod with entry_bci
561 static nmethod* new_nmethod(const methodHandle& method,
562 int compile_id,
563 int entry_bci,
564 CodeOffsets* offsets,
565 int orig_pc_offset,
566 DebugInformationRecorder* recorder,
567 Dependencies* dependencies,
568 CodeBuffer *code_buffer,
569 int frame_size,
570 OopMapSet* oop_maps,
571 ExceptionHandlerTable* handler_table,
572 ImplicitExceptionTable* nul_chk_table,
573 AbstractCompiler* compiler,
574 CompLevel comp_level
575 #if INCLUDE_JVMCI
576 , char* speculations = nullptr,
577 int speculations_len = 0,
578 JVMCINMethodData* jvmci_data = nullptr
579 #endif
580 );
581
582 // Relocate the nmethod to the code heap identified by code_blob_type.
583 // Returns nullptr if the code heap does not have enough space, the
584 // nmethod is unrelocatable, or the nmethod is invalidated during relocation,
585 // otherwise the relocated nmethod. The original nmethod will be marked not entrant.
586 nmethod* relocate(CodeBlobType code_blob_type);
587
588 static nmethod* new_native_nmethod(const methodHandle& method,
589 int compile_id,
590 CodeBuffer *code_buffer,
591 int vep_offset,
592 int frame_complete,
593 int frame_size,
594 ByteSize receiver_sp_offset,
595 ByteSize basic_lock_sp_offset,
596 OopMapSet* oop_maps,
597 int exception_handler = -1);
598
599 Method* method () const { return _method; }
600 bool is_native_method() const { return _method != nullptr && _method->is_native(); }
601 bool is_java_method () const { return _method != nullptr && !_method->is_native(); }
602 bool is_osr_method () const { return _entry_bci != InvocationEntryBci; }
603
604 bool is_relocatable();
605
606 // Compiler task identification. Note that all OSR methods
607 // are numbered in an independent sequence if CICountOSR is true,
608 // and native method wrappers are also numbered independently if
609 // CICountNative is true.
610 int compile_id() const { return _compile_id; }
611 const char* compile_kind() const;
612
613 inline bool is_compiled_by_c1 () const { return _compiler_type == compiler_c1; }
614 inline bool is_compiled_by_c2 () const { return _compiler_type == compiler_c2; }
615 inline bool is_compiled_by_jvmci() const { return _compiler_type == compiler_jvmci; }
616 CompilerType compiler_type () const { return _compiler_type; }
617 const char* compiler_name () const;
618
619 // boundaries for different parts
620 address consts_begin () const { return content_begin(); }
621 address consts_end () const { return code_begin() ; }
622 address insts_begin () const { return code_begin() ; }
623 address insts_end () const { return header_begin() + _stub_offset ; }
624 address stub_begin () const { return header_begin() + _stub_offset ; }
625 address stub_end () const { return code_end() ; }
626 address exception_begin () const { return header_begin() + _exception_offset ; }
627 address deopt_handler_entry () const { return header_begin() + _deopt_handler_entry_offset ; }
628 address unwind_handler_begin () const { return _unwind_handler_offset != -1 ? (insts_end() - _unwind_handler_offset) : nullptr; }
629 oop* oops_begin () const { return (oop*) data_begin(); }
630 oop* oops_end () const { return (oop*) data_end(); }
631
632 // mutable data
633 Metadata** metadata_begin () const { return (Metadata**) (mutable_data_begin() + _relocation_size); }
634 #if INCLUDE_JVMCI
635 Metadata** metadata_end () const { return (Metadata**) (mutable_data_begin() + _relocation_size + _metadata_size); }
636 address jvmci_data_begin () const { return mutable_data_begin() + _relocation_size + _metadata_size; }
637 address jvmci_data_end () const { return mutable_data_end(); }
638 #else
639 Metadata** metadata_end () const { return (Metadata**) mutable_data_end(); }
640 #endif
641
642 // immutable data
643 address immutable_data_begin () const { return _immutable_data; }
644 address immutable_data_end () const { return _immutable_data + _immutable_data_size ; }
645 address dependencies_begin () const { return _immutable_data; }
646 address dependencies_end () const { return _immutable_data + _nul_chk_table_offset; }
647 address nul_chk_table_begin () const { return _immutable_data + _nul_chk_table_offset; }
648 address nul_chk_table_end () const { return _immutable_data + _handler_table_offset; }
649 address handler_table_begin () const { return _immutable_data + _handler_table_offset; }
650 address handler_table_end () const { return _immutable_data + _scopes_pcs_offset ; }
651 PcDesc* scopes_pcs_begin () const { return (PcDesc*)(_immutable_data + _scopes_pcs_offset) ; }
652 PcDesc* scopes_pcs_end () const { return (PcDesc*)(_immutable_data + _scopes_data_offset) ; }
653 address scopes_data_begin () const { return _immutable_data + _scopes_data_offset ; }
654
655 #if INCLUDE_JVMCI
656 address scopes_data_end () const { return _immutable_data + _speculations_offset ; }
657 address speculations_begin () const { return _immutable_data + _speculations_offset ; }
658 address speculations_end () const { return _immutable_data + _immutable_data_ref_count_offset ; }
659 #else
660 address scopes_data_end () const { return _immutable_data + _immutable_data_ref_count_offset ; }
661 #endif
662 address immutable_data_ref_count_begin () const { return _immutable_data + _immutable_data_ref_count_offset ; }
663
664 // Sizes
665 int immutable_data_size() const { return _immutable_data_size; }
666 int consts_size () const { return int( consts_end () - consts_begin ()); }
667 int insts_size () const { return int( insts_end () - insts_begin ()); }
668 int stub_size () const { return int( stub_end () - stub_begin ()); }
669 int oops_size () const { return int((address) oops_end () - (address) oops_begin ()); }
670 int metadata_size () const { return int((address) metadata_end () - (address) metadata_begin ()); }
671 int scopes_data_size () const { return int( scopes_data_end () - scopes_data_begin ()); }
672 int scopes_pcs_size () const { return int((intptr_t)scopes_pcs_end () - (intptr_t)scopes_pcs_begin ()); }
673 int dependencies_size () const { return int( dependencies_end () - dependencies_begin ()); }
674 int handler_table_size () const { return int( handler_table_end() - handler_table_begin()); }
675 int nul_chk_table_size () const { return int( nul_chk_table_end() - nul_chk_table_begin()); }
676 #if INCLUDE_JVMCI
677 int speculations_size () const { return int( speculations_end () - speculations_begin ()); }
678 int jvmci_data_size () const { return int( jvmci_data_end () - jvmci_data_begin ()); }
679 #endif
680
681 int oops_count() const { assert(oops_size() % oopSize == 0, ""); return (oops_size() / oopSize) + 1; }
682 int metadata_count() const { assert(metadata_size() % wordSize == 0, ""); return (metadata_size() / wordSize) + 1; }
683
684 int skipped_instructions_size () const { return _skipped_instructions_size; }
685 int total_size() const;
686
687 // Containment
688 bool consts_contains (address addr) const { return consts_begin () <= addr && addr < consts_end (); }
689 // Returns true if a given address is in the 'insts' section. The method
690 // insts_contains_inclusive() is end-inclusive.
691 bool insts_contains (address addr) const { return insts_begin () <= addr && addr < insts_end (); }
692 bool insts_contains_inclusive(address addr) const { return insts_begin () <= addr && addr <= insts_end (); }
693 bool stub_contains (address addr) const { return stub_begin () <= addr && addr < stub_end (); }
694 bool oops_contains (oop* addr) const { return oops_begin () <= addr && addr < oops_end (); }
695 bool metadata_contains (Metadata** addr) const { return metadata_begin () <= addr && addr < metadata_end (); }
696 bool scopes_data_contains (address addr) const { return scopes_data_begin () <= addr && addr < scopes_data_end (); }
697 bool scopes_pcs_contains (PcDesc* addr) const { return scopes_pcs_begin () <= addr && addr < scopes_pcs_end (); }
698 bool handler_table_contains (address addr) const { return handler_table_begin() <= addr && addr < handler_table_end(); }
699 bool nul_chk_table_contains (address addr) const { return nul_chk_table_begin() <= addr && addr < nul_chk_table_end(); }
700
701 // entry points
702 address entry_point() const { return code_begin() + _entry_offset; } // normal entry point
703 address verified_entry_point() const { return code_begin() + _verified_entry_offset; } // if klass is correct
704 address inline_entry_point() const { return code_begin() + _inline_entry_offset; } // inline type entry point (unpack all inline type args)
705 address verified_inline_entry_point() const { return code_begin() + _verified_inline_entry_offset; } // inline type entry point (unpack all inline type args) without class check
706 address verified_inline_ro_entry_point() const { return code_begin() + _verified_inline_ro_entry_offset; } // inline type entry point (only unpack receiver) without class check
707
708 enum : signed char { not_installed = -1, // in construction, only the owner doing the construction is
709 // allowed to advance state
710 in_use = 0, // executable nmethod
711 not_entrant = 1 // marked for deoptimization but activations may still exist
712 };
713
714 // flag accessing and manipulation
715 bool is_not_installed() const { return _state == not_installed; }
716 bool is_in_use() const { return _state <= in_use; }
717 bool is_not_entrant() const { return _state == not_entrant; }
718 int get_state() const { return _state; }
719
720 void clear_unloading_state();
721 // Heuristically deduce an nmethod isn't worth keeping around
722 bool is_cold();
723 bool is_unloading();
724 void do_unloading(bool unloading_occurred);
725
726 bool make_in_use() {
727 return try_transition(in_use);
728 }
729 // Make the nmethod non entrant. The nmethod will continue to be
730 // alive. It is used when an uncommon trap happens. Returns true
731 // if this thread changed the state of the nmethod or false if
732 // another thread performed the transition.
733 bool make_not_entrant(InvalidationReason invalidation_reason);
734 bool make_not_used() { return make_not_entrant(InvalidationReason::NOT_USED); }
735
736 bool is_marked_for_deoptimization() const { return deoptimization_status() != not_marked; }
737 bool has_been_deoptimized() const { return deoptimization_status() == deoptimize_done; }
738 void set_deoptimized_done();
739
740 bool update_recompile_counts() const {
741 // Update recompile counts when either the update is explicitly requested (deoptimize)
742 // or the nmethod is not marked for deoptimization at all (not_marked).
743 // The latter happens during uncommon traps when deoptimized nmethod is made not entrant.
744 DeoptimizationStatus status = deoptimization_status();
745 return status != deoptimize_noupdate && status != deoptimize_done;
746 }
747
748 // tells whether frames described by this nmethod can be deoptimized
749 // note: native wrappers cannot be deoptimized.
750 bool can_be_deoptimized() const { return is_java_method(); }
751
752 bool has_dependencies() { return dependencies_size() != 0; }
753 void print_dependencies_on(outputStream* out) PRODUCT_RETURN;
754 void flush_dependencies();
755
756 template<typename T>
757 T* gc_data() const { return reinterpret_cast<T*>(_gc_data); }
758 template<typename T>
759 void set_gc_data(T* gc_data) { _gc_data = reinterpret_cast<void*>(gc_data); }
760
761 bool has_unsafe_access() const { return _has_unsafe_access; }
762 void set_has_unsafe_access(bool z) { _has_unsafe_access = z; }
763
764 bool has_monitors() const { return _has_monitors; }
765 void set_has_monitors(bool z) { _has_monitors = z; }
766
767 bool has_scoped_access() const { return _has_scoped_access; }
768 void set_has_scoped_access(bool z) { _has_scoped_access = z; }
769
770 bool has_wide_vectors() const { return _has_wide_vectors; }
771 void set_has_wide_vectors(bool z) { _has_wide_vectors = z; }
772
773 bool needs_stack_repair() const {
774 if (is_compiled_by_c1()) {
775 return method()->c1_needs_stack_repair();
776 } else if (is_compiled_by_c2()) {
777 return method()->c2_needs_stack_repair();
778 } else {
779 return false;
780 }
781 }
782
783 bool has_flushed_dependencies() const { return _has_flushed_dependencies; }
784 void set_has_flushed_dependencies(bool z) {
785 assert(!has_flushed_dependencies(), "should only happen once");
786 _has_flushed_dependencies = z;
787 }
788
789 bool is_unlinked() const { return _is_unlinked; }
790 void set_is_unlinked() {
791 assert(!_is_unlinked, "already unlinked");
792 _is_unlinked = true;
793 }
794
795 int comp_level() const { return _comp_level; }
796
797 // Support for oops in scopes and relocs:
798 // Note: index 0 is reserved for null.
799 oop oop_at(int index) const;
800 oop oop_at_phantom(int index) const; // phantom reference
801 oop* oop_addr_at(int index) const { // for GC
802 // relocation indexes are biased by 1 (because 0 is reserved)
803 assert(index > 0 && index <= oops_count(), "must be a valid non-zero index");
804 return &oops_begin()[index - 1];
805 }
806
807 // Support for meta data in scopes and relocs:
808 // Note: index 0 is reserved for null.
809 Metadata* metadata_at(int index) const { return index == 0 ? nullptr: *metadata_addr_at(index); }
810 Metadata** metadata_addr_at(int index) const { // for GC
811 // relocation indexes are biased by 1 (because 0 is reserved)
812 assert(index > 0 && index <= metadata_count(), "must be a valid non-zero index");
813 return &metadata_begin()[index - 1];
814 }
815
816 void copy_values(GrowableArray<jobject>* oops);
817 void copy_values(GrowableArray<Metadata*>* metadata);
818 void copy_values(GrowableArray<address>* metadata) {} // Nothing to do
819
820 // Relocation support
821 private:
822 void fix_oop_relocations(address begin, address end, bool initialize_immediates);
823 inline void initialize_immediate_oop(oop* dest, jobject handle);
824
825 protected:
826 address oops_reloc_begin() const;
827
828 public:
829 void fix_oop_relocations(address begin, address end) { fix_oop_relocations(begin, end, false); }
830 void fix_oop_relocations() { fix_oop_relocations(nullptr, nullptr, false); }
831
832 bool is_at_poll_return(address pc);
833 bool is_at_poll_or_poll_return(address pc);
834
835 protected:
836 // Exception cache support
837 // Note: _exception_cache may be read and cleaned concurrently.
838 ExceptionCache* exception_cache() const { return _exception_cache; }
839 ExceptionCache* exception_cache_acquire() const;
840
841 public:
842 address handler_for_exception_and_pc(Handle exception, address pc);
843 void add_handler_for_exception_and_pc(Handle exception, address pc, address handler);
844 void clean_exception_cache();
845
846 void add_exception_cache_entry(ExceptionCache* new_entry);
847 ExceptionCache* exception_cache_entry_for_exception(Handle exception);
848
849
850 // Deopt
851 // Return true is the PC is one would expect if the frame is being deopted.
852 inline bool is_deopt_pc(address pc);
853 inline bool is_deopt_entry(address pc);
854
855 // Accessor/mutator for the original pc of a frame before a frame was deopted.
856 address get_original_pc(const frame* fr) { return *orig_pc_addr(fr); }
857 void set_original_pc(const frame* fr, address pc) { *orig_pc_addr(fr) = pc; }
858
859 const char* state() const;
860
861 bool inlinecache_check_contains(address addr) const {
862 return (addr >= code_begin() && (addr < verified_entry_point() || addr < verified_inline_entry_point()));
863 }
864
865 void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f);
866
867 // implicit exceptions support
868 address continuation_for_implicit_div0_exception(address pc) { return continuation_for_implicit_exception(pc, true); }
869 address continuation_for_implicit_null_exception(address pc) { return continuation_for_implicit_exception(pc, false); }
870
871 // Inline cache support for class unloading and nmethod unloading
872 private:
873 void cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all);
874
875 address continuation_for_implicit_exception(address pc, bool for_div0_check);
876
877 public:
878 // Serial version used by whitebox test
879 void cleanup_inline_caches_whitebox();
880
881 void clear_inline_caches();
882
883 // Execute nmethod barrier code, as if entering through nmethod call.
884 void run_nmethod_entry_barrier();
885
886 void verify_oop_relocations();
887
888 bool has_evol_metadata();
889
890 Method* attached_method(address call_pc);
891 Method* attached_method_before_pc(address pc);
892
893 // GC unloading support
894 // Cleans unloaded klasses and unloaded nmethods in inline caches
895
896 void unload_nmethod_caches(bool class_unloading_occurred);
897
898 void unlink_from_method();
899
900 // On-stack replacement support
901 int osr_entry_bci() const { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
902 address osr_entry() const { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
903 nmethod* osr_link() const { return _osr_link; }
904 void set_osr_link(nmethod *n) { _osr_link = n; }
905 void invalidate_osr_method();
906
907 int num_stack_arg_slots(bool rounded = true) const {
908 return rounded ? align_up(_num_stack_arg_slots, 2) : _num_stack_arg_slots;
909 }
910
911 // Verify calls to dead methods have been cleaned.
912 void verify_clean_inline_caches();
913
914 // Unlink this nmethod from the system
915 void unlink();
916
917 // Deallocate this nmethod - called by the GC
918 void purge(bool unregister_nmethod);
919
920 // See comment at definition of _last_seen_on_stack
921 void mark_as_maybe_on_stack();
922 bool is_maybe_on_stack();
923
924 // Evolution support. We make old (discarded) compiled methods point to new Method*s.
925 void set_method(Method* method) { _method = method; }
926
927 #if INCLUDE_JVMCI
928 // Gets the JVMCI name of this nmethod.
929 const char* jvmci_name();
930
931 // Records the pending failed speculation in the
932 // JVMCI speculation log associated with this nmethod.
933 void update_speculation(JavaThread* thread);
934
935 // Gets the data specific to a JVMCI compiled method.
936 // This returns a non-nullptr value iff this nmethod was
937 // compiled by the JVMCI compiler.
938 JVMCINMethodData* jvmci_nmethod_data() const {
939 return jvmci_data_size() == 0 ? nullptr : (JVMCINMethodData*) jvmci_data_begin();
940 }
941
942 // Returns true if the runtime should NOT collect deoptimization profile for a JVMCI
943 // compiled method
944 bool jvmci_skip_profile_deopt() const;
945 #endif
946
947 void oops_do(OopClosure* f);
948
949 // All-in-one claiming of nmethods: returns true if the caller successfully claimed that
950 // nmethod.
951 bool oops_do_try_claim();
952
953 // Loom support for following nmethods on the stack
954 void follow_nmethod(OopIterateClosure* cl);
955
956 // Class containing callbacks for the oops_do_process_weak/strong() methods
957 // below.
958 class OopsDoProcessor {
959 public:
960 // Process the oops of the given nmethod based on whether it has been called
961 // in a weak or strong processing context, i.e. apply either weak or strong
962 // work on it.
963 virtual void do_regular_processing(nmethod* nm) = 0;
964 // Assuming that the oops of the given nmethod has already been its weak
965 // processing applied, apply the remaining strong processing part.
966 virtual void do_remaining_strong_processing(nmethod* nm) = 0;
967 };
968
969 // The following two methods do the work corresponding to weak/strong nmethod
970 // processing.
971 void oops_do_process_weak(OopsDoProcessor* p);
972 void oops_do_process_strong(OopsDoProcessor* p);
973
974 static void oops_do_marking_prologue();
975 static void oops_do_marking_epilogue();
976
977 private:
978 ScopeDesc* scope_desc_in(address begin, address end);
979
980 address* orig_pc_addr(const frame* fr);
981
982 // used by jvmti to track if the load events has been reported
983 bool load_reported() const { return _load_reported; }
984 void set_load_reported() { _load_reported = true; }
985
986 inline void init_immutable_data_ref_count() {
987 assert(is_not_installed(), "should be called in nmethod constructor");
988 *((int*)immutable_data_ref_count_begin()) = 1;
989 }
990
991 inline int inc_immutable_data_ref_count() {
992 assert_lock_strong(CodeCache_lock);
993 int* ref_count = (int*)immutable_data_ref_count_begin();
994 assert(*ref_count > 0, "Must be positive");
995 return ++(*ref_count);
996 }
997
998 inline int dec_immutable_data_ref_count() {
999 assert_lock_strong(CodeCache_lock);
1000 int* ref_count = (int*)immutable_data_ref_count_begin();
1001 assert(*ref_count > 0, "Must be positive");
1002 return --(*ref_count);
1003 }
1004
1005 static void add_delayed_compiled_method_load_event(nmethod* nm) NOT_CDS_RETURN;
1006
1007 public:
1008 // ScopeDesc retrieval operation
1009 PcDesc* pc_desc_at(address pc) { return find_pc_desc(pc, false); }
1010 // pc_desc_near returns the first PcDesc at or after the given pc.
1011 PcDesc* pc_desc_near(address pc) { return find_pc_desc(pc, true); }
1012
1013 // ScopeDesc for an instruction
1014 ScopeDesc* scope_desc_at(address pc);
1015 ScopeDesc* scope_desc_near(address pc);
1016
1017 // copying of debugging information
1018 void copy_scopes_pcs(PcDesc* pcs, int count);
1019 void copy_scopes_data(address buffer, int size);
1020
1021 int orig_pc_offset() { return _orig_pc_offset; }
1022
1023 // Post successful compilation
1024 void post_compiled_method(CompileTask* task);
1025
1026 // jvmti support:
1027 void post_compiled_method_load_event(JvmtiThreadState* state = nullptr);
1028
1029 // verify operations
1030 void verify();
1031 void verify_scopes();
1032 void verify_interrupt_point(address interrupt_point, bool is_inline_cache);
1033
1034 // Disassemble this nmethod with additional debug information, e.g. information about blocks.
1035 void decode2(outputStream* st) const;
1036 void print_constant_pool(outputStream* st);
1037
1038 // Avoid hiding of parent's 'decode(outputStream*)' method.
1039 void decode(outputStream* st) const { decode2(st); } // just delegate here.
1040
1041 // AOT cache support
1042 static void post_delayed_compiled_method_load_events() NOT_CDS_RETURN;
1043
1044 // printing support
1045 void print_on_impl(outputStream* st) const;
1046 void print_code();
1047 void print_value_on_impl(outputStream* st) const;
1048 void print_code_snippet(outputStream* st, address addr) const;
1049
1050 #if defined(SUPPORT_DATA_STRUCTS)
1051 // print output in opt build for disassembler library
1052 void print_relocations() PRODUCT_RETURN;
1053 void print_pcs_on(outputStream* st);
1054 void print_scopes() { print_scopes_on(tty); }
1055 void print_scopes_on(outputStream* st) PRODUCT_RETURN;
1056 void print_handler_table();
1057 void print_nul_chk_table();
1058 void print_recorded_oop(int log_n, int index);
1059 void print_recorded_oops();
1060 void print_recorded_metadata();
1061
1062 void print_oops(outputStream* st); // oops from the underlying CodeBlob.
1063 void print_metadata(outputStream* st); // metadata in metadata pool.
1064 #else
1065 void print_pcs_on(outputStream* st) { return; }
1066 #endif
1067
1068 void print_calls(outputStream* st) PRODUCT_RETURN;
1069 static void print_statistics() PRODUCT_RETURN;
1070
1071 void maybe_print_nmethod(const DirectiveSet* directive);
1072 void print_nmethod(bool print_code);
1073
1074 void print_on_with_msg(outputStream* st, const char* msg) const;
1075
1076 // Logging
1077 void log_identity(xmlStream* log) const;
1078 void log_new_nmethod() const;
1079 void log_relocated_nmethod(nmethod* original) const;
1080 void log_state_change(InvalidationReason invalidation_reason) const;
1081
1082 // Prints block-level comments, including nmethod specific block labels:
1083 void print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels=true) const;
1084 const char* nmethod_section_label(address pos) const;
1085
1086 // returns whether this nmethod has code comments.
1087 bool has_code_comment(address begin, address end);
1088 // Prints a comment for one native instruction (reloc info, pc desc)
1089 void print_code_comment_on(outputStream* st, int column, address begin, address end);
1090
1091 // tells if this compiled method is dependent on the given changes,
1092 // and the changes have invalidated it
1093 bool check_dependency_on(DepChange& changes);
1094
1095 // Tells if this compiled method is dependent on the given method.
1096 // Returns true if this nmethod corresponds to the given method as well.
1097 // It is used for fast breakpoint support and updating the calling convention
1098 // in case of mismatch.
1099 bool is_dependent_on_method(Method* dependee);
1100
1101 // JVMTI's GetLocalInstance() support
1102 ByteSize native_receiver_sp_offset() {
1103 assert(is_native_method(), "sanity");
1104 return _native_receiver_sp_offset;
1105 }
1106 ByteSize native_basic_lock_sp_offset() {
1107 assert(is_native_method(), "sanity");
1108 return _native_basic_lock_sp_offset;
1109 }
1110
1111 // support for code generation
1112 static ByteSize osr_entry_point_offset() { return byte_offset_of(nmethod, _osr_entry_point); }
1113 static ByteSize state_offset() { return byte_offset_of(nmethod, _state); }
1114
1115 void metadata_do(MetadataClosure* f);
1116
1117 address call_instruction_address(address pc) const;
1118
1119 void make_deoptimized();
1120 void finalize_relocations();
1121
1122 class Vptr : public CodeBlob::Vptr {
1123 void print_on(const CodeBlob* instance, outputStream* st) const override {
1124 ttyLocker ttyl;
1125 instance->as_nmethod()->print_on_impl(st);
1126 }
1127 void print_value_on(const CodeBlob* instance, outputStream* st) const override {
1128 instance->as_nmethod()->print_value_on_impl(st);
1129 }
1130 };
1131
1132 static const Vptr _vpntr;
1133 };
1134
1135 struct NMethodMarkingScope : StackObj {
1136 NMethodMarkingScope() {
1137 nmethod::oops_do_marking_prologue();
1138 }
1139 ~NMethodMarkingScope() {
1140 nmethod::oops_do_marking_epilogue();
1141 }
1142 };
1143
1144 #endif // SHARE_CODE_NMETHOD_HPP