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