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 _handler_table_offset;
211   int _nul_chk_table_offset;
212 #if INCLUDE_JVMCI
213   int _speculations_offset;
214   int _jvmci_data_offset;
215 #endif
216   int _nmethod_end_offset;
217 
218   int code_offset() const { return (address) code_begin() - header_begin(); }
219 
220   // location in frame (offset for sp) that deopt can store the original
221   // pc during a deopt.
222   int _orig_pc_offset;
223 
224   int _compile_id;                           // which compilation made this nmethod
225   int _comp_level;                           // compilation level
226 
227   // protected by CodeCache_lock
228   bool _has_flushed_dependencies;            // Used for maintenance of dependencies (CodeCache_lock)
229 
230   // used by jvmti to track if an event has been posted for this nmethod.
231   bool _unload_reported;
232   bool _load_reported;
233 
234   // Protected by CompiledMethod_lock
235   volatile signed char _state;               // {not_installed, in_use, not_entrant, zombie, unloaded}
236 
237 #ifdef ASSERT
238   bool _oops_are_stale;  // indicates that it's no longer safe to access oops section
239 #endif
240 
241 #if INCLUDE_RTM_OPT
242   // RTM state at compile time. Used during deoptimization to decide
243   // whether to restart collecting RTM locking abort statistic again.
244   RTMState _rtm_state;
245 #endif
246 
247   // Nmethod Flushing lock. If non-zero, then the nmethod is not removed
248   // and is not made into a zombie. However, once the nmethod is made into
249   // a zombie, it will be locked one final time if CompiledMethodUnload
250   // event processing needs to be done.
251   volatile jint _lock_count;
252 
253   // not_entrant method removal. Each mark_sweep pass will update
254   // this mark to current sweep invocation count if it is seen on the
255   // stack.  An not_entrant method can be removed when there are no
256   // more activations, i.e., when the _stack_traversal_mark is less than
257   // current sweep traversal index.
258   volatile long _stack_traversal_mark;
259 
260   // The _hotness_counter indicates the hotness of a method. The higher
261   // the value the hotter the method. The hotness counter of a nmethod is
262   // set to [(ReservedCodeCacheSize / (1024 * 1024)) * 2] each time the method
263   // is active while stack scanning (do_stack_scanning()). The hotness
264   // counter is decreased (by 1) while sweeping.
265   int _hotness_counter;
266 
267   // Local state used to keep track of whether unloading is happening or not
268   volatile uint8_t _is_unloading_state;
269 
270   // These are used for compiled synchronized native methods to
271   // locate the owner and stack slot for the BasicLock. They are
272   // needed because there is no debug information for compiled native
273   // wrappers and the oop maps are insufficient to allow
274   // frame::retrieve_receiver() to work. Currently they are expected
275   // to be byte offsets from the Java stack pointer for maximum code
276   // sharing between platforms. JVMTI's GetLocalInstance() uses these
277   // offsets to find the receiver for non-static native wrapper frames.
278   ByteSize _native_receiver_sp_offset;
279   ByteSize _native_basic_lock_sp_offset;
280 
281   friend class nmethodLocker;
282 
283   // For native wrappers
284   nmethod(Method* method,
285           CompilerType type,
286           int nmethod_size,
287           int compile_id,
288           CodeOffsets* offsets,
289           CodeBuffer *code_buffer,
290           int frame_size,
291           ByteSize basic_lock_owner_sp_offset, /* synchronized natives only */
292           ByteSize basic_lock_sp_offset,       /* synchronized natives only */
293           OopMapSet* oop_maps);
294 
295   // Creation support
296   nmethod(Method* method,
297           CompilerType type,
298           int nmethod_size,
299           int compile_id,
300           int entry_bci,
301           CodeOffsets* offsets,
302           int orig_pc_offset,
303           DebugInformationRecorder *recorder,
304           Dependencies* dependencies,
305           CodeBuffer *code_buffer,
306           int frame_size,
307           OopMapSet* oop_maps,
308           ExceptionHandlerTable* handler_table,
309           ImplicitExceptionTable* nul_chk_table,
310           AbstractCompiler* compiler,
311           int comp_level
312 #if INCLUDE_JVMCI
313           , char* speculations,
314           int speculations_len,
315           int jvmci_data_size
316 #endif
317           );
318 
319   // helper methods
320   void* operator new(size_t size, int nmethod_size, int comp_level) throw();
321 
322   const char* reloc_string_for(u_char* begin, u_char* end);
323 
324   bool try_transition(int new_state);
325 
326   // Returns true if this thread changed the state of the nmethod or
327   // false if another thread performed the transition.
328   bool make_not_entrant_or_zombie(int state);
329   bool make_entrant() { Unimplemented(); return false; }
330   void inc_decompile_count();
331 
332   // Inform external interfaces that a compiled method has been unloaded
333   void post_compiled_method_unload();
334 
335   // Initailize fields to their default values
336   void init_defaults();
337 
338   // Offsets
339   int content_offset() const                  { return content_begin() - header_begin(); }
340   int data_offset() const                     { return _data_offset; }
341 
342   address header_end() const                  { return (address)    header_begin() + header_size(); }
343 
344  public:
345   // create nmethod with entry_bci
346   static nmethod* new_nmethod(const methodHandle& method,
347                               int compile_id,
348                               int entry_bci,
349                               CodeOffsets* offsets,
350                               int orig_pc_offset,
351                               DebugInformationRecorder* recorder,
352                               Dependencies* dependencies,
353                               CodeBuffer *code_buffer,
354                               int frame_size,
355                               OopMapSet* oop_maps,
356                               ExceptionHandlerTable* handler_table,
357                               ImplicitExceptionTable* nul_chk_table,
358                               AbstractCompiler* compiler,
359                               int comp_level
360 #if INCLUDE_JVMCI
361                               , char* speculations = NULL,
362                               int speculations_len = 0,
363                               int nmethod_mirror_index = -1,
364                               const char* nmethod_mirror_name = NULL,
365                               FailedSpeculation** failed_speculations = NULL
366 #endif
367   );
368 
369   // Only used for unit tests.
370   nmethod()
371     : CompiledMethod(),
372       _is_unloading_state(0),
373       _native_receiver_sp_offset(in_ByteSize(-1)),
374       _native_basic_lock_sp_offset(in_ByteSize(-1)) {}
375 
376 
377   static nmethod* new_native_nmethod(const methodHandle& method,
378                                      int compile_id,
379                                      CodeBuffer *code_buffer,
380                                      int vep_offset,
381                                      int frame_complete,
382                                      int frame_size,
383                                      ByteSize receiver_sp_offset,
384                                      ByteSize basic_lock_sp_offset,
385                                      OopMapSet* oop_maps);
386 
387   // type info
388   bool is_nmethod() const                         { return true; }
389   bool is_osr_method() const                      { return _entry_bci != InvocationEntryBci; }
390 
391   // boundaries for different parts
392   address consts_begin          () const          { return           header_begin() + _consts_offset        ; }
393   address consts_end            () const          { return           code_begin()                           ; }
394   address stub_begin            () const          { return           header_begin() + _stub_offset          ; }
395   address stub_end              () const          { return           header_begin() + _oops_offset          ; }
396   address exception_begin       () const          { return           header_begin() + _exception_offset     ; }
397   address unwind_handler_begin  () const          { return _unwind_handler_offset != -1 ? (header_begin() + _unwind_handler_offset) : NULL; }
398   oop*    oops_begin            () const          { return (oop*)   (header_begin() + _oops_offset)         ; }
399   oop*    oops_end              () const          { return (oop*)   (header_begin() + _metadata_offset)     ; }
400 
401   Metadata** metadata_begin   () const            { return (Metadata**)  (header_begin() + _metadata_offset)     ; }
402   Metadata** metadata_end     () const            { return (Metadata**)  _scopes_data_begin; }
403 
404   address scopes_data_end       () const          { return           header_begin() + _scopes_pcs_offset    ; }
405   PcDesc* scopes_pcs_begin      () const          { return (PcDesc*)(header_begin() + _scopes_pcs_offset   ); }
406   PcDesc* scopes_pcs_end        () const          { return (PcDesc*)(header_begin() + _dependencies_offset) ; }
407   address dependencies_begin    () const          { return           header_begin() + _dependencies_offset  ; }
408   address dependencies_end      () const          { return           header_begin() + _handler_table_offset ; }
409   address handler_table_begin   () const          { return           header_begin() + _handler_table_offset ; }
410   address handler_table_end     () const          { return           header_begin() + _nul_chk_table_offset ; }
411   address nul_chk_table_begin   () const          { return           header_begin() + _nul_chk_table_offset ; }
412 #if INCLUDE_JVMCI
413   address nul_chk_table_end     () const          { return           header_begin() + _speculations_offset  ; }
414   address speculations_begin    () const          { return           header_begin() + _speculations_offset  ; }
415   address speculations_end      () const          { return           header_begin() + _jvmci_data_offset   ; }
416   address jvmci_data_begin      () const          { return           header_begin() + _jvmci_data_offset    ; }
417   address jvmci_data_end        () const          { return           header_begin() + _nmethod_end_offset   ; }
418 #else
419   address nul_chk_table_end     () const          { return           header_begin() + _nmethod_end_offset   ; }
420 #endif
421 
422   // Sizes
423   int oops_size         () const                  { return (address)  oops_end         () - (address)  oops_begin         (); }
424   int metadata_size     () const                  { return (address)  metadata_end     () - (address)  metadata_begin     (); }
425   int dependencies_size () const                  { return            dependencies_end () -            dependencies_begin (); }
426 #if INCLUDE_JVMCI
427   int speculations_size () const                  { return            speculations_end () -            speculations_begin (); }
428   int jvmci_data_size   () const                  { return            jvmci_data_end   () -            jvmci_data_begin   (); }
429 #endif
430 
431   int     oops_count() const { assert(oops_size() % oopSize == 0, "");  return (oops_size() / oopSize) + 1; }
432   int metadata_count() const { assert(metadata_size() % wordSize == 0, ""); return (metadata_size() / wordSize) + 1; }
433 
434   int total_size        () const;
435 
436   void dec_hotness_counter()        { _hotness_counter--; }
437   void set_hotness_counter(int val) { _hotness_counter = val; }
438   int  hotness_counter() const      { return _hotness_counter; }
439 
440   // Containment
441   bool oops_contains         (oop*    addr) const { return oops_begin         () <= addr && addr < oops_end         (); }
442   bool metadata_contains     (Metadata** addr) const   { return metadata_begin     () <= addr && addr < metadata_end     (); }
443   bool scopes_data_contains  (address addr) const { return scopes_data_begin  () <= addr && addr < scopes_data_end  (); }
444   bool scopes_pcs_contains   (PcDesc* addr) const { return scopes_pcs_begin   () <= addr && addr < scopes_pcs_end   (); }
445 
446   // entry points
447   address entry_point() const                     { return _entry_point;             } // normal entry point
448   address verified_entry_point() const            { return _verified_entry_point;    } // if klass is correct
449 
450   // flag accessing and manipulation
451   bool  is_not_installed() const                  { return _state == not_installed; }
452   bool  is_in_use() const                         { return _state <= in_use; }
453   bool  is_alive() const                          { return _state < unloaded; }
454   bool  is_not_entrant() const                    { return _state == not_entrant; }
455   bool  is_zombie() const                         { return _state == zombie; }
456   bool  is_unloaded() const                       { return _state == unloaded; }
457 
458   void clear_unloading_state();
459   virtual bool is_unloading();
460   virtual void do_unloading(bool unloading_occurred);
461 
462 #if INCLUDE_RTM_OPT
463   // rtm state accessing and manipulating
464   RTMState  rtm_state() const                     { return _rtm_state; }
465   void set_rtm_state(RTMState state)              { _rtm_state = state; }
466 #endif
467 
468   bool make_in_use() {
469     return try_transition(in_use);
470   }
471   // Make the nmethod non entrant. The nmethod will continue to be
472   // alive.  It is used when an uncommon trap happens.  Returns true
473   // if this thread changed the state of the nmethod or false if
474   // another thread performed the transition.
475   bool  make_not_entrant() {
476     assert(!method()->is_method_handle_intrinsic(), "Cannot make MH intrinsic not entrant");
477     return make_not_entrant_or_zombie(not_entrant);
478   }
479   bool  make_not_used()    { return make_not_entrant(); }
480   bool  make_zombie()      { return make_not_entrant_or_zombie(zombie); }
481 
482   int get_state() const {
483     return _state;
484   }
485 
486   void  make_unloaded();
487 
488   bool has_dependencies()                         { return dependencies_size() != 0; }
489   void print_dependencies()                       PRODUCT_RETURN;
490   void flush_dependencies(bool delete_immediately);
491   bool has_flushed_dependencies()                 { return _has_flushed_dependencies; }
492   void set_has_flushed_dependencies()             {
493     assert(!has_flushed_dependencies(), "should only happen once");
494     _has_flushed_dependencies = 1;
495   }
496 
497   int   comp_level() const                        { return _comp_level; }
498 
499   void unlink_from_method();
500 
501   // Support for oops in scopes and relocs:
502   // Note: index 0 is reserved for null.
503   oop   oop_at(int index) const;
504   oop   oop_at_phantom(int index) const; // phantom reference
505   oop*  oop_addr_at(int index) const {  // for GC
506     // relocation indexes are biased by 1 (because 0 is reserved)
507     assert(index > 0 && index <= oops_count(), "must be a valid non-zero index");
508     assert(!_oops_are_stale, "oops are stale");
509     return &oops_begin()[index - 1];
510   }
511 
512   // Support for meta data in scopes and relocs:
513   // Note: index 0 is reserved for null.
514   Metadata*     metadata_at(int index) const      { return index == 0 ? NULL: *metadata_addr_at(index); }
515   Metadata**  metadata_addr_at(int index) const {  // for GC
516     // relocation indexes are biased by 1 (because 0 is reserved)
517     assert(index > 0 && index <= metadata_count(), "must be a valid non-zero index");
518     return &metadata_begin()[index - 1];
519   }
520 
521   void copy_values(GrowableArray<jobject>* oops);
522   void copy_values(GrowableArray<Metadata*>* metadata);
523 
524   // Relocation support
525 private:
526   void fix_oop_relocations(address begin, address end, bool initialize_immediates);
527   inline void initialize_immediate_oop(oop* dest, jobject handle);
528 
529 public:
530   void fix_oop_relocations(address begin, address end) { fix_oop_relocations(begin, end, false); }
531   void fix_oop_relocations()                           { fix_oop_relocations(NULL, NULL, false); }
532 
533   // Sweeper support
534   long  stack_traversal_mark()                    { return _stack_traversal_mark; }
535   void  set_stack_traversal_mark(long l)          { _stack_traversal_mark = l; }
536 
537   // On-stack replacement support
538   int   osr_entry_bci() const                     { assert(is_osr_method(), "wrong kind of nmethod"); return _entry_bci; }
539   address  osr_entry() const                      { assert(is_osr_method(), "wrong kind of nmethod"); return _osr_entry_point; }
540   void  invalidate_osr_method();
541   nmethod* osr_link() const                       { return _osr_link; }
542   void     set_osr_link(nmethod *n)               { _osr_link = n; }
543 
544   // Verify calls to dead methods have been cleaned.
545   void verify_clean_inline_caches();
546 
547   // unlink and deallocate this nmethod
548   // Only NMethodSweeper class is expected to use this. NMethodSweeper is not
549   // expected to use any other private methods/data in this class.
550 
551  protected:
552   void flush();
553 
554  public:
555   // When true is returned, it is unsafe to remove this nmethod even if
556   // it is a zombie, since the VM or the ServiceThread might still be
557   // using it.
558   bool is_locked_by_vm() const                    { return _lock_count >0; }
559 
560   // See comment at definition of _last_seen_on_stack
561   void mark_as_seen_on_stack();
562   bool can_convert_to_zombie();
563 
564   // Evolution support. We make old (discarded) compiled methods point to new Method*s.
565   void set_method(Method* method) { _method = method; }
566 
567 #if INCLUDE_JVMCI
568   // Gets the JVMCI name of this nmethod.
569   const char* jvmci_name();
570 
571   // Records the pending failed speculation in the
572   // JVMCI speculation log associated with this nmethod.
573   void update_speculation(JavaThread* thread);
574 
575   // Gets the data specific to a JVMCI compiled method.
576   // This returns a non-NULL value iff this nmethod was
577   // compiled by the JVMCI compiler.
578   JVMCINMethodData* jvmci_nmethod_data() const {
579     return jvmci_data_size() == 0 ? NULL : (JVMCINMethodData*) jvmci_data_begin();
580   }
581 #endif
582 
583  public:
584   void oops_do(OopClosure* f) { oops_do(f, false); }
585   void oops_do(OopClosure* f, bool allow_dead);
586 
587   // All-in-one claiming of nmethods: returns true if the caller successfully claimed that
588   // nmethod.
589   bool oops_do_try_claim();
590 
591   // Class containing callbacks for the oops_do_process_weak/strong() methods
592   // below.
593   class OopsDoProcessor {
594   public:
595     // Process the oops of the given nmethod based on whether it has been called
596     // in a weak or strong processing context, i.e. apply either weak or strong
597     // work on it.
598     virtual void do_regular_processing(nmethod* nm) = 0;
599     // Assuming that the oops of the given nmethod has already been its weak
600     // processing applied, apply the remaining strong processing part.
601     virtual void do_remaining_strong_processing(nmethod* nm) = 0;
602   };
603 
604   // The following two methods do the work corresponding to weak/strong nmethod
605   // processing.
606   void oops_do_process_weak(OopsDoProcessor* p);
607   void oops_do_process_strong(OopsDoProcessor* p);
608 
609   static void oops_do_marking_prologue();
610   static void oops_do_marking_epilogue();
611 
612  private:
613   ScopeDesc* scope_desc_in(address begin, address end);
614 
615   address* orig_pc_addr(const frame* fr);
616 
617   // used by jvmti to track if the load and unload events has been reported
618   bool  unload_reported() const                   { return _unload_reported; }
619   void  set_unload_reported()                     { _unload_reported = true; }
620   bool  load_reported() const                     { return _load_reported; }
621   void  set_load_reported()                       { _load_reported = true; }
622 
623  public:
624   // copying of debugging information
625   void copy_scopes_pcs(PcDesc* pcs, int count);
626   void copy_scopes_data(address buffer, int size);
627 
628   // Accessor/mutator for the original pc of a frame before a frame was deopted.
629   address get_original_pc(const frame* fr) { return *orig_pc_addr(fr); }
630   void    set_original_pc(const frame* fr, address pc) { *orig_pc_addr(fr) = pc; }
631 
632   // jvmti support:
633   void post_compiled_method_load_event(JvmtiThreadState* state = NULL);
634 
635   // verify operations
636   void verify();
637   void verify_scopes();
638   void verify_interrupt_point(address interrupt_point);
639 
640   // Disassemble this nmethod with additional debug information, e.g. information about blocks.
641   void decode2(outputStream* st) const;
642   void print_constant_pool(outputStream* st);
643 
644   // Avoid hiding of parent's 'decode(outputStream*)' method.
645   void decode(outputStream* st) const { decode2(st); } // just delegate here.
646 
647   // printing support
648   void print()                          const;
649   void print(outputStream* st)          const;
650   void print_code();
651 
652 #if defined(SUPPORT_DATA_STRUCTS)
653   // print output in opt build for disassembler library
654   void print_relocations()                        PRODUCT_RETURN;
655   void print_pcs() { print_pcs_on(tty); }
656   void print_pcs_on(outputStream* st);
657   void print_scopes() { print_scopes_on(tty); }
658   void print_scopes_on(outputStream* st)          PRODUCT_RETURN;
659   void print_value_on(outputStream* st) const;
660   void print_handler_table();
661   void print_nul_chk_table();
662   void print_recorded_oop(int log_n, int index);
663   void print_recorded_oops();
664   void print_recorded_metadata();
665 
666   void print_oops(outputStream* st);     // oops from the underlying CodeBlob.
667   void print_metadata(outputStream* st); // metadata in metadata pool.
668 #else
669   // void print_pcs()                             PRODUCT_RETURN;
670   void print_pcs()                                { return; }
671 #endif
672 
673   void print_calls(outputStream* st)              PRODUCT_RETURN;
674   static void print_statistics()                  PRODUCT_RETURN;
675 
676   void maybe_print_nmethod(DirectiveSet* directive);
677   void print_nmethod(bool print_code);
678 
679   // need to re-define this from CodeBlob else the overload hides it
680   virtual void print_on(outputStream* st) const { CodeBlob::print_on(st); }
681   void print_on(outputStream* st, const char* msg) const;
682 
683   // Logging
684   void log_identity(xmlStream* log) const;
685   void log_new_nmethod() const;
686   void log_state_change() const;
687 
688   // Prints block-level comments, including nmethod specific block labels:
689   virtual void print_block_comment(outputStream* stream, address block_begin) const {
690 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
691     print_nmethod_labels(stream, block_begin);
692     CodeBlob::print_block_comment(stream, block_begin);
693 #endif
694   }
695 
696   void print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels=true) const;
697   const char* nmethod_section_label(address pos) const;
698 
699   // returns whether this nmethod has code comments.
700   bool has_code_comment(address begin, address end);
701   // Prints a comment for one native instruction (reloc info, pc desc)
702   void print_code_comment_on(outputStream* st, int column, address begin, address end);
703 
704   // Compiler task identification.  Note that all OSR methods
705   // are numbered in an independent sequence if CICountOSR is true,
706   // and native method wrappers are also numbered independently if
707   // CICountNative is true.
708   virtual int compile_id() const { return _compile_id; }
709   const char* compile_kind() const;
710 
711   // tells if any of this method's dependencies have been invalidated
712   // (this is expensive!)
713   static void check_all_dependencies(DepChange& changes);
714 
715   // tells if this compiled method is dependent on the given changes,
716   // and the changes have invalidated it
717   bool check_dependency_on(DepChange& changes);
718 
719   // Fast breakpoint support. Tells if this compiled method is
720   // dependent on the given method. Returns true if this nmethod
721   // corresponds to the given method as well.
722   virtual bool is_dependent_on_method(Method* dependee);
723 
724   // is it ok to patch at address?
725   bool is_patchable_at(address instr_address);
726 
727   // JVMTI's GetLocalInstance() support
728   ByteSize native_receiver_sp_offset() {
729     return _native_receiver_sp_offset;
730   }
731   ByteSize native_basic_lock_sp_offset() {
732     return _native_basic_lock_sp_offset;
733   }
734 
735   // support for code generation
736   static int verified_entry_point_offset()        { return offset_of(nmethod, _verified_entry_point); }
737   static int osr_entry_point_offset()             { return offset_of(nmethod, _osr_entry_point); }
738   static int state_offset()                       { return offset_of(nmethod, _state); }
739 
740   virtual void metadata_do(MetadataClosure* f);
741 
742   NativeCallWrapper* call_wrapper_at(address call) const;
743   NativeCallWrapper* call_wrapper_before(address return_pc) const;
744   address call_instruction_address(address pc) const;
745 
746   virtual CompiledStaticCall* compiledStaticCall_at(Relocation* call_site) const;
747   virtual CompiledStaticCall* compiledStaticCall_at(address addr) const;
748   virtual CompiledStaticCall* compiledStaticCall_before(address addr) const;
749 };
750 
751 // Locks an nmethod so its code will not get removed and it will not
752 // be made into a zombie, even if it is a not_entrant method. After the
753 // nmethod becomes a zombie, if CompiledMethodUnload event processing
754 // needs to be done, then lock_nmethod() is used directly to keep the
755 // generated code from being reused too early.
756 class nmethodLocker : public StackObj {
757   CompiledMethod* _nm;
758 
759  public:
760 
761   // note: nm can be NULL
762   // Only JvmtiDeferredEvent::compiled_method_unload_event()
763   // should pass zombie_ok == true.
764   static void lock_nmethod(CompiledMethod* nm, bool zombie_ok = false);
765   static void unlock_nmethod(CompiledMethod* nm); // (ditto)
766 
767   nmethodLocker(address pc); // derive nm from pc
768   nmethodLocker(nmethod *nm) { _nm = nm; lock_nmethod(_nm); }
769   nmethodLocker(CompiledMethod *nm) {
770     _nm = nm;
771     lock(_nm);
772   }
773 
774   static void lock(CompiledMethod* method, bool zombie_ok = false) {
775     if (method == NULL) return;
776     lock_nmethod(method, zombie_ok);
777   }
778 
779   static void unlock(CompiledMethod* method) {
780     if (method == NULL) return;
781     unlock_nmethod(method);
782   }
783 
784   nmethodLocker() { _nm = NULL; }
785   ~nmethodLocker() {
786     unlock(_nm);
787   }
788 
789   CompiledMethod* code() { return _nm; }
790   void set_code(CompiledMethod* new_nm, bool zombie_ok = false) {
791     unlock(_nm);   // note:  This works even if _nm==new_nm.
792     _nm = new_nm;
793     lock(_nm, zombie_ok);
794   }
795 };
796 
797 #endif // SHARE_CODE_NMETHOD_HPP