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