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