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