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