1 /*
  2  * Copyright (c) 1997, 2021, 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/compiledMethod.hpp"
 29 
 30 class DepChange;
 31 class DirectiveSet;
 32 class DebugInformationRecorder;
 33 class JvmtiThreadState;
 34 
 35 // nmethods (native methods) are the compiled code versions of Java methods.
 36 //
 37 // An nmethod contains:
 38 //  - header                 (the nmethod structure)
 39 //  [Relocation]
 40 //  - relocation information
 41 //  - constant part          (doubles, longs and floats used in nmethod)
 42 //  - oop table
 43 //  [Code]
 44 //  - code body
 45 //  - exception handler
 46 //  - stub code
 47 //  [Debugging information]
 48 //  - oop array
 49 //  - data array
 50 //  - pcs
 51 //  [Exception handler table]
 52 //  - handler entry point array
 53 //  [Implicit Null Pointer exception table]
 54 //  - implicit null table array
 55 //  [Speculations]
 56 //  - encoded speculations array
 57 //  [JVMCINMethodData]
 58 //  - meta data for JVMCI compiled nmethod
 59 
 60 #if INCLUDE_JVMCI
 61 class FailedSpeculation;
 62 class JVMCINMethodData;
 63 #endif
 64 
 65 class nmethod : public CompiledMethod {
 66   friend class VMStructs;
 67   friend class JVMCIVMStructs;
 68   friend class NMethodSweeper;
 69   friend class CodeCache;  // scavengable oops
 70   friend class JVMCINMethodData;
 71 
 72  private:
 73   // Shared fields for all nmethod's
 74   int       _entry_bci;        // != InvocationEntryBci if this nmethod is an on-stack replacement method
 75 
 76   // To support simple linked-list chaining of nmethods:
 77   nmethod*  _osr_link;         // from InstanceKlass::osr_nmethods_head
 78 
 79   // STW two-phase nmethod root processing helpers.
 80   //
 81   // When determining liveness of a given nmethod to do code cache unloading,
 82   // some collectors need to do different things depending on whether the nmethods
 83   // need to absolutely be kept alive during root processing; "strong"ly reachable
 84   // nmethods are known to be kept alive at root processing, but the liveness of
 85   // "weak"ly reachable ones is to be determined later.
 86   //
 87   // We want to allow strong and weak processing of nmethods by different threads
 88   // at the same time without heavy synchronization. Additional constraints are
 89   // to make sure that every nmethod is processed a minimal amount of time, and
 90   // nmethods themselves are always iterated at most once at a particular time.
 91   //
 92   // Note that strong processing work must be a superset of weak processing work
 93   // for this code to work.
 94   //
 95   // We store state and claim information in the _oops_do_mark_link member, using
 96   // the two LSBs for the state and the remaining upper bits for linking together
 97   // nmethods that were already visited.
 98   // The last element is self-looped, i.e. points to itself to avoid some special
 99   // "end-of-list" sentinel value.
100   //
101   // _oops_do_mark_link special values:
102   //
103   //   _oops_do_mark_link == NULL: the nmethod has not been visited at all yet, i.e.
104   //      is Unclaimed.
105   //
106   // For other values, its lowest two bits indicate the following states of the nmethod:
107   //
108   //   weak_request (WR): the nmethod has been claimed by a thread for weak processing
109   //   weak_done (WD): weak processing has been completed for this nmethod.
110   //   strong_request (SR): the nmethod has been found to need strong processing while
111   //       being weak processed.
112   //   strong_done (SD): strong processing has been completed for this nmethod .
113   //
114   // The following shows the _only_ possible progressions of the _oops_do_mark_link
115   // pointer.
116   //
117   // Given
118   //   N as the nmethod
119   //   X the current next value of _oops_do_mark_link
120   //
121   // Unclaimed (C)-> N|WR (C)-> X|WD: the nmethod has been processed weakly by
122   //   a single thread.
123   // Unclaimed (C)-> N|WR (C)-> X|WD (O)-> X|SD: after weak processing has been
124   //   completed (as above) another thread found that the nmethod needs strong
125   //   processing after all.
126   // Unclaimed (C)-> N|WR (O)-> N|SR (C)-> X|SD: during weak processing another
127   //   thread finds that the nmethod needs strong processing, marks it as such and
128   //   terminates. The original thread completes strong processing.
129   // Unclaimed (C)-> N|SD (C)-> X|SD: the nmethod has been processed strongly from
130   //   the beginning by a single thread.
131   //
132   // "|" describes the concatentation of bits in _oops_do_mark_link.
133   //
134   // The diagram also describes the threads responsible for changing the nmethod to
135   // the next state by marking the _transition_ with (C) and (O), which mean "current"
136   // and "other" thread respectively.
137   //
138   struct oops_do_mark_link; // Opaque data type.
139 
140   // States used for claiming nmethods during root processing.
141   static const uint claim_weak_request_tag = 0;
142   static const uint claim_weak_done_tag = 1;
143   static const uint claim_strong_request_tag = 2;
144   static const uint claim_strong_done_tag = 3;
145 
146   static oops_do_mark_link* mark_link(nmethod* nm, uint tag) {
147     assert(tag <= claim_strong_done_tag, "invalid tag %u", tag);
148     assert(is_aligned(nm, 4), "nmethod pointer must have zero lower two LSB");
149     return (oops_do_mark_link*)(((uintptr_t)nm & ~0x3) | tag);
150   }
151 
152   static uint extract_state(oops_do_mark_link* link) {
153     return (uint)((uintptr_t)link & 0x3);
154   }
155 
156   static nmethod* extract_nmethod(oops_do_mark_link* link) {
157     return (nmethod*)((uintptr_t)link & ~0x3);
158   }
159 
160   void oops_do_log_change(const char* state);
161 
162   static bool oops_do_has_weak_request(oops_do_mark_link* next) {
163     return extract_state(next) == claim_weak_request_tag;
164   }
165 
166   static bool oops_do_has_any_strong_state(oops_do_mark_link* next) {
167     return extract_state(next) >= claim_strong_request_tag;
168   }
169 
170   // Attempt Unclaimed -> N|WR transition. Returns true if successful.
171   bool oops_do_try_claim_weak_request();
172 
173   // Attempt Unclaimed -> N|SD transition. Returns the current link.
174   oops_do_mark_link* oops_do_try_claim_strong_done();
175   // Attempt N|WR -> X|WD transition. Returns NULL if successful, X otherwise.
176   nmethod* oops_do_try_add_to_list_as_weak_done();
177 
178   // Attempt X|WD -> N|SR transition. Returns the current link.
179   oops_do_mark_link* oops_do_try_add_strong_request(oops_do_mark_link* next);
180   // Attempt X|WD -> X|SD transition. Returns true if successful.
181   bool oops_do_try_claim_weak_done_as_strong_done(oops_do_mark_link* next);
182 
183   // Do the N|SD -> X|SD transition.
184   void oops_do_add_to_list_as_strong_done();
185 
186   // Sets this nmethod as strongly claimed (as part of N|SD -> X|SD and N|SR -> X|SD
187   // transitions).
188   void oops_do_set_strong_done(nmethod* old_head);
189 
190   static nmethod* volatile _oops_do_mark_nmethods;
191   oops_do_mark_link* volatile _oops_do_mark_link;
192 
193   // offsets for entry points
194   address _entry_point;                      // entry point with class check
195   address _verified_entry_point;             // entry point without class check
196   address _osr_entry_point;                  // entry point for on stack replacement
197 
198   // Offsets for different nmethod parts
199   int  _exception_offset;
200   // Offset of the unwind handler if it exists
201   int _unwind_handler_offset;
202 
203   int _consts_offset;
204   int _stub_offset;
205   int _oops_offset;                       // offset to where embedded oop table begins (inside data)
206   int _metadata_offset;                   // embedded meta data table
207   int _scopes_data_offset;
208   int _scopes_pcs_offset;
209   int _dependencies_offset;
210   int _native_invokers_offset;
211   int _handler_table_offset;
212   int _nul_chk_table_offset;
213 #if INCLUDE_JVMCI
214   int _speculations_offset;
215   int _jvmci_data_offset;
216 #endif
217   int _nmethod_end_offset;
218 
219   int code_offset() const { return (address) code_begin() - header_begin(); }
220 
221   // location in frame (offset for sp) that deopt can store the original
222   // pc during a deopt.
223   int _orig_pc_offset;
224 
225   int _compile_id;                           // which compilation made this nmethod
226   int _comp_level;                           // compilation level
227 
228   // protected by CodeCache_lock
229   bool _has_flushed_dependencies;            // Used for maintenance of dependencies (CodeCache_lock)
230 
231   // used by jvmti to track if an event has been posted for this nmethod.
232   bool _unload_reported;
233   bool _load_reported;
234 
235   // Protected by CompiledMethod_lock
236   volatile signed char _state;               // {not_installed, in_use, not_entrant, zombie, unloaded}
237 
238 #ifdef ASSERT
239   bool _oops_are_stale;  // indicates that it's no longer safe to access oops section
240 #endif
241 
242 #if INCLUDE_RTM_OPT
243   // RTM state at compile time. Used during deoptimization to decide
244   // whether to restart collecting RTM locking abort statistic again.
245   RTMState _rtm_state;
246 #endif
247 
248   // Nmethod Flushing lock. If non-zero, then the nmethod is not removed
249   // and is not made into a zombie. However, once the nmethod is made into
250   // a zombie, it will be locked one final time if CompiledMethodUnload
251   // event processing needs to be done.
252   volatile jint _lock_count;
253 
254   // not_entrant method removal. Each mark_sweep pass will update
255   // this mark to current sweep invocation count if it is seen on the
256   // stack.  An not_entrant method can be removed when there are no
257   // more activations, i.e., when the _stack_traversal_mark is less than
258   // current sweep traversal index.
259   volatile long _stack_traversal_mark;
260 
261   // The _hotness_counter indicates the hotness of a method. The higher
262   // the value the hotter the method. The hotness counter of a nmethod is
263   // set to [(ReservedCodeCacheSize / (1024 * 1024)) * 2] each time the method
264   // is active while stack scanning (do_stack_scanning()). The hotness
265   // counter is decreased (by 1) while sweeping.
266   int _hotness_counter;
267 
268   // Local state used to keep track of whether unloading is happening or not
269   volatile uint8_t _is_unloading_state;
270 
271   // These are used for compiled synchronized native methods to
272   // locate the owner and stack slot for the BasicLock. They are
273   // needed because there is no debug information for compiled native
274   // wrappers and the oop maps are insufficient to allow
275   // frame::retrieve_receiver() to work. Currently they are expected
276   // to be byte offsets from the Java stack pointer for maximum code
277   // sharing between platforms. JVMTI's GetLocalInstance() uses these
278   // offsets to find the receiver for non-static native wrapper frames.
279   ByteSize _native_receiver_sp_offset;
280   ByteSize _native_basic_lock_sp_offset;
281 
282   friend class nmethodLocker;
283 
284   // For native wrappers
285   nmethod(Method* method,
286           CompilerType type,
287           int nmethod_size,
288           int compile_id,
289           CodeOffsets* offsets,
290           CodeBuffer *code_buffer,
291           int frame_size,
292           ByteSize basic_lock_owner_sp_offset, /* synchronized natives only */
293           ByteSize basic_lock_sp_offset,       /* synchronized natives only */
294           OopMapSet* oop_maps);
295 
296   // Creation support
297   nmethod(Method* method,
298           CompilerType type,
299           int nmethod_size,
300           int compile_id,
301           int entry_bci,
302           CodeOffsets* offsets,
303           int orig_pc_offset,
304           DebugInformationRecorder *recorder,
305           Dependencies* dependencies,
306           CodeBuffer *code_buffer,
307           int frame_size,
308           OopMapSet* oop_maps,
309           ExceptionHandlerTable* handler_table,
310           ImplicitExceptionTable* nul_chk_table,
311           AbstractCompiler* compiler,
312           int comp_level,
313           const GrowableArrayView<RuntimeStub*>& native_invokers
314 #if INCLUDE_JVMCI
315           , char* speculations,
316           int speculations_len,
317           int jvmci_data_size
318 #endif
319           );
320 
321   // helper methods
322   void* operator new(size_t size, int nmethod_size, int comp_level) throw();
323 
324   const char* reloc_string_for(u_char* begin, u_char* end);
325 
326   bool try_transition(int new_state);
327 
328   // Returns true if this thread changed the state of the nmethod or
329   // false if another thread performed the transition.
330   bool make_not_entrant_or_zombie(int state);
331   bool make_entrant() { Unimplemented(); return false; }
332   void inc_decompile_count();
333 
334   // Inform external interfaces that a compiled method has been unloaded
335   void post_compiled_method_unload();
336 
337   // Initailize fields to their default values
338   void init_defaults();
339 
340   // Offsets
341   int content_offset() const                  { return content_begin() - header_begin(); }
342   int data_offset() const                     { return _data_offset; }
343 
344   address header_end() const                  { return (address)    header_begin() + header_size(); }
345 
346  public:
347   // create nmethod with entry_bci
348   static nmethod* new_nmethod(const methodHandle& method,
349                               int compile_id,
350                               int entry_bci,
351                               CodeOffsets* offsets,
352                               int orig_pc_offset,
353                               DebugInformationRecorder* recorder,
354                               Dependencies* dependencies,
355                               CodeBuffer *code_buffer,
356                               int frame_size,
357                               OopMapSet* oop_maps,
358                               ExceptionHandlerTable* handler_table,
359                               ImplicitExceptionTable* nul_chk_table,
360                               AbstractCompiler* compiler,
361                               int comp_level,
362                               const GrowableArrayView<RuntimeStub*>& native_invokers = GrowableArrayView<RuntimeStub*>::EMPTY
363 #if INCLUDE_JVMCI
364                               , char* speculations = NULL,
365                               int speculations_len = 0,
366                               int nmethod_mirror_index = -1,
367                               const char* nmethod_mirror_name = NULL,
368                               FailedSpeculation** failed_speculations = NULL
369 #endif
370   );
371 
372   // Only used for unit tests.
373   nmethod()
374     : CompiledMethod(),
375       _is_unloading_state(0),
376       _native_receiver_sp_offset(in_ByteSize(-1)),
377       _native_basic_lock_sp_offset(in_ByteSize(-1)) {}
378 
379 
380   static nmethod* new_native_nmethod(const methodHandle& method,
381                                      int compile_id,
382                                      CodeBuffer *code_buffer,
383                                      int vep_offset,
384                                      int frame_complete,
385                                      int frame_size,
386                                      ByteSize receiver_sp_offset,
387                                      ByteSize basic_lock_sp_offset,
388                                      OopMapSet* oop_maps);
389 
390   // type info
391   bool is_nmethod() const                         { return true; }
392   bool is_osr_method() const                      { return _entry_bci != InvocationEntryBci; }
393 
394   // boundaries for different parts
395   address consts_begin          () const          { return           header_begin() + _consts_offset        ; }
396   address consts_end            () const          { return           code_begin()                           ; }
397   address stub_begin            () const          { return           header_begin() + _stub_offset          ; }
398   address stub_end              () const          { return           header_begin() + _oops_offset          ; }
399   address exception_begin       () const          { return           header_begin() + _exception_offset     ; }
400   address unwind_handler_begin  () const          { return _unwind_handler_offset != -1 ? (header_begin() + _unwind_handler_offset) : NULL; }
401   oop*    oops_begin            () const          { return (oop*)   (header_begin() + _oops_offset)         ; }
402   oop*    oops_end              () const          { return (oop*)   (header_begin() + _metadata_offset)     ; }
403 
404   Metadata** metadata_begin   () const            { return (Metadata**)  (header_begin() + _metadata_offset)     ; }
405   Metadata** metadata_end     () const            { return (Metadata**)  _scopes_data_begin; }
406 
407   address scopes_data_end       () const          { return           header_begin() + _scopes_pcs_offset    ; }
408   PcDesc* scopes_pcs_begin      () const          { return (PcDesc*)(header_begin() + _scopes_pcs_offset   ); }
409   PcDesc* scopes_pcs_end        () const          { return (PcDesc*)(header_begin() + _dependencies_offset) ; }
410   address dependencies_begin    () const          { return           header_begin() + _dependencies_offset  ; }
411   address dependencies_end      () const          { return           header_begin() + _native_invokers_offset ; }
412   RuntimeStub** native_invokers_begin() const     { return (RuntimeStub**)(header_begin() + _native_invokers_offset) ; }
413   RuntimeStub** native_invokers_end  () const     { return (RuntimeStub**)(header_begin() + _handler_table_offset); }
414   address handler_table_begin   () const          { return           header_begin() + _handler_table_offset ; }
415   address handler_table_end     () const          { return           header_begin() + _nul_chk_table_offset ; }
416   address nul_chk_table_begin   () const          { return           header_begin() + _nul_chk_table_offset ; }
417 #if INCLUDE_JVMCI
418   address nul_chk_table_end     () const          { return           header_begin() + _speculations_offset  ; }
419   address speculations_begin    () const          { return           header_begin() + _speculations_offset  ; }
420   address speculations_end      () const          { return           header_begin() + _jvmci_data_offset   ; }
421   address jvmci_data_begin      () const          { return           header_begin() + _jvmci_data_offset    ; }
422   address jvmci_data_end        () const          { return           header_begin() + _nmethod_end_offset   ; }
423 #else
424   address nul_chk_table_end     () const          { return           header_begin() + _nmethod_end_offset   ; }
425 #endif
426 
427   // Sizes
428   int oops_size         () const                  { return (address)  oops_end         () - (address)  oops_begin         (); }
429   int metadata_size     () const                  { return (address)  metadata_end     () - (address)  metadata_begin     (); }
430   int dependencies_size () const                  { return            dependencies_end () -            dependencies_begin (); }
431 #if INCLUDE_JVMCI
432   int speculations_size () const                  { return            speculations_end () -            speculations_begin (); }
433   int jvmci_data_size   () const                  { return            jvmci_data_end   () -            jvmci_data_begin   (); }
434 #endif
435 
436   int     oops_count() const { assert(oops_size() % oopSize == 0, "");  return (oops_size() / oopSize) + 1; }
437   int metadata_count() const { assert(metadata_size() % wordSize == 0, ""); return (metadata_size() / wordSize) + 1; }
438 
439   int total_size        () const;
440 
441   void dec_hotness_counter()        { _hotness_counter--; }
442   void set_hotness_counter(int val) { _hotness_counter = val; }
443   int  hotness_counter() const      { return _hotness_counter; }
444 
445   // Containment
446   bool oops_contains         (oop*    addr) const { return oops_begin         () <= addr && addr < oops_end         (); }
447   bool metadata_contains     (Metadata** addr) const   { return metadata_begin     () <= addr && addr < metadata_end     (); }
448   bool scopes_data_contains  (address addr) const { return scopes_data_begin  () <= addr && addr < scopes_data_end  (); }
449   bool scopes_pcs_contains   (PcDesc* addr) const { return scopes_pcs_begin   () <= addr && addr < scopes_pcs_end   (); }
450 
451   // entry points
452   address entry_point() const                     { return _entry_point;             } // normal entry point
453   address verified_entry_point() const            { return _verified_entry_point;    } // if klass is correct
454 
455   // flag accessing and manipulation
456   bool  is_not_installed() const                  { return _state == not_installed; }
457   bool  is_in_use() const                         { return _state <= in_use; }
458   bool  is_alive() const                          { return _state < unloaded; }
459   bool  is_not_entrant() const                    { return _state == not_entrant; }
460   bool  is_zombie() const                         { return _state == zombie; }
461   bool  is_unloaded() const                       { return _state == unloaded; }
462 
463   void clear_unloading_state();
464   virtual bool is_unloading();
465   virtual void do_unloading(bool unloading_occurred);
466 
467 #if INCLUDE_RTM_OPT
468   // rtm state accessing and manipulating
469   RTMState  rtm_state() const                     { return _rtm_state; }
470   void set_rtm_state(RTMState state)              { _rtm_state = state; }
471 #endif
472 
473   bool make_in_use() {
474     return try_transition(in_use);
475   }
476   // Make the nmethod non entrant. The nmethod will continue to be
477   // alive.  It is used when an uncommon trap happens.  Returns true
478   // if this thread changed the state of the nmethod or false if
479   // another thread performed the transition.
480   bool  make_not_entrant() {
481     assert(!method()->is_method_handle_intrinsic(), "Cannot make MH intrinsic not entrant");
482     return make_not_entrant_or_zombie(not_entrant);
483   }
484   bool  make_not_used()    { return make_not_entrant(); }
485   bool  make_zombie()      { return make_not_entrant_or_zombie(zombie); }
486 
487   int get_state() const {
488     return _state;
489   }
490 
491   void  make_unloaded();
492 
493   bool has_dependencies()                         { return dependencies_size() != 0; }
494   void print_dependencies()                       PRODUCT_RETURN;
495   void flush_dependencies(bool delete_immediately);
496   bool has_flushed_dependencies()                 { return _has_flushed_dependencies; }
497   void set_has_flushed_dependencies()             {
498     assert(!has_flushed_dependencies(), "should only happen once");
499     _has_flushed_dependencies = 1;
500   }
501 
502   int   comp_level() const                        { return _comp_level; }
503 
504   void unlink_from_method();
505 
506   // Support for oops in scopes and relocs:
507   // Note: index 0 is reserved for null.
508   oop   oop_at(int index) const;
509   oop   oop_at_phantom(int index) const; // phantom reference
510   oop*  oop_addr_at(int index) const {  // for GC
511     // relocation indexes are biased by 1 (because 0 is reserved)
512     assert(index > 0 && index <= oops_count(), "must be a valid non-zero index");
513     assert(!_oops_are_stale, "oops are stale");
514     return &oops_begin()[index - 1];
515   }
516 
517   // Support for meta data in scopes and relocs:
518   // Note: index 0 is reserved for null.
519   Metadata*     metadata_at(int index) const      { return index == 0 ? NULL: *metadata_addr_at(index); }
520   Metadata**  metadata_addr_at(int index) const {  // for GC
521     // relocation indexes are biased by 1 (because 0 is reserved)
522     assert(index > 0 && index <= metadata_count(), "must be a valid non-zero index");
523     return &metadata_begin()[index - 1];
524   }
525 
526   void copy_values(GrowableArray<jobject>* oops);
527   void copy_values(GrowableArray<Metadata*>* metadata);
528 
529   void free_native_invokers();
530 
531   // Relocation support
532 private:
533   void fix_oop_relocations(address begin, address end, bool initialize_immediates);
534   inline void initialize_immediate_oop(oop* dest, jobject handle);
535 
536 public:
537   void fix_oop_relocations(address begin, address end) { fix_oop_relocations(begin, end, false); }
538   void fix_oop_relocations()                           { fix_oop_relocations(NULL, NULL, false); }
539 
540   // Sweeper support
541   long  stack_traversal_mark()                    { return _stack_traversal_mark; }
542   void  set_stack_traversal_mark(long l)          { _stack_traversal_mark = l; }
543 
544   // On-stack replacement support
545   int   osr_entry_bci() const                     { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
546   address  osr_entry() const                      { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
547   void  invalidate_osr_method();
548   nmethod* osr_link() const                       { return _osr_link; }
549   void     set_osr_link(nmethod *n)               { _osr_link = n; }
550 
551   // Verify calls to dead methods have been cleaned.
552   void verify_clean_inline_caches();
553 
554   // unlink and deallocate this nmethod
555   // Only NMethodSweeper class is expected to use this. NMethodSweeper is not
556   // expected to use any other private methods/data in this class.
557 
558  protected:
559   void flush();
560 
561  public:
562   // When true is returned, it is unsafe to remove this nmethod even if
563   // it is a zombie, since the VM or the ServiceThread might still be
564   // using it.
565   bool is_locked_by_vm() const                    { return _lock_count >0; }
566 
567   // See comment at definition of _last_seen_on_stack
568   void mark_as_seen_on_stack();
569   bool can_convert_to_zombie();
570 
571   // Evolution support. We make old (discarded) compiled methods point to new Method*s.
572   void set_method(Method* method) { _method = method; }
573 
574 #if INCLUDE_JVMCI
575   // Gets the JVMCI name of this nmethod.
576   const char* jvmci_name();
577 
578   // Records the pending failed speculation in the
579   // JVMCI speculation log associated with this nmethod.
580   void update_speculation(JavaThread* thread);
581 
582   // Gets the data specific to a JVMCI compiled method.
583   // This returns a non-NULL value iff this nmethod was
584   // compiled by the JVMCI compiler.
585   JVMCINMethodData* jvmci_nmethod_data() const {
586     return jvmci_data_size() == 0 ? NULL : (JVMCINMethodData*) jvmci_data_begin();
587   }
588 #endif
589 
590  public:
591   void oops_do(OopClosure* f) { oops_do(f, false); }
592   void oops_do(OopClosure* f, bool allow_dead);
593 
594   // All-in-one claiming of nmethods: returns true if the caller successfully claimed that
595   // nmethod.
596   bool oops_do_try_claim();
597 
598   // Class containing callbacks for the oops_do_process_weak/strong() methods
599   // below.
600   class OopsDoProcessor {
601   public:
602     // Process the oops of the given nmethod based on whether it has been called
603     // in a weak or strong processing context, i.e. apply either weak or strong
604     // work on it.
605     virtual void do_regular_processing(nmethod* nm) = 0;
606     // Assuming that the oops of the given nmethod has already been its weak
607     // processing applied, apply the remaining strong processing part.
608     virtual void do_remaining_strong_processing(nmethod* nm) = 0;
609   };
610 
611   // The following two methods do the work corresponding to weak/strong nmethod
612   // processing.
613   void oops_do_process_weak(OopsDoProcessor* p);
614   void oops_do_process_strong(OopsDoProcessor* p);
615 
616   static void oops_do_marking_prologue();
617   static void oops_do_marking_epilogue();
618 
619  private:
620   ScopeDesc* scope_desc_in(address begin, address end);
621 
622   address* orig_pc_addr(const frame* fr);
623 
624   // used by jvmti to track if the load and unload events has been reported
625   bool  unload_reported() const                   { return _unload_reported; }
626   void  set_unload_reported()                     { _unload_reported = true; }
627   bool  load_reported() const                     { return _load_reported; }
628   void  set_load_reported()                       { _load_reported = true; }
629 
630  public:
631   // copying of debugging information
632   void copy_scopes_pcs(PcDesc* pcs, int count);
633   void copy_scopes_data(address buffer, int size);
634 
635   // Accessor/mutator for the original pc of a frame before a frame was deopted.
636   address get_original_pc(const frame* fr) { return *orig_pc_addr(fr); }
637   void    set_original_pc(const frame* fr, address pc) { *orig_pc_addr(fr) = pc; }
638 
639   // jvmti support:
640   void post_compiled_method_load_event(JvmtiThreadState* state = NULL);
641 
642   // verify operations
643   void verify();
644   void verify_scopes();
645   void verify_interrupt_point(address interrupt_point);
646 
647   // Disassemble this nmethod with additional debug information, e.g. information about blocks.
648   void decode2(outputStream* st) const;
649   void print_constant_pool(outputStream* st);
650 
651   // Avoid hiding of parent's 'decode(outputStream*)' method.
652   void decode(outputStream* st) const { decode2(st); } // just delegate here.
653 
654   // printing support
655   void print()                          const;
656   void print(outputStream* st)          const;
657   void print_code();
658 
659 #if defined(SUPPORT_DATA_STRUCTS)
660   // print output in opt build for disassembler library
661   void print_relocations()                        PRODUCT_RETURN;
662   void print_pcs() { print_pcs_on(tty); }
663   void print_pcs_on(outputStream* st);
664   void print_scopes() { print_scopes_on(tty); }
665   void print_scopes_on(outputStream* st)          PRODUCT_RETURN;
666   void print_value_on(outputStream* st) const;
667   void print_native_invokers();
668   void print_handler_table();
669   void print_nul_chk_table();
670   void print_recorded_oop(int log_n, int index);
671   void print_recorded_oops();
672   void print_recorded_metadata();
673 
674   void print_oops(outputStream* st);     // oops from the underlying CodeBlob.
675   void print_metadata(outputStream* st); // metadata in metadata pool.
676 #else
677   // void print_pcs()                             PRODUCT_RETURN;
678   void print_pcs()                                { return; }
679 #endif
680 
681   void print_calls(outputStream* st)              PRODUCT_RETURN;
682   static void print_statistics()                  PRODUCT_RETURN;
683 
684   void maybe_print_nmethod(DirectiveSet* directive);
685   void print_nmethod(bool print_code);
686 
687   // need to re-define this from CodeBlob else the overload hides it
688   virtual void print_on(outputStream* st) const { CodeBlob::print_on(st); }
689   void print_on(outputStream* st, const char* msg) const;
690 
691   // Logging
692   void log_identity(xmlStream* log) const;
693   void log_new_nmethod() const;
694   void log_state_change() const;
695 
696   // Prints block-level comments, including nmethod specific block labels:
697   virtual void print_block_comment(outputStream* stream, address block_begin) const {
698 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
699     print_nmethod_labels(stream, block_begin);
700     CodeBlob::print_block_comment(stream, block_begin);
701 #endif
702   }
703 
704   void print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels=true) const;
705   const char* nmethod_section_label(address pos) const;
706 
707   // returns whether this nmethod has code comments.
708   bool has_code_comment(address begin, address end);
709   // Prints a comment for one native instruction (reloc info, pc desc)
710   void print_code_comment_on(outputStream* st, int column, address begin, address end);
711 
712   // Compiler task identification.  Note that all OSR methods
713   // are numbered in an independent sequence if CICountOSR is true,
714   // and native method wrappers are also numbered independently if
715   // CICountNative is true.
716   virtual int compile_id() const { return _compile_id; }
717   const char* compile_kind() const;
718 
719   // tells if any of this method's dependencies have been invalidated
720   // (this is expensive!)
721   static void check_all_dependencies(DepChange& changes);
722 
723   // tells if this compiled method is dependent on the given changes,
724   // and the changes have invalidated it
725   bool check_dependency_on(DepChange& changes);
726 
727   // Fast breakpoint support. Tells if this compiled method is
728   // dependent on the given method. Returns true if this nmethod
729   // corresponds to the given method as well.
730   virtual bool is_dependent_on_method(Method* dependee);
731 
732   // is it ok to patch at address?
733   bool is_patchable_at(address instr_address);
734 
735   // JVMTI's GetLocalInstance() support
736   ByteSize native_receiver_sp_offset() {
737     return _native_receiver_sp_offset;
738   }
739   ByteSize native_basic_lock_sp_offset() {
740     return _native_basic_lock_sp_offset;
741   }
742 
743   // support for code generation
744   static int verified_entry_point_offset()        { return offset_of(nmethod, _verified_entry_point); }
745   static int osr_entry_point_offset()             { return offset_of(nmethod, _osr_entry_point); }
746   static int state_offset()                       { return offset_of(nmethod, _state); }
747 
748   virtual void metadata_do(MetadataClosure* f);
749 
750   NativeCallWrapper* call_wrapper_at(address call) const;
751   NativeCallWrapper* call_wrapper_before(address return_pc) const;
752   address call_instruction_address(address pc) const;
753 
754   virtual CompiledStaticCall* compiledStaticCall_at(Relocation* call_site) const;
755   virtual CompiledStaticCall* compiledStaticCall_at(address addr) const;
756   virtual CompiledStaticCall* compiledStaticCall_before(address addr) const;
757 };
758 
759 // Locks an nmethod so its code will not get removed and it will not
760 // be made into a zombie, even if it is a not_entrant method. After the
761 // nmethod becomes a zombie, if CompiledMethodUnload event processing
762 // needs to be done, then lock_nmethod() is used directly to keep the
763 // generated code from being reused too early.
764 class nmethodLocker : public StackObj {
765   CompiledMethod* _nm;
766 
767  public:
768 
769   // note: nm can be NULL
770   // Only JvmtiDeferredEvent::compiled_method_unload_event()
771   // should pass zombie_ok == true.
772   static void lock_nmethod(CompiledMethod* nm, bool zombie_ok = false);
773   static void unlock_nmethod(CompiledMethod* nm); // (ditto)
774 
775   nmethodLocker(address pc); // derive nm from pc
776   nmethodLocker(nmethod *nm) { _nm = nm; lock_nmethod(_nm); }
777   nmethodLocker(CompiledMethod *nm) {
778     _nm = nm;
779     lock(_nm);
780   }
781 
782   static void lock(CompiledMethod* method, bool zombie_ok = false) {
783     if (method == NULL) return;
784     lock_nmethod(method, zombie_ok);
785   }
786 
787   static void unlock(CompiledMethod* method) {
788     if (method == NULL) return;
789     unlock_nmethod(method);
790   }
791 
792   nmethodLocker() { _nm = NULL; }
793   ~nmethodLocker() {
794     unlock(_nm);
795   }
796 
797   CompiledMethod* code() { return _nm; }
798   void set_code(CompiledMethod* new_nm, bool zombie_ok = false) {
799     unlock(_nm);   // note:  This works even if _nm==new_nm.
800     _nm = new_nm;
801     lock(_nm, zombie_ok);
802   }
803 };
804 
805 #endif // SHARE_CODE_NMETHOD_HPP