0 /*                                                                                                                                   
1  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.                                                      
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.                                                                     
3  *                                                                                                                                   
4  * This code is free software; you can redistribute it and/or modify it                                                              
5  * under the terms of the GNU General Public License version 2 only, as                                                              
6  * published by the Free Software Foundation.                                                                                        
7  *                                                                                                                                   
8  * This code is distributed in the hope that it will be useful, but WITHOUT                                                          
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or                                                             
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License                                                             
11  * version 2 for more details (a copy is included in the LICENSE file that                                                           
12  * accompanied this code).                                                                                                           
13  *                                                                                                                                   
14  * You should have received a copy of the GNU General Public License version                                                         
15  * 2 along with this work; if not, write to the Free Software Foundation,                                                            
16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.                                                                     
17  *                                                                                                                                   
18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA                                                           
19  * or visit www.oracle.com if you need additional information or have any                                                            
20  * questions.                                                                                                                        
21  *                                                                                                                                   
22  */                                                                                                                                  
23 
24 #include "precompiled.hpp"                                                                                                           
25 #include "jvm.h"                                                                                                                     
26 #include "code/codeCache.hpp"                                                                                                        
27 #include "code/compiledIC.hpp"                                                                                                       
28 #include "code/compiledMethod.inline.hpp"                                                                                            
29 #include "code/dependencies.hpp"                                                                                                     
30 #include "code/nativeInst.hpp"                                                                                                       
31 #include "code/nmethod.hpp"                                                                                                          
32 #include "code/scopeDesc.hpp"                                                                                                        
33 #include "compiler/abstractCompiler.hpp"                                                                                             
34 #include "compiler/compileBroker.hpp"                                                                                                
35 #include "compiler/compileLog.hpp"                                                                                                   
36 #include "compiler/compilerDirectives.hpp"                                                                                           
37 #include "compiler/directivesParser.hpp"                                                                                             
38 #include "compiler/disassembler.hpp"                                                                                                 
39 #include "interpreter/bytecode.hpp"                                                                                                  
40 #include "logging/log.hpp"                                                                                                           
41 #include "logging/logStream.hpp"                                                                                                     
42 #include "memory/allocation.inline.hpp"                                                                                              
43 #include "memory/resourceArea.hpp"                                                                                                   
44 #include "oops/access.inline.hpp"                                                                                                    
45 #include "oops/method.inline.hpp"                                                                                                    
46 #include "oops/methodData.hpp"                                                                                                       
47 #include "oops/oop.inline.hpp"                                                                                                       
48 #include "prims/jvmtiImpl.hpp"                                                                                                       
49 #include "runtime/atomic.hpp"                                                                                                        
50 #include "runtime/flags/flagSetting.hpp"                                                                                             
51 #include "runtime/frame.inline.hpp"                                                                                                  
52 #include "runtime/handles.inline.hpp"                                                                                                
53 #include "runtime/jniHandles.inline.hpp"                                                                                             
54 #include "runtime/orderAccess.hpp"                                                                                                   
55 #include "runtime/os.hpp"                                                                                                            
56 #include "runtime/safepointVerifiers.hpp"                                                                                            
57 #include "runtime/sharedRuntime.hpp"                                                                                                 
58 #include "runtime/sweeper.hpp"                                                                                                       
59 #include "runtime/vmThread.hpp"                                                                                                      
60 #include "utilities/align.hpp"                                                                                                       
61 #include "utilities/dtrace.hpp"                                                                                                      
62 #include "utilities/events.hpp"                                                                                                      
63 #include "utilities/resourceHash.hpp"                                                                                                
64 #include "utilities/xmlstream.hpp"                                                                                                   
65 #if INCLUDE_JVMCI                                                                                                                    
66 #include "jvmci/jvmciJavaClasses.hpp"                                                                                                
67 #endif                                                                                                                               
68 
69 #ifdef DTRACE_ENABLED                                                                                                                
70 
71 // Only bother with this argument setup if dtrace is available                                                                       
72 
73 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \                                                          
74   {                                                                       \                                                          
75     Method* m = (method);                                                 \                                                          
76     if (m != NULL) {                                                      \                                                          
77       Symbol* klass_name = m->klass_name();                               \                                                          
78       Symbol* name = m->name();                                           \                                                          
79       Symbol* signature = m->signature();                                 \                                                          
80       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \                                                          
81         (char *) klass_name->bytes(), klass_name->utf8_length(),                   \                                                 
82         (char *) name->bytes(), name->utf8_length(),                               \                                                 
83         (char *) signature->bytes(), signature->utf8_length());                    \                                                 
84     }                                                                     \                                                          
85   }                                                                                                                                  
86 
87 #else //  ndef DTRACE_ENABLED                                                                                                        
88 
89 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                                                                           
90 
91 #endif                                                                                                                               
92 
93 //---------------------------------------------------------------------------------                                                  
94 // NMethod statistics                                                                                                                
95 // They are printed under various flags, including:                                                                                  
96 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.                                                        
97 // (In the latter two cases, they like other stats are printed to the log only.)                                                     
98 
99 #ifndef PRODUCT                                                                                                                      
100 // These variables are put into one block to reduce relocations                                                                      
101 // and make it simpler to print from the debugger.                                                                                   
102 struct java_nmethod_stats_struct {                                                                                                   
103   int nmethod_count;                                                                                                                 
104   int total_size;                                                                                                                    
105   int relocation_size;                                                                                                               
106   int consts_size;                                                                                                                   
107   int insts_size;                                                                                                                    
108   int stub_size;                                                                                                                     
109   int scopes_data_size;                                                                                                              
110   int scopes_pcs_size;                                                                                                               
111   int dependencies_size;                                                                                                             
112   int handler_table_size;                                                                                                            
113   int nul_chk_table_size;                                                                                                            
114   int oops_size;                                                                                                                     
115   int metadata_size;                                                                                                                 
116 
117   void note_nmethod(nmethod* nm) {                                                                                                   
118     nmethod_count += 1;                                                                                                              
119     total_size          += nm->size();                                                                                               
120     relocation_size     += nm->relocation_size();                                                                                    
121     consts_size         += nm->consts_size();                                                                                        
122     insts_size          += nm->insts_size();                                                                                         
123     stub_size           += nm->stub_size();                                                                                          
124     oops_size           += nm->oops_size();                                                                                          
125     metadata_size       += nm->metadata_size();                                                                                      
126     scopes_data_size    += nm->scopes_data_size();                                                                                   
127     scopes_pcs_size     += nm->scopes_pcs_size();                                                                                    
128     dependencies_size   += nm->dependencies_size();                                                                                  
129     handler_table_size  += nm->handler_table_size();                                                                                 
130     nul_chk_table_size  += nm->nul_chk_table_size();                                                                                 
131   }                                                                                                                                  
132   void print_nmethod_stats(const char* name) {                                                                                       
133     if (nmethod_count == 0)  return;                                                                                                 
134     tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);                                              
135     if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);                                                 
136     if (nmethod_count != 0)       tty->print_cr(" header         = " SIZE_FORMAT, nmethod_count * sizeof(nmethod));                  
137     if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);                                            
138     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);                                                
139     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);                                                 
140     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);                                                  
141     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);                                                  
142     if (metadata_size != 0)       tty->print_cr(" metadata       = %d", metadata_size);                                              
143     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);                                           
144     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);                                            
145     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);                                          
146     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);                                         
147     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);                                         
148   }                                                                                                                                  
149 };                                                                                                                                   
150 
151 struct native_nmethod_stats_struct {                                                                                                 
152   int native_nmethod_count;                                                                                                          
153   int native_total_size;                                                                                                             
154   int native_relocation_size;                                                                                                        
155   int native_insts_size;                                                                                                             
156   int native_oops_size;                                                                                                              
157   int native_metadata_size;                                                                                                          
158   void note_native_nmethod(nmethod* nm) {                                                                                            
159     native_nmethod_count += 1;                                                                                                       
160     native_total_size       += nm->size();                                                                                           
161     native_relocation_size  += nm->relocation_size();                                                                                
162     native_insts_size       += nm->insts_size();                                                                                     
163     native_oops_size        += nm->oops_size();                                                                                      
164     native_metadata_size    += nm->metadata_size();                                                                                  
165   }                                                                                                                                  
166   void print_native_nmethod_stats() {                                                                                                
167     if (native_nmethod_count == 0)  return;                                                                                          
168     tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);                                                       
169     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);                                      
170     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);                                 
171     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);                                      
172     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);                                       
173     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %d", native_metadata_size);                                   
174   }                                                                                                                                  
175 };                                                                                                                                   
176 
177 struct pc_nmethod_stats_struct {                                                                                                     
178   int pc_desc_resets;   // number of resets (= number of caches)                                                                     
179   int pc_desc_queries;  // queries to nmethod::find_pc_desc                                                                          
180   int pc_desc_approx;   // number of those which have approximate true                                                               
181   int pc_desc_repeats;  // number of _pc_descs[0] hits                                                                               
182   int pc_desc_hits;     // number of LRU cache hits                                                                                  
183   int pc_desc_tests;    // total number of PcDesc examinations                                                                       
184   int pc_desc_searches; // total number of quasi-binary search steps                                                                 
185   int pc_desc_adds;     // number of LUR cache insertions                                                                            
186 
187   void print_pc_stats() {                                                                                                            
188     tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",                                                      
189                   pc_desc_queries,                                                                                                   
190                   (double)(pc_desc_tests + pc_desc_searches)                                                                         
191                   / pc_desc_queries);                                                                                                
192     tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",                                                     
193                   pc_desc_resets,                                                                                                    
194                   pc_desc_queries, pc_desc_approx,                                                                                   
195                   pc_desc_repeats, pc_desc_hits,                                                                                     
196                   pc_desc_tests, pc_desc_searches, pc_desc_adds);                                                                    
197   }                                                                                                                                  
198 };                                                                                                                                   
199 
200 #ifdef COMPILER1                                                                                                                     
201 static java_nmethod_stats_struct c1_java_nmethod_stats;                                                                              
202 #endif                                                                                                                               
203 #ifdef COMPILER2                                                                                                                     
204 static java_nmethod_stats_struct c2_java_nmethod_stats;                                                                              
205 #endif                                                                                                                               
206 #if INCLUDE_JVMCI                                                                                                                    
207 static java_nmethod_stats_struct jvmci_java_nmethod_stats;                                                                           
208 #endif                                                                                                                               
209 static java_nmethod_stats_struct unknown_java_nmethod_stats;                                                                         
210 
211 static native_nmethod_stats_struct native_nmethod_stats;                                                                             
212 static pc_nmethod_stats_struct pc_nmethod_stats;                                                                                     
213 
214 static void note_java_nmethod(nmethod* nm) {                                                                                         
215 #ifdef COMPILER1                                                                                                                     
216   if (nm->is_compiled_by_c1()) {                                                                                                     
217     c1_java_nmethod_stats.note_nmethod(nm);                                                                                          
218   } else                                                                                                                             
219 #endif                                                                                                                               
220 #ifdef COMPILER2                                                                                                                     
221   if (nm->is_compiled_by_c2()) {                                                                                                     
222     c2_java_nmethod_stats.note_nmethod(nm);                                                                                          
223   } else                                                                                                                             
224 #endif                                                                                                                               
225 #if INCLUDE_JVMCI                                                                                                                    
226   if (nm->is_compiled_by_jvmci()) {                                                                                                  
227     jvmci_java_nmethod_stats.note_nmethod(nm);                                                                                       
228   } else                                                                                                                             
229 #endif                                                                                                                               
230   {                                                                                                                                  
231     unknown_java_nmethod_stats.note_nmethod(nm);                                                                                     
232   }                                                                                                                                  
233 }                                                                                                                                    
234 #endif // !PRODUCT                                                                                                                   
235 
236 //---------------------------------------------------------------------------------                                                  
237 
238 
239 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {                                                      
240   assert(pc != NULL, "Must be non null");                                                                                            
241   assert(exception.not_null(), "Must be non null");                                                                                  
242   assert(handler != NULL, "Must be non null");                                                                                       
243 
244   _count = 0;                                                                                                                        
245   _exception_type = exception->klass();                                                                                              
246   _next = NULL;                                                                                                                      
247   _purge_list_next = NULL;                                                                                                           
248 
249   add_address_and_handler(pc,handler);                                                                                               
250 }                                                                                                                                    
251 
252 
253 address ExceptionCache::match(Handle exception, address pc) {                                                                        
254   assert(pc != NULL,"Must be non null");                                                                                             
255   assert(exception.not_null(),"Must be non null");                                                                                   
256   if (exception->klass() == exception_type()) {                                                                                      
257     return (test_address(pc));                                                                                                       
258   }                                                                                                                                  
259 
260   return NULL;                                                                                                                       
261 }                                                                                                                                    
262 
263 
264 bool ExceptionCache::match_exception_with_space(Handle exception) {                                                                  
265   assert(exception.not_null(),"Must be non null");                                                                                   
266   if (exception->klass() == exception_type() && count() < cache_size) {                                                              
267     return true;                                                                                                                     
268   }                                                                                                                                  
269   return false;                                                                                                                      
270 }                                                                                                                                    
271 
272 
273 address ExceptionCache::test_address(address addr) {                                                                                 
274   int limit = count();                                                                                                               
275   for (int i = 0; i < limit; i++) {                                                                                                  
276     if (pc_at(i) == addr) {                                                                                                          
277       return handler_at(i);                                                                                                          
278     }                                                                                                                                
279   }                                                                                                                                  
280   return NULL;                                                                                                                       
281 }                                                                                                                                    
282 
283 
284 bool ExceptionCache::add_address_and_handler(address addr, address handler) {                                                        
285   if (test_address(addr) == handler) return true;                                                                                    
286 
287   int index = count();                                                                                                               
288   if (index < cache_size) {                                                                                                          
289     set_pc_at(index, addr);                                                                                                          
290     set_handler_at(index, handler);                                                                                                  
291     increment_count();                                                                                                               
292     return true;                                                                                                                     
293   }                                                                                                                                  
294   return false;                                                                                                                      
295 }                                                                                                                                    
296 
297 ExceptionCache* ExceptionCache::next() {                                                                                             
298   return Atomic::load(&_next);                                                                                                       
299 }                                                                                                                                    
300 
301 void ExceptionCache::set_next(ExceptionCache *ec) {                                                                                  
302   Atomic::store(ec, &_next);                                                                                                         
303 }                                                                                                                                    
304 
305 //-----------------------------------------------------------------------------                                                      
306 
307 
308 // Helper used by both find_pc_desc methods.                                                                                         
309 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {                                                         
310   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);                                                                                     
311   if (!approximate)                                                                                                                  
312     return pc->pc_offset() == pc_offset;                                                                                             
313   else                                                                                                                               
314     return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();                                                          
315 }                                                                                                                                    
316 
317 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {                                                                                
318   if (initial_pc_desc == NULL) {                                                                                                     
319     _pc_descs[0] = NULL; // native method; no PcDescs at all                                                                         
320     return;                                                                                                                          
321   }                                                                                                                                  
322   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);                                                                                    
323   // reset the cache by filling it with benign (non-null) values                                                                     
324   assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");                                                                      
325   for (int i = 0; i < cache_size; i++)                                                                                               
326     _pc_descs[i] = initial_pc_desc;                                                                                                  
327 }                                                                                                                                    
328 
329 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {                                                                 
330   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);                                                                                   
331   NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);                                                                   
332 
333   // Note: one might think that caching the most recently                                                                            
334   // read value separately would be a win, but one would be                                                                          
335   // wrong.  When many threads are updating it, the cache                                                                            
336   // line it's in would bounce between caches, negating                                                                              
337   // any benefit.                                                                                                                    
338 
339   // In order to prevent race conditions do not load cache elements                                                                  
340   // repeatedly, but use a local copy:                                                                                               
341   PcDesc* res;                                                                                                                       
342 
343   // Step one:  Check the most recently added value.                                                                                 
344   res = _pc_descs[0];                                                                                                                
345   if (res == NULL) return NULL;  // native method; no PcDescs at all                                                                 
346   if (match_desc(res, pc_offset, approximate)) {                                                                                     
347     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);                                                                                 
348     return res;                                                                                                                      
349   }                                                                                                                                  
350 
351   // Step two:  Check the rest of the LRU cache.                                                                                     
352   for (int i = 1; i < cache_size; ++i) {                                                                                             
353     res = _pc_descs[i];                                                                                                              
354     if (res->pc_offset() < 0) break;  // optimization: skip empty cache                                                              
355     if (match_desc(res, pc_offset, approximate)) {                                                                                   
356       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);                                                                                  
357       return res;                                                                                                                    
358     }                                                                                                                                
359   }                                                                                                                                  
360 
361   // Report failure.                                                                                                                 
362   return NULL;                                                                                                                       
363 }                                                                                                                                    
364 
365 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {                                                                                     
366   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);                                                                                      
367   // Update the LRU cache by shifting pc_desc forward.                                                                               
368   for (int i = 0; i < cache_size; i++)  {                                                                                            
369     PcDesc* next = _pc_descs[i];                                                                                                     
370     _pc_descs[i] = pc_desc;                                                                                                          
371     pc_desc = next;                                                                                                                  
372   }                                                                                                                                  
373 }                                                                                                                                    
374 
375 // adjust pcs_size so that it is a multiple of both oopSize and                                                                      
376 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple                                                                  
377 // of oopSize, then 2*sizeof(PcDesc) is)                                                                                             
378 static int adjust_pcs_size(int pcs_size) {                                                                                           
379   int nsize = align_up(pcs_size,   oopSize);                                                                                         
380   if ((nsize % sizeof(PcDesc)) != 0) {                                                                                               
381     nsize = pcs_size + sizeof(PcDesc);                                                                                               
382   }                                                                                                                                  
383   assert((nsize % oopSize) == 0, "correct alignment");                                                                               
384   return nsize;                                                                                                                      
385 }                                                                                                                                    
386 
387 
388 int nmethod::total_size() const {                                                                                                    
389   return                                                                                                                             
390     consts_size()        +                                                                                                           
391     insts_size()         +                                                                                                           
392     stub_size()          +                                                                                                           
393     scopes_data_size()   +                                                                                                           
394     scopes_pcs_size()    +                                                                                                           
395     handler_table_size() +                                                                                                           
396     nul_chk_table_size();                                                                                                            
397 }                                                                                                                                    
398 
399 address* nmethod::orig_pc_addr(const frame* fr) {                                                                                    
400   return (address*) ((address)fr->unextended_sp() + _orig_pc_offset);                                                                
401 }                                                                                                                                    
402 
403 const char* nmethod::compile_kind() const {                                                                                          
404   if (is_osr_method())     return "osr";                                                                                             
405   if (method() != NULL && is_native_method())  return "c2n";                                                                         
406   return NULL;                                                                                                                       
407 }                                                                                                                                    
408 
409 // Fill in default values for various flag fields                                                                                    
410 void nmethod::init_defaults() {                                                                                                      
411   _state                      = not_installed;                                                                                       
412   _has_flushed_dependencies   = 0;                                                                                                   
413   _lock_count                 = 0;                                                                                                   
414   _stack_traversal_mark       = 0;                                                                                                   
415   _unload_reported            = false; // jvmti state                                                                                
416   _is_far_code                = false; // nmethods are located in CodeCache                                                          
417 
418 #ifdef ASSERT                                                                                                                        
419   _oops_are_stale             = false;                                                                                               
420 #endif                                                                                                                               
421 
422   _oops_do_mark_link       = NULL;                                                                                                   
423   _jmethod_id              = NULL;                                                                                                   
424   _osr_link                = NULL;                                                                                                   
425   _scavenge_root_link      = NULL;                                                                                                   
426   _scavenge_root_state     = 0;                                                                                                      
427 #if INCLUDE_RTM_OPT                                                                                                                  
428   _rtm_state               = NoRTM;                                                                                                  
429 #endif                                                                                                                               
430 #if INCLUDE_JVMCI                                                                                                                    
431   _jvmci_installed_code   = NULL;                                                                                                    
432   _speculation_log        = NULL;                                                                                                    
433   _jvmci_installed_code_triggers_invalidation = false;                                                                               
434 #endif                                                                                                                               
435 }                                                                                                                                    
436 
437 nmethod* nmethod::new_native_nmethod(const methodHandle& method,                                                                     
438   int compile_id,                                                                                                                    
439   CodeBuffer *code_buffer,                                                                                                           
440   int vep_offset,                                                                                                                    
441   int frame_complete,                                                                                                                
442   int frame_size,                                                                                                                    
443   ByteSize basic_lock_owner_sp_offset,                                                                                               
444   ByteSize basic_lock_sp_offset,                                                                                                     
445   OopMapSet* oop_maps) {                                                                                                             
446   code_buffer->finalize_oop_references(method);                                                                                      
447   // create nmethod                                                                                                                  
448   nmethod* nm = NULL;                                                                                                                
449   {                                                                                                                                  
450     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);                                                               
451     int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));                                               
452     CodeOffsets offsets;                                                                                                             
453     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);                                                                      
454     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);                                                                  
455     nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), compiler_none, native_nmethod_size,                             
456                                             compile_id, &offsets,                                                                    
457                                             code_buffer, frame_size,                                                                 
458                                             basic_lock_owner_sp_offset,                                                              
459                                             basic_lock_sp_offset, oop_maps);                                                         
460     NOT_PRODUCT(if (nm != NULL)  native_nmethod_stats.note_native_nmethod(nm));                                                      
461   }                                                                                                                                  
462 
463   if (nm != NULL) {                                                                                                                  
464     // verify nmethod                                                                                                                
465     debug_only(nm->verify();) // might block                                                                                         
466 
467     nm->log_new_nmethod();                                                                                                           
468     nm->make_in_use();                                                                                                               
469   }                                                                                                                                  
470   return nm;                                                                                                                         
471 }                                                                                                                                    
472 
473 nmethod* nmethod::new_nmethod(const methodHandle& method,                                                                            
474   int compile_id,                                                                                                                    
475   int entry_bci,                                                                                                                     
476   CodeOffsets* offsets,                                                                                                              
477   int orig_pc_offset,                                                                                                                
478   DebugInformationRecorder* debug_info,                                                                                              
479   Dependencies* dependencies,                                                                                                        
480   CodeBuffer* code_buffer, int frame_size,                                                                                           
481   OopMapSet* oop_maps,                                                                                                               
482   ExceptionHandlerTable* handler_table,                                                                                              
483   ImplicitExceptionTable* nul_chk_table,                                                                                             
484   AbstractCompiler* compiler,                                                                                                        
485   int comp_level                                                                                                                     
486 #if INCLUDE_JVMCI                                                                                                                    
487   , jweak installed_code,                                                                                                            
488   jweak speculationLog                                                                                                               
489 #endif                                                                                                                               
490 )                                                                                                                                    
491 {                                                                                                                                    
492   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");                                                    
493   code_buffer->finalize_oop_references(method);                                                                                      
494   // create nmethod                                                                                                                  
495   nmethod* nm = NULL;                                                                                                                
496   { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);                                                               
497     int nmethod_size =                                                                                                               
498       CodeBlob::allocation_size(code_buffer, sizeof(nmethod))                                                                        
499       + adjust_pcs_size(debug_info->pcs_size())                                                                                      
500       + align_up((int)dependencies->size_in_bytes(), oopSize)                                                                        
501       + align_up(handler_table->size_in_bytes()    , oopSize)                                                                        
502       + align_up(nul_chk_table->size_in_bytes()    , oopSize)                                                                        
503       + align_up(debug_info->data_size()           , oopSize);                                                                       
504 
505     nm = new (nmethod_size, comp_level)                                                                                              
506     nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets,                                                
507             orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,                                                       
508             oop_maps,                                                                                                                
509             handler_table,                                                                                                           
510             nul_chk_table,                                                                                                           
511             compiler,                                                                                                                
512             comp_level                                                                                                               
513 #if INCLUDE_JVMCI                                                                                                                    
514             , installed_code,                                                                                                        
515             speculationLog                                                                                                           
516 #endif                                                                                                                               
517             );                                                                                                                       
518 
519     if (nm != NULL) {                                                                                                                
520       // To make dependency checking during class loading fast, record                                                               
521       // the nmethod dependencies in the classes it is dependent on.                                                                 
522       // This allows the dependency checking code to simply walk the                                                                 
523       // class hierarchy above the loaded class, checking only nmethods                                                              
524       // which are dependent on those classes.  The slow way is to                                                                   
525       // check every nmethod for dependencies which makes it linear in                                                               
526       // the number of methods compiled.  For applications with a lot                                                                
527       // classes the slow way is too slow.                                                                                           
528       for (Dependencies::DepStream deps(nm); deps.next(); ) {                                                                        
529         if (deps.type() == Dependencies::call_site_target_value) {                                                                   
530           // CallSite dependencies are managed on per-CallSite instance basis.                                                       
531           oop call_site = deps.argument_oop(0);                                                                                      
532           MethodHandles::add_dependent_nmethod(call_site, nm);                                                                       
533         } else {                                                                                                                     
534           Klass* klass = deps.context_type();                                                                                        
535           if (klass == NULL) {                                                                                                       
536             continue;  // ignore things like evol_method                                                                             
537           }                                                                                                                          
538           // record this nmethod as dependent on this klass                                                                          
539           InstanceKlass::cast(klass)->add_dependent_nmethod(nm);                                                                     
540         }                                                                                                                            
541       }                                                                                                                              
542       NOT_PRODUCT(if (nm != NULL)  note_java_nmethod(nm));                                                                           
543     }                                                                                                                                
544   }                                                                                                                                  
545   // Do verification and logging outside CodeCache_lock.                                                                             
546   if (nm != NULL) {                                                                                                                  
547     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.                                            
548     DEBUG_ONLY(nm->verify();)                                                                                                        
549     nm->log_new_nmethod();                                                                                                           
550   }                                                                                                                                  
551   return nm;                                                                                                                         
552 }                                                                                                                                    
553 
554 // For native wrappers                                                                                                               
555 nmethod::nmethod(                                                                                                                    
556   Method* method,                                                                                                                    
557   CompilerType type,                                                                                                                 
558   int nmethod_size,                                                                                                                  
559   int compile_id,                                                                                                                    
560   CodeOffsets* offsets,                                                                                                              
561   CodeBuffer* code_buffer,                                                                                                           
562   int frame_size,                                                                                                                    
563   ByteSize basic_lock_owner_sp_offset,                                                                                               
564   ByteSize basic_lock_sp_offset,                                                                                                     
565   OopMapSet* oop_maps )                                                                                                              
566   : CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Comp
567   _is_unloading_state(0),                                                                                                            
568   _native_receiver_sp_offset(basic_lock_owner_sp_offset),                                                                            
569   _native_basic_lock_sp_offset(basic_lock_sp_offset)                                                                                 
570 {                                                                                                                                    
571   {                                                                                                                                  
572     int scopes_data_offset = 0;                                                                                                      
573     int deoptimize_offset       = 0;                                                                                                 
574     int deoptimize_mh_offset    = 0;                                                                                                 
575 
576     debug_only(NoSafepointVerifier nsv;)                                                                                             
577     assert_locked_or_safepoint(CodeCache_lock);                                                                                      
578 
579     init_defaults();                                                                                                                 
580     _entry_bci               = InvocationEntryBci;                                                                                   
581     // We have no exception handler or deopt handler make the                                                                        
582     // values something that will never match a pc like the nmethod vtable entry                                                     
583     _exception_offset        = 0;                                                                                                    
584     _orig_pc_offset          = 0;                                                                                                    
585 
586     _consts_offset           = data_offset();                                                                                        
587     _stub_offset             = data_offset();                                                                                        
588     _oops_offset             = data_offset();                                                                                        
589     _metadata_offset         = _oops_offset         + align_up(code_buffer->total_oop_size(), oopSize);                              
590     scopes_data_offset       = _metadata_offset     + align_up(code_buffer->total_metadata_size(), wordSize);                        
591     _scopes_pcs_offset       = scopes_data_offset;                                                                                   
592     _dependencies_offset     = _scopes_pcs_offset;                                                                                   
593     _handler_table_offset    = _dependencies_offset;                                                                                 
594     _nul_chk_table_offset    = _handler_table_offset;                                                                                
595     _nmethod_end_offset      = _nul_chk_table_offset;                                                                                
596     _compile_id              = compile_id;                                                                                           
597     _comp_level              = CompLevel_none;                                                                                       
598     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);                                           
599     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);                                  
600     _osr_entry_point         = NULL;                                                                                                 
601     _exception_cache         = NULL;                                                                                                 
602     _pc_desc_container.reset_to(NULL);                                                                                               
603     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();                                                          
604 
605     _scopes_data_begin = (address) this + scopes_data_offset;                                                                        
606     _deopt_handler_begin = (address) this + deoptimize_offset;                                                                       
607     _deopt_mh_handler_begin = (address) this + deoptimize_mh_offset;                                                                 
608 
609     code_buffer->copy_code_and_locs_to(this);                                                                                        
610     code_buffer->copy_values_to(this);                                                                                               
611 
612     clear_unloading_state();                                                                                                         
613     if (ScavengeRootsInCode) {                                                                                                       
614       Universe::heap()->register_nmethod(this);                                                                                      
615     }                                                                                                                                
616     debug_only(Universe::heap()->verify_nmethod(this));                                                                              
617     CodeCache::commit(this);                                                                                                         
618   }                                                                                                                                  
619 
620   if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {                                              
621     ttyLocker ttyl;  // keep the following output all in one block                                                                   
622     // This output goes directly to the tty, not the compiler log.                                                                   
623     // To enable tools to match it up with the compilation activity,                                                                 
624     // be sure to tag this tty output with the compile ID.                                                                           
625     if (xtty != NULL) {                                                                                                              
626       xtty->begin_head("print_native_nmethod");                                                                                      
627       xtty->method(_method);                                                                                                         
628       xtty->stamp();                                                                                                                 
629       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);                                                               
630     }                                                                                                                                
631     // print the header part first                                                                                                   
632     print();                                                                                                                         
633     // then print the requested information                                                                                          
634     if (PrintNativeNMethods) {                                                                                                       
635       print_code();                                                                                                                  
636       if (oop_maps != NULL) {                                                                                                        
637         oop_maps->print();                                                                                                           
638       }                                                                                                                              
639     }                                                                                                                                
640     if (PrintRelocations) {                                                                                                          
641       print_relocations();                                                                                                           
642     }                                                                                                                                
643     if (xtty != NULL) {                                                                                                              
644       xtty->tail("print_native_nmethod");                                                                                            
645     }                                                                                                                                
646   }                                                                                                                                  
647 }                                                                                                                                    
648 
649 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {                                                
650   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));                                               
651 }                                                                                                                                    
652 
653 nmethod::nmethod(                                                                                                                    
654   Method* method,                                                                                                                    
655   CompilerType type,                                                                                                                 
656   int nmethod_size,                                                                                                                  
657   int compile_id,                                                                                                                    
658   int entry_bci,                                                                                                                     
659   CodeOffsets* offsets,                                                                                                              
660   int orig_pc_offset,                                                                                                                
661   DebugInformationRecorder* debug_info,                                                                                              
662   Dependencies* dependencies,                                                                                                        
663   CodeBuffer *code_buffer,                                                                                                           
664   int frame_size,                                                                                                                    
665   OopMapSet* oop_maps,                                                                                                               
666   ExceptionHandlerTable* handler_table,                                                                                              
667   ImplicitExceptionTable* nul_chk_table,                                                                                             
668   AbstractCompiler* compiler,                                                                                                        
669   int comp_level                                                                                                                     
670 #if INCLUDE_JVMCI                                                                                                                    
671   , jweak installed_code,                                                                                                            
672   jweak speculation_log                                                                                                              
673 #endif                                                                                                                               
674   )                                                                                                                                  
675   : CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), 
676   _is_unloading_state(0),                                                                                                            
677   _native_receiver_sp_offset(in_ByteSize(-1)),                                                                                       
678   _native_basic_lock_sp_offset(in_ByteSize(-1))                                                                                      
679 {                                                                                                                                    
680   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");                                                    
681   {                                                                                                                                  
682     debug_only(NoSafepointVerifier nsv;)                                                                                             
683     assert_locked_or_safepoint(CodeCache_lock);                                                                                      
684 
685     _deopt_handler_begin = (address) this;                                                                                           
686     _deopt_mh_handler_begin = (address) this;                                                                                        
687 
688     init_defaults();                                                                                                                 
689     _entry_bci               = entry_bci;                                                                                            
690     _compile_id              = compile_id;                                                                                           
691     _comp_level              = comp_level;                                                                                           
692     _orig_pc_offset          = orig_pc_offset;                                                                                       
693     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();                                                          
694 
695     // Section offsets                                                                                                               
696     _consts_offset           = content_offset()      + code_buffer->total_offset_of(code_buffer->consts());                          
697     _stub_offset             = content_offset()      + code_buffer->total_offset_of(code_buffer->stubs());                           
698     set_ctable_begin(header_begin() + _consts_offset);                                                                               
699 
700 #if INCLUDE_JVMCI                                                                                                                    
701     _jvmci_installed_code = installed_code;                                                                                          
702     _speculation_log = speculation_log;                                                                                              
703     oop obj = JNIHandles::resolve(installed_code);                                                                                   
704     if (obj == NULL || (obj->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(obj))) {                                     
705       _jvmci_installed_code_triggers_invalidation = false;                                                                           
706     } else {                                                                                                                         
707       _jvmci_installed_code_triggers_invalidation = true;                                                                            
708     }                                                                                                                                
709 
710     if (compiler->is_jvmci()) {                                                                                                      
711       // JVMCI might not produce any stub sections                                                                                   
712       if (offsets->value(CodeOffsets::Exceptions) != -1) {                                                                           
713         _exception_offset        = code_offset()          + offsets->value(CodeOffsets::Exceptions);                                 
714       } else {                                                                                                                       
715         _exception_offset = -1;                                                                                                      
716       }                                                                                                                              
717       if (offsets->value(CodeOffsets::Deopt) != -1) {                                                                                
718         _deopt_handler_begin       = (address) this + code_offset()          + offsets->value(CodeOffsets::Deopt);                   
719       } else {                                                                                                                       
720         _deopt_handler_begin = NULL;                                                                                                 
721       }                                                                                                                              
722       if (offsets->value(CodeOffsets::DeoptMH) != -1) {                                                                              
723         _deopt_mh_handler_begin  = (address) this + code_offset()          + offsets->value(CodeOffsets::DeoptMH);                   
724       } else {                                                                                                                       
725         _deopt_mh_handler_begin = NULL;                                                                                              
726       }                                                                                                                              
727     } else {                                                                                                                         
728 #endif                                                                                                                               
729     // Exception handler and deopt handler are in the stub section                                                                   
730     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");                                                            
731     assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");                                                            
732 
733     _exception_offset       = _stub_offset          + offsets->value(CodeOffsets::Exceptions);                                       
734     _deopt_handler_begin    = (address) this + _stub_offset          + offsets->value(CodeOffsets::Deopt);                           
735     if (offsets->value(CodeOffsets::DeoptMH) != -1) {                                                                                
736       _deopt_mh_handler_begin  = (address) this + _stub_offset          + offsets->value(CodeOffsets::DeoptMH);                      
737     } else {                                                                                                                         
738       _deopt_mh_handler_begin  = NULL;                                                                                               
739 #if INCLUDE_JVMCI                                                                                                                    
740     }                                                                                                                                
741 #endif                                                                                                                               
742     }                                                                                                                                
743     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {                                                                          
744       _unwind_handler_offset = code_offset()         + offsets->value(CodeOffsets::UnwindHandler);                                   
745     } else {                                                                                                                         
746       _unwind_handler_offset = -1;                                                                                                   
747     }                                                                                                                                
748 
749     _oops_offset             = data_offset();                                                                                        
750     _metadata_offset         = _oops_offset          + align_up(code_buffer->total_oop_size(), oopSize);                             
751     int scopes_data_offset   = _metadata_offset      + align_up(code_buffer->total_metadata_size(), wordSize);                       
752 
753     _scopes_pcs_offset       = scopes_data_offset    + align_up(debug_info->data_size       (), oopSize);                            
754     _dependencies_offset     = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());                                      
755     _handler_table_offset    = _dependencies_offset  + align_up((int)dependencies->size_in_bytes (), oopSize);                       
756     _nul_chk_table_offset    = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);                            
757     _nmethod_end_offset      = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize);                            
758     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);                                           
759     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);                                  
760     _osr_entry_point         = code_begin()          + offsets->value(CodeOffsets::OSR_Entry);                                       
761     _exception_cache         = NULL;                                                                                                 
762 
763     _scopes_data_begin = (address) this + scopes_data_offset;                                                                        
764 
765     _pc_desc_container.reset_to(scopes_pcs_begin());                                                                                 
766 
767     code_buffer->copy_code_and_locs_to(this);                                                                                        
768     // Copy contents of ScopeDescRecorder to nmethod                                                                                 
769     code_buffer->copy_values_to(this);                                                                                               
770     debug_info->copy_to(this);                                                                                                       
771     dependencies->copy_to(this);                                                                                                     
772     clear_unloading_state();                                                                                                         
773     if (ScavengeRootsInCode) {                                                                                                       
774       Universe::heap()->register_nmethod(this);                                                                                      
775     }                                                                                                                                
776     debug_only(Universe::heap()->verify_nmethod(this));                                                                              
777 
778     CodeCache::commit(this);                                                                                                         
779 
780     // Copy contents of ExceptionHandlerTable to nmethod                                                                             
781     handler_table->copy_to(this);                                                                                                    
782     nul_chk_table->copy_to(this);                                                                                                    
783 
784     // we use the information of entry points to find out if a method is                                                             
785     // static or non static                                                                                                          
786     assert(compiler->is_c2() || compiler->is_jvmci() ||                                                                              
787            _method->is_static() == (entry_point() == _verified_entry_point),                                                         
788            " entry points must be same for static methods and vice versa");                                                          
789   }                                                                                                                                  
790 }                                                                                                                                    
791 
792 // Print a short set of xml attributes to identify this nmethod.  The                                                                
793 // output should be embedded in some other element.                                                                                  
794 void nmethod::log_identity(xmlStream* log) const {                                                                                   
795   log->print(" compile_id='%d'", compile_id());                                                                                      
796   const char* nm_kind = compile_kind();                                                                                              
797   if (nm_kind != NULL)  log->print(" compile_kind='%s'", nm_kind);                                                                   
798   log->print(" compiler='%s'", compiler_name());                                                                                     
799   if (TieredCompilation) {                                                                                                           
800     log->print(" level='%d'", comp_level());                                                                                         
801   }                                                                                                                                  
802 #if INCLUDE_JVMCI                                                                                                                    
803     char buffer[O_BUFLEN];                                                                                                           
804     char* jvmci_name = jvmci_installed_code_name(buffer, O_BUFLEN);                                                                  
805     if (jvmci_name != NULL) {                                                                                                        
806       log->print(" jvmci_installed_code_name='");                                                                                    
807       log->text("%s", jvmci_name);                                                                                                   
808       log->print("'");                                                                                                               
809     }                                                                                                                                
810 #endif                                                                                                                               
811 }                                                                                                                                    
812 
813 
814 #define LOG_OFFSET(log, name)                    \                                                                                   
815   if (p2i(name##_end()) - p2i(name##_begin())) \                                                                                     
816     log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'"    , \                                                                     
817                p2i(name##_begin()) - p2i(this))                                                                                      
818 
819 
820 void nmethod::log_new_nmethod() const {                                                                                              
821   if (LogCompilation && xtty != NULL) {                                                                                              
822     ttyLocker ttyl;                                                                                                                  
823     HandleMark hm;                                                                                                                   
824     xtty->begin_elem("nmethod");                                                                                                     
825     log_identity(xtty);                                                                                                              
826     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());                                                  
827     xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));                                                                          
828 
829     LOG_OFFSET(xtty, relocation);                                                                                                    
830     LOG_OFFSET(xtty, consts);                                                                                                        
831     LOG_OFFSET(xtty, insts);                                                                                                         
832     LOG_OFFSET(xtty, stub);                                                                                                          
833     LOG_OFFSET(xtty, scopes_data);                                                                                                   
834     LOG_OFFSET(xtty, scopes_pcs);                                                                                                    
835     LOG_OFFSET(xtty, dependencies);                                                                                                  
836     LOG_OFFSET(xtty, handler_table);                                                                                                 
837     LOG_OFFSET(xtty, nul_chk_table);                                                                                                 
838     LOG_OFFSET(xtty, oops);                                                                                                          
839     LOG_OFFSET(xtty, metadata);                                                                                                      
840 
841     xtty->method(method());                                                                                                          
842     xtty->stamp();                                                                                                                   
843     xtty->end_elem();                                                                                                                
844   }                                                                                                                                  
845 }                                                                                                                                    
846 
847 #undef LOG_OFFSET                                                                                                                    
848 
849 
850 // Print out more verbose output usually for a newly created nmethod.                                                                
851 void nmethod::print_on(outputStream* st, const char* msg) const {                                                                    
852   if (st != NULL) {                                                                                                                  
853     ttyLocker ttyl;                                                                                                                  
854     if (WizardMode) {                                                                                                                
855       CompileTask::print(st, this, msg, /*short_form:*/ true);                                                                       
856       st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));                                                                               
857     } else {                                                                                                                         
858       CompileTask::print(st, this, msg, /*short_form:*/ false);                                                                      
859     }                                                                                                                                
860   }                                                                                                                                  
861 }                                                                                                                                    
862 
863 void nmethod::maybe_print_nmethod(DirectiveSet* directive) {                                                                         
864   bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;                                             
865   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {                          
866     print_nmethod(printnmethods);                                                                                                    
867   }                                                                                                                                  
868 }                                                                                                                                    
869 
870 void nmethod::print_nmethod(bool printmethod) {                                                                                      
871   ttyLocker ttyl;  // keep the following output all in one block                                                                     
872   if (xtty != NULL) {                                                                                                                
873     xtty->begin_head("print_nmethod");                                                                                               
874     xtty->stamp();                                                                                                                   
875     xtty->end_head();                                                                                                                
876   }                                                                                                                                  
877   // print the header part first                                                                                                     
878   print();                                                                                                                           
879   // then print the requested information                                                                                            
880   if (printmethod) {                                                                                                                 
881     print_code();                                                                                                                    
882     print_pcs();                                                                                                                     
883     if (oop_maps()) {                                                                                                                
884       oop_maps()->print();                                                                                                           
885     }                                                                                                                                
886   }                                                                                                                                  
887   if (printmethod || PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) {                               
888     print_scopes();                                                                                                                  
889   }                                                                                                                                  
890   if (printmethod || PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) {                           
891     print_relocations();                                                                                                             
892   }                                                                                                                                  
893   if (printmethod || PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) {                         
894     print_dependencies();                                                                                                            
895   }                                                                                                                                  
896   if (printmethod || PrintExceptionHandlers) {                                                                                       
897     print_handler_table();                                                                                                           
898     print_nul_chk_table();                                                                                                           
899   }                                                                                                                                  
900   if (printmethod) {                                                                                                                 
901     print_recorded_oops();                                                                                                           
902     print_recorded_metadata();                                                                                                       
903   }                                                                                                                                  
904   if (xtty != NULL) {                                                                                                                
905     xtty->tail("print_nmethod");                                                                                                     
906   }                                                                                                                                  
907 }                                                                                                                                    
908 
909 
910 // Promote one word from an assembly-time handle to a live embedded oop.                                                             
911 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {                                                           
912   if (handle == NULL ||                                                                                                              
913       // As a special case, IC oops are initialized to 1 or -1.                                                                      
914       handle == (jobject) Universe::non_oop_word()) {                                                                                
915     (*dest) = (oop) handle;                                                                                                          
916   } else {                                                                                                                           
917     (*dest) = JNIHandles::resolve_non_null(handle);                                                                                  
918   }                                                                                                                                  
919 }                                                                                                                                    
920 
921 
922 // Have to have the same name because it's called by a template                                                                      
923 void nmethod::copy_values(GrowableArray<jobject>* array) {                                                                           
924   int length = array->length();                                                                                                      
925   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");                                                
926   oop* dest = oops_begin();                                                                                                          
927   for (int index = 0 ; index < length; index++) {                                                                                    
928     initialize_immediate_oop(&dest[index], array->at(index));                                                                        
929   }                                                                                                                                  
930 
931   // Now we can fix up all the oops in the code.  We need to do this                                                                 
932   // in the code because the assembler uses jobjects as placeholders.                                                                
933   // The code and relocations have already been initialized by the                                                                   
934   // CodeBlob constructor, so it is valid even at this early point to                                                                
935   // iterate over relocations and patch the code.                                                                                    
936   fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);                                                                  
937 }                                                                                                                                    
938 
939 void nmethod::copy_values(GrowableArray<Metadata*>* array) {                                                                         
940   int length = array->length();                                                                                                      
941   assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");                                             
942   Metadata** dest = metadata_begin();                                                                                                
943   for (int index = 0 ; index < length; index++) {                                                                                    
944     dest[index] = array->at(index);                                                                                                  
945   }                                                                                                                                  
946 }                                                                                                                                    
947 
948 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {                                          
949   // re-patch all oop-bearing instructions, just in case some oops moved                                                             
950   RelocIterator iter(this, begin, end);                                                                                              
951   while (iter.next()) {                                                                                                              
952     if (iter.type() == relocInfo::oop_type) {                                                                                        
953       oop_Relocation* reloc = iter.oop_reloc();                                                                                      
954       if (initialize_immediates && reloc->oop_is_immediate()) {                                                                      
955         oop* dest = reloc->oop_addr();                                                                                               
956         initialize_immediate_oop(dest, (jobject) *dest);                                                                             
957       }                                                                                                                              
958       // Refresh the oop-related bits of this instruction.                                                                           
959       reloc->fix_oop_relocation();                                                                                                   
960     } else if (iter.type() == relocInfo::metadata_type) {                                                                            
961       metadata_Relocation* reloc = iter.metadata_reloc();                                                                            
962       reloc->fix_metadata_relocation();                                                                                              
963     }                                                                                                                                
964   }                                                                                                                                  
965 }                                                                                                                                    
966 
967 
968 void nmethod::verify_clean_inline_caches() {                                                                                         
969   assert(CompiledICLocker::is_safe(this), "mt unsafe call");                                                                         
970 
971   ResourceMark rm;                                                                                                                   
972   RelocIterator iter(this, oops_reloc_begin());                                                                                      
973   while(iter.next()) {                                                                                                               
974     switch(iter.type()) {                                                                                                            
975       case relocInfo::virtual_call_type:                                                                                             
976       case relocInfo::opt_virtual_call_type: {                                                                                       
977         CompiledIC *ic = CompiledIC_at(&iter);                                                                                       
978         // Ok, to lookup references to zombies here                                                                                  
979         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());                                                            
980         assert(cb != NULL, "destination not in CodeBlob?");                                                                          
981         nmethod* nm = cb->as_nmethod_or_null();                                                                                      
982         if( nm != NULL ) {                                                                                                           
983           // Verify that inline caches pointing to both zombie and not_entrant methods are clean                                     
984           if (!nm->is_in_use() || (nm->method()->code() != nm)) {                                                                    
985             assert(ic->is_clean(), "IC should be clean");                                                                            
986           }                                                                                                                          
987         }                                                                                                                            
988         break;                                                                                                                       
989       }                                                                                                                              
990       case relocInfo::static_call_type: {                                                                                            
991         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());                                                               
992         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());                                                              
993         assert(cb != NULL, "destination not in CodeBlob?");                                                                          
994         nmethod* nm = cb->as_nmethod_or_null();                                                                                      
995         if( nm != NULL ) {                                                                                                           
996           // Verify that inline caches pointing to both zombie and not_entrant methods are clean                                     
997           if (!nm->is_in_use() || (nm->method()->code() != nm)) {                                                                    
998             assert(csc->is_clean(), "IC should be clean");                                                                           
999           }                                                                                                                          
1000         }                                                                                                                            
1001         break;                                                                                                                       
1002       }                                                                                                                              
1003       default:                                                                                                                       
1004         break;                                                                                                                       
1005     }                                                                                                                                
1006   }                                                                                                                                  
1007 }                                                                                                                                    
1008 
1009 // This is a private interface with the sweeper.                                                                                     
1010 void nmethod::mark_as_seen_on_stack() {                                                                                              
1011   assert(is_alive(), "Must be an alive method");                                                                                     
1012   // Set the traversal mark to ensure that the sweeper does 2                                                                        
1013   // cleaning passes before moving to zombie.                                                                                        
1014   set_stack_traversal_mark(NMethodSweeper::traversal_count());                                                                       
1015 }                                                                                                                                    
1016 
1017 // Tell if a non-entrant method can be converted to a zombie (i.e.,                                                                  
1018 // there are no activations on the stack, not in use by the VM,                                                                      
1019 // and not in use by the ServiceThread)                                                                                              
1020 bool nmethod::can_convert_to_zombie() {                                                                                              
1021   // Note that this is called when the sweeper has observed the nmethod to be                                                        
1022   // not_entrant. However, with concurrent code cache unloading, the state                                                           
1023   // might have moved on to unloaded if it is_unloading(), due to racing                                                             
1024   // concurrent GC threads.                                                                                                          
1025   assert(is_not_entrant() || is_unloading(), "must be a non-entrant method");                                                        
1026 
1027   // Since the nmethod sweeper only does partial sweep the sweeper's traversal                                                       
1028   // count can be greater than the stack traversal count before it hits the                                                          
1029   // nmethod for the second time.                                                                                                    
1030   // If an is_unloading() nmethod is still not_entrant, then it is not safe to                                                       
1031   // convert it to zombie due to GC unloading interactions. However, if it                                                           
1032   // has become unloaded, then it is okay to convert such nmethods to zombie.                                                        
1033   return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() &&                                                           
1034          !is_locked_by_vm() && (!is_unloading() || is_unloaded());                                                                   
1035 }                                                                                                                                    
1036 
1037 void nmethod::inc_decompile_count() {                                                                                                
1038   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;                                                                       
1039   // Could be gated by ProfileTraps, but do not bother...                                                                            
1040   Method* m = method();                                                                                                              
1041   if (m == NULL)  return;                                                                                                            
1042   MethodData* mdo = m->method_data();                                                                                                
1043   if (mdo == NULL)  return;                                                                                                          
1044   // There is a benign race here.  See comments in methodData.hpp.                                                                   
1045   mdo->inc_decompile_count();                                                                                                        
1046 }                                                                                                                                    
1047 
1048 void nmethod::make_unloaded() {                                                                                                      
1049   post_compiled_method_unload();                                                                                                     
1050 
1051   // This nmethod is being unloaded, make sure that dependencies                                                                     
1052   // recorded in instanceKlasses get flushed.                                                                                        
1053   // Since this work is being done during a GC, defer deleting dependencies from the                                                 
1054   // InstanceKlass.                                                                                                                  
1055   assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(),                                            
1056          "should only be called during gc");                                                                                         
1057   flush_dependencies(/*delete_immediately*/false);                                                                                   
1058 
1059   // Break cycle between nmethod & method                                                                                            
1060   LogTarget(Trace, class, unload, nmethod) lt;                                                                                       
1061   if (lt.is_enabled()) {                                                                                                             
1062     LogStream ls(lt);                                                                                                                
1063     ls.print("making nmethod " INTPTR_FORMAT                                                                                         
1064              " unloadable, Method*(" INTPTR_FORMAT                                                                                   
1065              ") ",                                                                                                                   
1066              p2i(this), p2i(_method));                                                                                               
1067      ls.cr();                                                                                                                        
1068   }                                                                                                                                  
1069   // Unlink the osr method, so we do not look this up again                                                                          
1070   if (is_osr_method()) {                                                                                                             
1071     // Invalidate the osr nmethod only once                                                                                          
1072     if (is_in_use()) {                                                                                                               
1073       invalidate_osr_method();                                                                                                       
1074     }                                                                                                                                
1075 #ifdef ASSERT                                                                                                                        
1076     if (method() != NULL) {                                                                                                          
1077       // Make sure osr nmethod is invalidated, i.e. not on the list                                                                  
1078       bool found = method()->method_holder()->remove_osr_nmethod(this);                                                              
1079       assert(!found, "osr nmethod should have been invalidated");                                                                    
1080     }                                                                                                                                
1081 #endif                                                                                                                               
1082   }                                                                                                                                  
1083 
1084   // If _method is already NULL the Method* is about to be unloaded,                                                                 
1085   // so we don't have to break the cycle. Note that it is possible to                                                                
1086   // have the Method* live here, in case we unload the nmethod because                                                               
1087   // it is pointing to some oop (other than the Method*) being unloaded.                                                             
1088   if (_method != NULL) {                                                                                                             
1089     // OSR methods point to the Method*, but the Method* does not                                                                    
1090     // point back!                                                                                                                   
1091     if (_method->code() == this) {                                                                                                   
1092       _method->clear_code(); // Break a cycle                                                                                        
1093     }                                                                                                                                
1094     _method = NULL;            // Clear the method of this dead nmethod                                                              
1095   }                                                                                                                                  
1096 
1097   // Make the class unloaded - i.e., change state and notify sweeper                                                                 
1098   assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(),                                     
1099          "must be at safepoint");                                                                                                    
1100 
1101   // Unregister must be done before the state change                                                                                 
1102   Universe::heap()->unregister_nmethod(this);                                                                                        
1103 
1104   // Log the unloading.                                                                                                              
1105   log_state_change();                                                                                                                
1106 
1107 #if INCLUDE_JVMCI                                                                                                                    
1108   // The method can only be unloaded after the pointer to the installed code                                                         
1109   // Java wrapper is no longer alive. Here we need to clear out this weak                                                            
1110   // reference to the dead object.                                                                                                   
1111   maybe_invalidate_installed_code();                                                                                                 
1112 #endif                                                                                                                               
1113 
1114   // The Method* is gone at this point                                                                                               
1115   assert(_method == NULL, "Tautology");                                                                                              
1116 
1117   set_osr_link(NULL);                                                                                                                
1118   NMethodSweeper::report_state_change(this);                                                                                         
1119 
1120   // The release is only needed for compile-time ordering, as accesses                                                               
1121   // into the nmethod after the store are not safe due to the sweeper                                                                
1122   // being allowed to free it when the store is observed, during                                                                     
1123   // concurrent nmethod unloading. Therefore, there is no need for                                                                   
1124   // acquire on the loader side.                                                                                                     
1125   OrderAccess::release_store(&_state, (signed char)unloaded);                                                                        
1126 }                                                                                                                                    
1127 
1128 void nmethod::invalidate_osr_method() {                                                                                              
1129   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");                                                                 
1130   // Remove from list of active nmethods                                                                                             
1131   if (method() != NULL) {                                                                                                            
1132     method()->method_holder()->remove_osr_nmethod(this);                                                                             
1133   }                                                                                                                                  
1134 }                                                                                                                                    
1135 
1136 void nmethod::log_state_change() const {                                                                                             
1137   if (LogCompilation) {                                                                                                              
1138     if (xtty != NULL) {                                                                                                              
1139       ttyLocker ttyl;  // keep the following output all in one block                                                                 
1140       if (_state == unloaded) {                                                                                                      
1141         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",                                                                  
1142                          os::current_thread_id());                                                                                   
1143       } else {                                                                                                                       
1144         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",                                                             
1145                          os::current_thread_id(),                                                                                    
1146                          (_state == zombie ? " zombie='1'" : ""));                                                                   
1147       }                                                                                                                              
1148       log_identity(xtty);                                                                                                            
1149       xtty->stamp();                                                                                                                 
1150       xtty->end_elem();                                                                                                              
1151     }                                                                                                                                
1152   }                                                                                                                                  
1153 
1154   const char *state_msg = _state == zombie ? "made zombie" : "made not entrant";                                                     
1155   CompileTask::print_ul(this, state_msg);                                                                                            
1156   if (PrintCompilation && _state != unloaded) {                                                                                      
1157     print_on(tty, state_msg);                                                                                                        
1158   }                                                                                                                                  
1159 }                                                                                                                                    
1160 
1161 /**                                                                                                                                  
1162  * Common functionality for both make_not_entrant and make_zombie                                                                    
1163  */                                                                                                                                  
1164 bool nmethod::make_not_entrant_or_zombie(int state) {                                                                                
1165   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");                                                  
1166   assert(!is_zombie(), "should not already be a zombie");                                                                            
1167 
1168   if (_state == state) {                                                                                                             
1169     // Avoid taking the lock if already in required state.                                                                           
1170     // This is safe from races because the state is an end-state,                                                                    
1171     // which the nmethod cannot back out of once entered.                                                                            
1172     // No need for fencing either.                                                                                                   
1173     return false;                                                                                                                    
1174   }                                                                                                                                  
1175 
1176   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.                                   
1177   nmethodLocker nml(this);                                                                                                           
1178   methodHandle the_method(method());                                                                                                 
1179   // This can be called while the system is already at a safepoint which is ok                                                       
1180   NoSafepointVerifier nsv(true, !SafepointSynchronize::is_at_safepoint());                                                           
1181 
1182   // during patching, depending on the nmethod state we must notify the GC that                                                      
1183   // code has been unloaded, unregistering it. We cannot do this right while                                                         
1184   // holding the Patching_lock because we need to use the CodeCache_lock. This                                                       
1185   // would be prone to deadlocks.                                                                                                    
1186   // This flag is used to remember whether we need to later lock and unregister.                                                     
1187   bool nmethod_needs_unregister = false;                                                                                             
1188 
1189   {                                                                                                                                  
1190     // invalidate osr nmethod before acquiring the patching lock since                                                               
1191     // they both acquire leaf locks and we don't want a deadlock.                                                                    
1192     // This logic is equivalent to the logic below for patching the                                                                  
1193     // verified entry point of regular methods. We check that the                                                                    
1194     // nmethod is in use to ensure that it is invalidated only once.                                                                 
1195     if (is_osr_method() && is_in_use()) {                                                                                            
1196       // this effectively makes the osr nmethod not entrant                                                                          
1197       invalidate_osr_method();                                                                                                       
1198     }                                                                                                                                
1199 
1200     // Enter critical section.  Does not block for safepoint.                                                                        
1201     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);                                                                
1202 
1203     if (_state == state) {                                                                                                           
1204       // another thread already performed this transition so nothing                                                                 
1205       // to do, but return false to indicate this.                                                                                   
1206       return false;                                                                                                                  
1207     }                                                                                                                                
1208 
1209     // The caller can be calling the method statically or through an inline                                                          
1210     // cache call.                                                                                                                   
1211     if (!is_osr_method() && !is_not_entrant()) {                                                                                     
1212       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),                                                        
1213                   SharedRuntime::get_handle_wrong_method_stub());                                                                    
1214     }                                                                                                                                
1215 
1216     if (is_in_use() && update_recompile_counts()) {                                                                                  
1217       // It's a true state change, so mark the method as decompiled.                                                                 
1218       // Do it only for transition from alive.                                                                                       
1219       inc_decompile_count();                                                                                                         
1220     }                                                                                                                                
1221 
1222     // If the state is becoming a zombie, signal to unregister the nmethod with                                                      
1223     // the heap.                                                                                                                     
1224     // This nmethod may have already been unloaded during a full GC.                                                                 
1225     if ((state == zombie) && !is_unloaded()) {                                                                                       
1226       nmethod_needs_unregister = true;                                                                                               
1227     }                                                                                                                                
1228 
1229     // Must happen before state change. Otherwise we have a race condition in                                                        
1230     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately                                                       
1231     // transition its state from 'not_entrant' to 'zombie' without having to wait                                                    
1232     // for stack scanning.                                                                                                           
1233     if (state == not_entrant) {                                                                                                      
1234       mark_as_seen_on_stack();                                                                                                       
1235       OrderAccess::storestore(); // _stack_traversal_mark and _state                                                                 
1236     }                                                                                                                                
1237 
1238     // Change state                                                                                                                  
1239     _state = state;                                                                                                                  
1240 
1241     // Log the transition once                                                                                                       
1242     log_state_change();                                                                                                              
1243 
1244     // Invalidate while holding the patching lock                                                                                    
1245     JVMCI_ONLY(maybe_invalidate_installed_code());                                                                                   
1246 
1247     // Remove nmethod from method.                                                                                                   
1248     // We need to check if both the _code and _from_compiled_code_entry_point                                                        
1249     // refer to this nmethod because there is a race in setting these two fields                                                     
1250     // in Method* as seen in bugid 4947125.                                                                                          
1251     // If the vep() points to the zombie nmethod, the memory for the nmethod                                                         
1252     // could be flushed and the compiler and vtable stubs could still call                                                           
1253     // through it.                                                                                                                   
1254     if (method() != NULL && (method()->code() == this ||                                                                             
1255                              method()->from_compiled_entry() == verified_entry_point())) {                                           
1256       HandleMark hm;                                                                                                                 
1257       method()->clear_code(false /* already owns Patching_lock */);                                                                  
1258     }                                                                                                                                
1259   } // leave critical region under Patching_lock                                                                                     
1260 
1261 #ifdef ASSERT                                                                                                                        
1262   if (is_osr_method() && method() != NULL) {                                                                                         
1263     // Make sure osr nmethod is invalidated, i.e. not on the list                                                                    
1264     bool found = method()->method_holder()->remove_osr_nmethod(this);                                                                
1265     assert(!found, "osr nmethod should have been invalidated");                                                                      
1266   }                                                                                                                                  
1267 #endif                                                                                                                               
1268 
1269   // When the nmethod becomes zombie it is no longer alive so the                                                                    
1270   // dependencies must be flushed.  nmethods in the not_entrant                                                                      
1271   // state will be flushed later when the transition to zombie                                                                       
1272   // happens or they get unloaded.                                                                                                   
1273   if (state == zombie) {                                                                                                             
1274     {                                                                                                                                
1275       // Flushing dependencies must be done before any possible                                                                      
1276       // safepoint can sneak in, otherwise the oops used by the                                                                      
1277       // dependency logic could have become stale.                                                                                   
1278       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);                                                             
1279       if (nmethod_needs_unregister) {                                                                                                
1280         Universe::heap()->unregister_nmethod(this);                                                                                  
1281       }                                                                                                                              
1282       flush_dependencies(/*delete_immediately*/true);                                                                                
1283     }                                                                                                                                
1284 
                                                                                                                                     
                                                                                                                                     
                                                                                                                                     
                                                                                                                                     
                                                                                                                                     
                                                                                                                                     
                                                                                                                                     
1285     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload                                                           
1286     // event and it hasn't already been reported for this nmethod then                                                               
1287     // report it now. The event may have been reported earlier if the GC                                                             
1288     // marked it for unloading). JvmtiDeferredEventQueue support means                                                               
1289     // we no longer go to a safepoint here.                                                                                          
1290     post_compiled_method_unload();                                                                                                   
1291 
1292 #ifdef ASSERT                                                                                                                        
1293     // It's no longer safe to access the oops section since zombie                                                                   
1294     // nmethods aren't scanned for GC.                                                                                               
1295     _oops_are_stale = true;                                                                                                          
1296 #endif                                                                                                                               
1297      // the Method may be reclaimed by class unloading now that the                                                                  
1298      // nmethod is in zombie state                                                                                                   
1299     set_method(NULL);                                                                                                                
1300   } else {                                                                                                                           
1301     assert(state == not_entrant, "other cases may need to be handled differently");                                                  
1302   }                                                                                                                                  
1303 
1304   if (TraceCreateZombies) {                                                                                                          
1305     ResourceMark m;                                                                                                                  
1306     tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string
1307   }                                                                                                                                  
1308 
1309   NMethodSweeper::report_state_change(this);                                                                                         
1310   return true;                                                                                                                       
1311 }                                                                                                                                    
1312 
1313 void nmethod::flush() {                                                                                                              
1314   // Note that there are no valid oops in the nmethod anymore.                                                                       
1315   assert(!is_osr_method() || is_unloaded() || is_zombie(),                                                                           
1316          "osr nmethod must be unloaded or zombie before flushing");                                                                  
1317   assert(is_zombie() || is_osr_method(), "must be a zombie method");                                                                 
1318   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");                                                                
1319   assert_locked_or_safepoint(CodeCache_lock);                                                                                        
1320 
1321   // completely deallocate this method                                                                                               
1322   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));                                                  
1323   if (PrintMethodFlushing) {                                                                                                         
1324     tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT                                            
1325                   "/Free CodeCache:" SIZE_FORMAT "Kb",                                                                               
1326                   is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(),                                      
1327                   CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);                                        
1328   }                                                                                                                                  
1329 
1330   // We need to deallocate any ExceptionCache data.                                                                                  
1331   // Note that we do not need to grab the nmethod lock for this, it                                                                  
1332   // better be thread safe if we're disposing of it!                                                                                 
1333   ExceptionCache* ec = exception_cache();                                                                                            
1334   set_exception_cache(NULL);                                                                                                         
1335   while(ec != NULL) {                                                                                                                
1336     ExceptionCache* next = ec->next();                                                                                               
1337     delete ec;                                                                                                                       
1338     ec = next;                                                                                                                       
1339   }                                                                                                                                  
1340 
1341   if (on_scavenge_root_list()) {                                                                                                     
1342     CodeCache::drop_scavenge_root_nmethod(this);                                                                                     
1343   }                                                                                                                                  
1344 
1345 #if INCLUDE_JVMCI                                                                                                                    
1346   assert(_jvmci_installed_code == NULL, "should have been nulled out when transitioned to zombie");                                  
1347   assert(_speculation_log == NULL, "should have been nulled out when transitioned to zombie");                                       
1348 #endif                                                                                                                               
1349 
1350   CodeBlob::flush();                                                                                                                 
1351   CodeCache::free(this);                                                                                                             
1352 }                                                                                                                                    
1353 
1354 oop nmethod::oop_at(int index) const {                                                                                               
1355   if (index == 0) {                                                                                                                  
1356     return NULL;                                                                                                                     
1357   }                                                                                                                                  
1358   return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index));                                                                
1359 }                                                                                                                                    
1360 
1361 //                                                                                                                                   
1362 // Notify all classes this nmethod is dependent on that it is no                                                                     
1363 // longer dependent. This should only be called in two situations.                                                                   
1364 // First, when a nmethod transitions to a zombie all dependents need                                                                 
1365 // to be clear.  Since zombification happens at a safepoint there's no                                                               
1366 // synchronization issues.  The second place is a little more tricky.                                                                
1367 // During phase 1 of mark sweep class unloading may happen and as a                                                                  
1368 // result some nmethods may get unloaded.  In this case the flushing                                                                 
1369 // of dependencies must happen during phase 1 since after GC any                                                                     
1370 // dependencies in the unloaded nmethod won't be updated, so                                                                         
1371 // traversing the dependency information in unsafe.  In that case this                                                               
1372 // function is called with a boolean argument and this function only                                                                 
1373 // notifies instanceKlasses that are reachable                                                                                       
1374 
1375 void nmethod::flush_dependencies(bool delete_immediately) {                                                                          
1376   DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();)                   
1377   assert(called_by_gc != delete_immediately,                                                                                         
1378   "delete_immediately is false if and only if we are called during GC");                                                             
1379   if (!has_flushed_dependencies()) {                                                                                                 
1380     set_has_flushed_dependencies();                                                                                                  
1381     for (Dependencies::DepStream deps(this); deps.next(); ) {                                                                        
1382       if (deps.type() == Dependencies::call_site_target_value) {                                                                     
1383         // CallSite dependencies are managed on per-CallSite instance basis.                                                         
1384         oop call_site = deps.argument_oop(0);                                                                                        
1385         if (delete_immediately) {                                                                                                    
1386           assert_locked_or_safepoint(CodeCache_lock);                                                                                
1387           MethodHandles::remove_dependent_nmethod(call_site, this);                                                                  
1388         } else {                                                                                                                     
1389           MethodHandles::clean_dependency_context(call_site);                                                                        
1390         }                                                                                                                            
1391       } else {                                                                                                                       
1392         Klass* klass = deps.context_type();                                                                                          
1393         if (klass == NULL) {                                                                                                         
1394           continue;  // ignore things like evol_method                                                                               
1395         }                                                                                                                            
1396         // During GC delete_immediately is false, and liveness                                                                       
1397         // of dependee determines class that needs to be updated.                                                                    
1398         if (delete_immediately) {                                                                                                    
1399           assert_locked_or_safepoint(CodeCache_lock);                                                                                
1400           InstanceKlass::cast(klass)->remove_dependent_nmethod(this);                                                                
1401         } else if (klass->is_loader_alive()) {                                                                                       
1402           // The GC may clean dependency contexts concurrently and in parallel.                                                      
1403           InstanceKlass::cast(klass)->clean_dependency_context();                                                                    
1404         }                                                                                                                            
1405       }                                                                                                                              
1406     }                                                                                                                                
1407   }                                                                                                                                  
1408 }                                                                                                                                    
1409 
1410 // ------------------------------------------------------------------                                                                
1411 // post_compiled_method_load_event                                                                                                   
1412 // new method for install_code() path                                                                                                
1413 // Transfer information from compilation to jvmti                                                                                    
1414 void nmethod::post_compiled_method_load_event() {                                                                                    
1415 
1416   Method* moop = method();                                                                                                           
1417   HOTSPOT_COMPILED_METHOD_LOAD(                                                                                                      
1418       (char *) moop->klass_name()->bytes(),                                                                                          
1419       moop->klass_name()->utf8_length(),                                                                                             
1420       (char *) moop->name()->bytes(),                                                                                                
1421       moop->name()->utf8_length(),                                                                                                   
1422       (char *) moop->signature()->bytes(),                                                                                           
1423       moop->signature()->utf8_length(),                                                                                              
1424       insts_begin(), insts_size());                                                                                                  
1425 
1426   if (JvmtiExport::should_post_compiled_method_load() ||                                                                             
1427       JvmtiExport::should_post_compiled_method_unload()) {                                                                           
1428     get_and_cache_jmethod_id();                                                                                                      
1429   }                                                                                                                                  
1430 
1431   if (JvmtiExport::should_post_compiled_method_load()) {                                                                             
1432     // Let the Service thread (which is a real Java thread) post the event                                                           
1433     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);                                                                 
1434     JvmtiDeferredEventQueue::enqueue(                                                                                                
1435       JvmtiDeferredEvent::compiled_method_load_event(this));                                                                         
1436   }                                                                                                                                  
1437 }                                                                                                                                    
1438 
1439 jmethodID nmethod::get_and_cache_jmethod_id() {                                                                                      
1440   if (_jmethod_id == NULL) {                                                                                                         
1441     // Cache the jmethod_id since it can no longer be looked up once the                                                             
1442     // method itself has been marked for unloading.                                                                                  
1443     _jmethod_id = method()->jmethod_id();                                                                                            
1444   }                                                                                                                                  
1445   return _jmethod_id;                                                                                                                
1446 }                                                                                                                                    
1447 
1448 void nmethod::post_compiled_method_unload() {                                                                                        
1449   if (unload_reported()) {                                                                                                           
1450     // During unloading we transition to unloaded and then to zombie                                                                 
1451     // and the unloading is reported during the first transition.                                                                    
1452     return;                                                                                                                          
1453   }                                                                                                                                  
1454 
1455   assert(_method != NULL && !is_unloaded(), "just checking");                                                                        
1456   DTRACE_METHOD_UNLOAD_PROBE(method());                                                                                              
1457 
1458   // If a JVMTI agent has enabled the CompiledMethodUnload event then                                                                
1459   // post the event. Sometime later this nmethod will be made a zombie                                                               
1460   // by the sweeper but the Method* will not be valid at that point.                                                                 
1461   // If the _jmethod_id is null then no load event was ever requested                                                                
1462   // so don't bother posting the unload.  The main reason for this is                                                                
1463   // that the jmethodID is a weak reference to the Method* so if                                                                     
1464   // it's being unloaded there's no way to look it up since the weak                                                                 
1465   // ref will have been cleared.                                                                                                     
1466   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {                                                    
1467     assert(!unload_reported(), "already unloaded");                                                                                  
1468     JvmtiDeferredEvent event =                                                                                                       
1469       JvmtiDeferredEvent::compiled_method_unload_event(this,                                                                         
1470           _jmethod_id, insts_begin());                                                                                               
1471     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);                                                                 
1472     JvmtiDeferredEventQueue::enqueue(event);                                                                                         
1473   }                                                                                                                                  
1474 
1475   // The JVMTI CompiledMethodUnload event can be enabled or disabled at                                                              
1476   // any time. As the nmethod is being unloaded now we mark it has                                                                   
1477   // having the unload event reported - this will ensure that we don't                                                               
1478   // attempt to report the event in the unlikely scenario where the                                                                  
1479   // event is enabled at the time the nmethod is made a zombie.                                                                      
1480   set_unload_reported();                                                                                                             
1481 }                                                                                                                                    
1482 
1483 // Iterate over metadata calling this function.   Used by RedefineClasses                                                            
1484 void nmethod::metadata_do(void f(Metadata*)) {                                                                                       
1485   {                                                                                                                                  
1486     // Visit all immediate references that are embedded in the instruction stream.                                                   
1487     RelocIterator iter(this, oops_reloc_begin());                                                                                    
1488     while (iter.next()) {                                                                                                            
1489       if (iter.type() == relocInfo::metadata_type ) {                                                                                
1490         metadata_Relocation* r = iter.metadata_reloc();                                                                              
1491         // In this metadata, we must only follow those metadatas directly embedded in                                                
1492         // the code.  Other metadatas (oop_index>0) are seen as part of                                                              
1493         // the metadata section below.                                                                                               
1494         assert(1 == (r->metadata_is_immediate()) +                                                                                   
1495                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),                                      
1496                "metadata must be found in exactly one place");                                                                       
1497         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {                                                             
1498           Metadata* md = r->metadata_value();                                                                                        
1499           if (md != _method) f(md);                                                                                                  
1500         }                                                                                                                            
1501       } else if (iter.type() == relocInfo::virtual_call_type) {                                                                      
1502         // Check compiledIC holders associated with this nmethod                                                                     
1503         ResourceMark rm;                                                                                                             
1504         CompiledIC *ic = CompiledIC_at(&iter);                                                                                       
1505         if (ic->is_icholder_call()) {                                                                                                
1506           CompiledICHolder* cichk = ic->cached_icholder();                                                                           
1507           f(cichk->holder_metadata());                                                                                               
1508           f(cichk->holder_klass());                                                                                                  
1509         } else {                                                                                                                     
1510           Metadata* ic_oop = ic->cached_metadata();                                                                                  
1511           if (ic_oop != NULL) {                                                                                                      
1512             f(ic_oop);                                                                                                               
1513           }                                                                                                                          
1514         }                                                                                                                            
1515       }                                                                                                                              
1516     }                                                                                                                                
1517   }                                                                                                                                  
1518 
1519   // Visit the metadata section                                                                                                      
1520   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {                                                                   
1521     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops                                                   
1522     Metadata* md = *p;                                                                                                               
1523     f(md);                                                                                                                           
1524   }                                                                                                                                  
1525 
1526   // Visit metadata not embedded in the other places.                                                                                
1527   if (_method != NULL) f(_method);                                                                                                   
1528 }                                                                                                                                    
1529 
1530 // The _is_unloading_state encodes a tuple comprising the unloading cycle                                                            
1531 // and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle.                                                            
1532 // This is the bit layout of the _is_unloading_state byte: 00000CCU                                                                  
1533 // CC refers to the cycle, which has 2 bits, and U refers to the result of                                                           
1534 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.                                                                    
1535 
1536 class IsUnloadingState: public AllStatic {                                                                                           
1537   static const uint8_t _is_unloading_mask = 1;                                                                                       
1538   static const uint8_t _is_unloading_shift = 0;                                                                                      
1539   static const uint8_t _unloading_cycle_mask = 6;                                                                                    
1540   static const uint8_t _unloading_cycle_shift = 1;                                                                                   
1541 
1542   static uint8_t set_is_unloading(uint8_t state, bool value) {                                                                       
1543     state &= ~_is_unloading_mask;                                                                                                    
1544     if (value) {                                                                                                                     
1545       state |= 1 << _is_unloading_shift;                                                                                             
1546     }                                                                                                                                
1547     assert(is_unloading(state) == value, "unexpected unloading cycle overflow");                                                     
1548     return state;                                                                                                                    
1549   }                                                                                                                                  
1550 
1551   static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {                                                                 
1552     state &= ~_unloading_cycle_mask;                                                                                                 
1553     state |= value << _unloading_cycle_shift;                                                                                        
1554     assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");                                                  
1555     return state;                                                                                                                    
1556   }                                                                                                                                  
1557 
1558 public:                                                                                                                              
1559   static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }                       
1560   static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }                
1561 
1562   static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {                                                                
1563     uint8_t state = 0;                                                                                                               
1564     state = set_is_unloading(state, is_unloading);                                                                                   
1565     state = set_unloading_cycle(state, unloading_cycle);                                                                             
1566     return state;                                                                                                                    
1567   }                                                                                                                                  
1568 };                                                                                                                                   
1569 
1570 bool nmethod::is_unloading() {                                                                                                       
1571   uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state);                                                                 
1572   bool state_is_unloading = IsUnloadingState::is_unloading(state);                                                                   
1573   uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);                                                          
1574   if (state_is_unloading) {                                                                                                          
1575     return true;                                                                                                                     
1576   }                                                                                                                                  
1577   uint8_t current_cycle = CodeCache::unloading_cycle();                                                                              
1578   if (state_unloading_cycle == current_cycle) {                                                                                      
1579     return false;                                                                                                                    
1580   }                                                                                                                                  
1581 
1582   // The IsUnloadingBehaviour is responsible for checking if there are any dead                                                      
1583   // oops in the CompiledMethod, by calling oops_do on it.                                                                           
1584   state_unloading_cycle = current_cycle;                                                                                             
1585 
1586   if (is_zombie()) {                                                                                                                 
1587     // Zombies without calculated unloading epoch are never unloading due to GC.                                                     
1588 
1589     // There are no races where a previously observed is_unloading() nmethod                                                         
1590     // suddenly becomes not is_unloading() due to here being observed as zombie.                                                     
1591 
1592     // With STW unloading, all is_alive() && is_unloading() nmethods are unlinked                                                    
1593     // and unloaded in the safepoint. That makes races where an nmethod is first                                                     
1594     // observed as is_alive() && is_unloading() and subsequently observed as                                                         
1595     // is_zombie() impossible.                                                                                                       
1596 
1597     // With concurrent unloading, all references to is_unloading() nmethods are                                                      
1598     // first unlinked (e.g. IC caches and dependency contexts). Then a global                                                        
1599     // handshake operation is performed with all JavaThreads before finally                                                          
1600     // unloading the nmethods. The sweeper never converts is_alive() && is_unloading()                                               
1601     // nmethods to zombies; it waits for them to become is_unloaded(). So before                                                     
1602     // the global handshake, it is impossible for is_unloading() nmethods to                                                         
1603     // racingly become is_zombie(). And is_unloading() is calculated for all is_alive()                                              
1604     // nmethods before taking that global handshake, meaning that it will never                                                      
1605     // be recalculated after the handshake.                                                                                          
1606 
1607     // After that global handshake, is_unloading() nmethods are only observable                                                      
1608     // to the iterators, and they will never trigger recomputation of the cached                                                     
1609     // is_unloading_state, and hence may not suffer from such races.                                                                 
1610 
1611     state_is_unloading = false;                                                                                                      
1612   } else {                                                                                                                           
1613     state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this);                                                        
1614   }                                                                                                                                  
1615 
1616   state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);                                                       
1617 
1618   RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);                                                                         
1619 
1620   return state_is_unloading;                                                                                                         
1621 }                                                                                                                                    
1622 
1623 void nmethod::clear_unloading_state() {                                                                                              
1624   uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());                                                     
1625   RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);                                                                         
1626 }                                                                                                                                    
1627 
1628 
1629 // This is called at the end of the strong tracing/marking phase of a                                                                
1630 // GC to unload an nmethod if it contains otherwise unreachable                                                                      
1631 // oops.                                                                                                                             
1632 
1633 void nmethod::do_unloading(bool unloading_occurred) {                                                                                
1634   // Make sure the oop's ready to receive visitors                                                                                   
1635   assert(!is_zombie() && !is_unloaded(),                                                                                             
1636          "should not call follow on zombie or unloaded nmethod");                                                                    
1637 
1638   if (is_unloading()) {                                                                                                              
1639     make_unloaded();                                                                                                                 
1640   } else {                                                                                                                           
1641 #if INCLUDE_JVMCI                                                                                                                    
1642     if (_jvmci_installed_code != NULL) {                                                                                             
1643       if (JNIHandles::is_global_weak_cleared(_jvmci_installed_code)) {                                                               
1644         if (_jvmci_installed_code_triggers_invalidation) {                                                                           
1645           make_not_entrant();                                                                                                        
1646         }                                                                                                                            
1647         clear_jvmci_installed_code();                                                                                                
1648       }                                                                                                                              
1649     }                                                                                                                                
1650 #endif                                                                                                                               
1651 
1652     guarantee(unload_nmethod_caches(unloading_occurred),                                                                             
1653               "Should not need transition stubs");                                                                                   
1654   }                                                                                                                                  
1655 }                                                                                                                                    
1656 
1657 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {                                                                            
1658   // make sure the oops ready to receive visitors                                                                                    
1659   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");                                                  
1660   assert(!is_unloaded(), "should not call follow on unloaded nmethod");                                                              
1661 
1662   // Prevent extra code cache walk for platforms that don't have immediate oops.                                                     
1663   if (relocInfo::mustIterateImmediateOopsInCode()) {                                                                                 
1664     RelocIterator iter(this, oops_reloc_begin());                                                                                    
1665 
1666     while (iter.next()) {                                                                                                            
1667       if (iter.type() == relocInfo::oop_type ) {                                                                                     
1668         oop_Relocation* r = iter.oop_reloc();                                                                                        
1669         // In this loop, we must only follow those oops directly embedded in                                                         
1670         // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.                                                      
1671         assert(1 == (r->oop_is_immediate()) +                                                                                        
1672                (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),                                                        
1673                "oop must be found in exactly one place");                                                                            
1674         if (r->oop_is_immediate() && r->oop_value() != NULL) {                                                                       
1675           f->do_oop(r->oop_addr());                                                                                                  
1676         }                                                                                                                            
1677       }                                                                                                                              
1678     }                                                                                                                                
1679   }                                                                                                                                  
1680 
1681   // Scopes                                                                                                                          
1682   // This includes oop constants not inlined in the code stream.                                                                     
1683   for (oop* p = oops_begin(); p < oops_end(); p++) {                                                                                 
1684     if (*p == Universe::non_oop_word())  continue;  // skip non-oops                                                                 
1685     f->do_oop(p);                                                                                                                    
1686   }                                                                                                                                  
1687 }                                                                                                                                    
1688 
1689 #define NMETHOD_SENTINEL ((nmethod*)badAddress)                                                                                      
1690 
1691 nmethod* volatile nmethod::_oops_do_mark_nmethods;                                                                                   
1692 
1693 // An nmethod is "marked" if its _mark_link is set non-null.                                                                         
1694 // Even if it is the end of the linked list, it will have a non-null link value,                                                     
1695 // as long as it is on the list.                                                                                                     
1696 // This code must be MP safe, because it is used from parallel GC passes.                                                            
1697 bool nmethod::test_set_oops_do_mark() {                                                                                              
1698   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");                                           
1699   if (_oops_do_mark_link == NULL) {                                                                                                  
1700     // Claim this nmethod for this thread to mark.                                                                                   
1701     if (Atomic::replace_if_null(NMETHOD_SENTINEL, &_oops_do_mark_link)) {                                                            
1702       // Atomically append this nmethod (now claimed) to the head of the list:                                                       
1703       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;                                                                      
1704       for (;;) {                                                                                                                     
1705         nmethod* required_mark_nmethods = observed_mark_nmethods;                                                                    
1706         _oops_do_mark_link = required_mark_nmethods;                                                                                 
1707         observed_mark_nmethods =                                                                                                     
1708           Atomic::cmpxchg(this, &_oops_do_mark_nmethods, required_mark_nmethods);                                                    
1709         if (observed_mark_nmethods == required_mark_nmethods)                                                                        
1710           break;                                                                                                                     
1711       }                                                                                                                              
1712       // Mark was clear when we first saw this guy.                                                                                  
1713       LogTarget(Trace, gc, nmethod) lt;                                                                                              
1714       if (lt.is_enabled()) {                                                                                                         
1715         LogStream ls(lt);                                                                                                            
1716         CompileTask::print(&ls, this, "oops_do, mark", /*short_form:*/ true);                                                        
1717       }                                                                                                                              
1718       return false;                                                                                                                  
1719     }                                                                                                                                
1720   }                                                                                                                                  
1721   // On fall through, another racing thread marked this nmethod before we did.                                                       
1722   return true;                                                                                                                       
1723 }                                                                                                                                    
1724 
1725 void nmethod::oops_do_marking_prologue() {                                                                                           
1726   log_trace(gc, nmethod)("oops_do_marking_prologue");                                                                                
1727   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");                                   
1728   // We use cmpxchg instead of regular assignment here because the user                                                              
1729   // may fork a bunch of threads, and we need them all to see the same state.                                                        
1730   nmethod* observed = Atomic::cmpxchg(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, (nmethod*)NULL);                                    
1731   guarantee(observed == NULL, "no races in this sequential code");                                                                   
1732 }                                                                                                                                    
1733 
1734 void nmethod::oops_do_marking_epilogue() {                                                                                           
1735   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");                                   
1736   nmethod* cur = _oops_do_mark_nmethods;                                                                                             
1737   while (cur != NMETHOD_SENTINEL) {                                                                                                  
1738     assert(cur != NULL, "not NULL-terminated");                                                                                      
1739     nmethod* next = cur->_oops_do_mark_link;                                                                                         
1740     cur->_oops_do_mark_link = NULL;                                                                                                  
1741     DEBUG_ONLY(cur->verify_oop_relocations());                                                                                       
1742 
1743     LogTarget(Trace, gc, nmethod) lt;                                                                                                
1744     if (lt.is_enabled()) {                                                                                                           
1745       LogStream ls(lt);                                                                                                              
1746       CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);                                                         
1747     }                                                                                                                                
1748     cur = next;                                                                                                                      
1749   }                                                                                                                                  
1750   nmethod* required = _oops_do_mark_nmethods;                                                                                        
1751   nmethod* observed = Atomic::cmpxchg((nmethod*)NULL, &_oops_do_mark_nmethods, required);                                            
1752   guarantee(observed == required, "no races in this sequential code");                                                               
1753   log_trace(gc, nmethod)("oops_do_marking_epilogue");                                                                                
1754 }                                                                                                                                    
1755 
1756 class DetectScavengeRoot: public OopClosure {                                                                                        
1757   bool     _detected_scavenge_root;                                                                                                  
1758   nmethod* _print_nm;                                                                                                                
1759 public:                                                                                                                              
1760   DetectScavengeRoot(nmethod* nm) : _detected_scavenge_root(false), _print_nm(nm) {}                                                 
1761 
1762   bool detected_scavenge_root() { return _detected_scavenge_root; }                                                                  
1763   virtual void do_oop(oop* p) {                                                                                                      
1764     if ((*p) != NULL && Universe::heap()->is_scavengable(*p)) {                                                                      
1765       NOT_PRODUCT(maybe_print(p));                                                                                                   
1766       _detected_scavenge_root = true;                                                                                                
1767     }                                                                                                                                
1768   }                                                                                                                                  
1769   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }                                                                        
1770 
1771 #ifndef PRODUCT                                                                                                                      
1772   void maybe_print(oop* p) {                                                                                                         
1773     LogTarget(Trace, gc, nmethod) lt;                                                                                                
1774     if (lt.is_enabled()) {                                                                                                           
1775       LogStream ls(lt);                                                                                                              
1776       if (!_detected_scavenge_root) {                                                                                                
1777         CompileTask::print(&ls, _print_nm, "new scavenge root", /*short_form:*/ true);                                               
1778       }                                                                                                                              
1779       ls.print("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ") ",                       
1780                p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm),                                                             
1781                p2i(*p), p2i(p));                                                                                                     
1782       ls.cr();                                                                                                                       
1783     }                                                                                                                                
1784   }                                                                                                                                  
1785 #endif //PRODUCT                                                                                                                     
1786 };                                                                                                                                   
1787 
1788 bool nmethod::detect_scavenge_root_oops() {                                                                                          
1789   DetectScavengeRoot detect_scavenge_root(this);                                                                                     
1790   oops_do(&detect_scavenge_root);                                                                                                    
1791   return detect_scavenge_root.detected_scavenge_root();                                                                              
1792 }                                                                                                                                    
1793 
1794 inline bool includes(void* p, void* from, void* to) {                                                                                
1795   return from <= p && p < to;                                                                                                        
1796 }                                                                                                                                    
1797 
1798 
1799 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {                                                                              
1800   assert(count >= 2, "must be sentinel values, at least");                                                                           
1801 
1802 #ifdef ASSERT                                                                                                                        
1803   // must be sorted and unique; we do a binary search in find_pc_desc()                                                              
1804   int prev_offset = pcs[0].pc_offset();                                                                                              
1805   assert(prev_offset == PcDesc::lower_offset_limit,                                                                                  
1806          "must start with a sentinel");                                                                                              
1807   for (int i = 1; i < count; i++) {                                                                                                  
1808     int this_offset = pcs[i].pc_offset();                                                                                            
1809     assert(this_offset > prev_offset, "offsets must be sorted");                                                                     
1810     prev_offset = this_offset;                                                                                                       
1811   }                                                                                                                                  
1812   assert(prev_offset == PcDesc::upper_offset_limit,                                                                                  
1813          "must end with a sentinel");                                                                                                
1814 #endif //ASSERT                                                                                                                      
1815 
1816   // Search for MethodHandle invokes and tag the nmethod.                                                                            
1817   for (int i = 0; i < count; i++) {                                                                                                  
1818     if (pcs[i].is_method_handle_invoke()) {                                                                                          
1819       set_has_method_handle_invokes(true);                                                                                           
1820       break;                                                                                                                         
1821     }                                                                                                                                
1822   }                                                                                                                                  
1823   assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler");                            
1824 
1825   int size = count * sizeof(PcDesc);                                                                                                 
1826   assert(scopes_pcs_size() >= size, "oob");                                                                                          
1827   memcpy(scopes_pcs_begin(), pcs, size);                                                                                             
1828 
1829   // Adjust the final sentinel downward.                                                                                             
1830   PcDesc* last_pc = &scopes_pcs_begin()[count-1];                                                                                    
1831   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");                                                              
1832   last_pc->set_pc_offset(content_size() + 1);                                                                                        
1833   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {                                                                             
1834     // Fill any rounding gaps with copies of the last record.                                                                        
1835     last_pc[1] = last_pc[0];                                                                                                         
1836   }                                                                                                                                  
1837   // The following assert could fail if sizeof(PcDesc) is not                                                                        
1838   // an integral multiple of oopSize (the rounding term).                                                                            
1839   // If it fails, change the logic to always allocate a multiple                                                                     
1840   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.                                                               
1841   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");                                                                     
1842 }                                                                                                                                    
1843 
1844 void nmethod::copy_scopes_data(u_char* buffer, int size) {                                                                           
1845   assert(scopes_data_size() >= size, "oob");                                                                                         
1846   memcpy(scopes_data_begin(), buffer, size);                                                                                         
1847 }                                                                                                                                    
1848 
1849 #ifdef ASSERT                                                                                                                        
1850 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) {                                          
1851   PcDesc* lower = search.scopes_pcs_begin();                                                                                         
1852   PcDesc* upper = search.scopes_pcs_end();                                                                                           
1853   lower += 1; // exclude initial sentinel                                                                                            
1854   PcDesc* res = NULL;                                                                                                                
1855   for (PcDesc* p = lower; p < upper; p++) {                                                                                          
1856     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc                                           
1857     if (match_desc(p, pc_offset, approximate)) {                                                                                     
1858       if (res == NULL)                                                                                                               
1859         res = p;                                                                                                                     
1860       else                                                                                                                           
1861         res = (PcDesc*) badAddress;                                                                                                  
1862     }                                                                                                                                
1863   }                                                                                                                                  
1864   return res;                                                                                                                        
1865 }                                                                                                                                    
1866 #endif                                                                                                                               
1867 
1868 
1869 // Finds a PcDesc with real-pc equal to "pc"                                                                                         
1870 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) {                           
1871   address base_address = search.code_begin();                                                                                        
1872   if ((pc < base_address) ||                                                                                                         
1873       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {                                                               
1874     return NULL;  // PC is wildly out of range                                                                                       
1875   }                                                                                                                                  
1876   int pc_offset = (int) (pc - base_address);                                                                                         
1877 
1878   // Check the PcDesc cache if it contains the desired PcDesc                                                                        
1879   // (This as an almost 100% hit rate.)                                                                                              
1880   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);                                                                 
1881   if (res != NULL) {                                                                                                                 
1882     assert(res == linear_search(search, pc_offset, approximate), "cache ok");                                                        
1883     return res;                                                                                                                      
1884   }                                                                                                                                  
1885 
1886   // Fallback algorithm: quasi-linear search for the PcDesc                                                                          
1887   // Find the last pc_offset less than the given offset.                                                                             
1888   // The successor must be the required match, if there is a match at all.                                                           
1889   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)                                                               
1890   PcDesc* lower = search.scopes_pcs_begin();                                                                                         
1891   PcDesc* upper = search.scopes_pcs_end();                                                                                           
1892   upper -= 1; // exclude final sentinel                                                                                              
1893   if (lower >= upper)  return NULL;  // native method; no PcDescs at all                                                             
1894 
1895 #define assert_LU_OK \                                                                                                               
1896   /* invariant on lower..upper during the following search: */ \                                                                     
1897   assert(lower->pc_offset() <  pc_offset, "sanity"); \                                                                               
1898   assert(upper->pc_offset() >= pc_offset, "sanity")                                                                                  
1899   assert_LU_OK;                                                                                                                      
1900 
1901   // Use the last successful return as a split point.                                                                                
1902   PcDesc* mid = _pc_desc_cache.last_pc_desc();                                                                                       
1903   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);                                                                                  
1904   if (mid->pc_offset() < pc_offset) {                                                                                                
1905     lower = mid;                                                                                                                     
1906   } else {                                                                                                                           
1907     upper = mid;                                                                                                                     
1908   }                                                                                                                                  
1909 
1910   // Take giant steps at first (4096, then 256, then 16, then 1)                                                                     
1911   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);                                                          
1912   const int RADIX = (1 << LOG2_RADIX);                                                                                               
1913   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {                                                            
1914     while ((mid = lower + step) < upper) {                                                                                           
1915       assert_LU_OK;                                                                                                                  
1916       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);                                                                              
1917       if (mid->pc_offset() < pc_offset) {                                                                                            
1918         lower = mid;                                                                                                                 
1919       } else {                                                                                                                       
1920         upper = mid;                                                                                                                 
1921         break;                                                                                                                       
1922       }                                                                                                                              
1923     }                                                                                                                                
1924     assert_LU_OK;                                                                                                                    
1925   }                                                                                                                                  
1926 
1927   // Sneak up on the value with a linear search of length ~16.                                                                       
1928   while (true) {                                                                                                                     
1929     assert_LU_OK;                                                                                                                    
1930     mid = lower + 1;                                                                                                                 
1931     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);                                                                                
1932     if (mid->pc_offset() < pc_offset) {                                                                                              
1933       lower = mid;                                                                                                                   
1934     } else {                                                                                                                         
1935       upper = mid;                                                                                                                   
1936       break;                                                                                                                         
1937     }                                                                                                                                
1938   }                                                                                                                                  
1939 #undef assert_LU_OK                                                                                                                  
1940 
1941   if (match_desc(upper, pc_offset, approximate)) {                                                                                   
1942     assert(upper == linear_search(search, pc_offset, approximate), "search ok");                                                     
1943     _pc_desc_cache.add_pc_desc(upper);                                                                                               
1944     return upper;                                                                                                                    
1945   } else {                                                                                                                           
1946     assert(NULL == linear_search(search, pc_offset, approximate), "search ok");                                                      
1947     return NULL;                                                                                                                     
1948   }                                                                                                                                  
1949 }                                                                                                                                    
1950 
1951 
1952 void nmethod::check_all_dependencies(DepChange& changes) {                                                                           
1953   // Checked dependencies are allocated into this ResourceMark                                                                       
1954   ResourceMark rm;                                                                                                                   
1955 
1956   // Turn off dependency tracing while actually testing dependencies.                                                                
1957   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );                                                                           
1958 
1959   typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,                                                    
1960                             &DependencySignature::equals, 11027> DepTable;                                                           
1961 
1962   DepTable* table = new DepTable();                                                                                                  
1963 
1964   // Iterate over live nmethods and check dependencies of all nmethods that are not                                                  
1965   // marked for deoptimization. A particular dependency is only checked once.                                                        
1966   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);                                                               
1967   while(iter.next()) {                                                                                                               
1968     nmethod* nm = iter.method();                                                                                                     
1969     // Only notify for live nmethods                                                                                                 
1970     if (!nm->is_marked_for_deoptimization()) {                                                                                       
1971       for (Dependencies::DepStream deps(nm); deps.next(); ) {                                                                        
1972         // Construct abstraction of a dependency.                                                                                    
1973         DependencySignature* current_sig = new DependencySignature(deps);                                                            
1974 
1975         // Determine if dependency is already checked. table->put(...) returns                                                       
1976         // 'true' if the dependency is added (i.e., was not in the hashtable).                                                       
1977         if (table->put(*current_sig, 1)) {                                                                                           
1978           if (deps.check_dependency() != NULL) {                                                                                     
1979             // Dependency checking failed. Print out information about the failed                                                    
1980             // dependency and finally fail with an assert. We can fail here, since                                                   
1981             // dependency checking is never done in a product build.                                                                 
1982             tty->print_cr("Failed dependency:");                                                                                     
1983             changes.print();                                                                                                         
1984             nm->print();                                                                                                             
1985             nm->print_dependencies();                                                                                                
1986             assert(false, "Should have been marked for deoptimization");                                                             
1987           }                                                                                                                          
1988         }                                                                                                                            
1989       }                                                                                                                              
1990     }                                                                                                                                
1991   }                                                                                                                                  
1992 }                                                                                                                                    
1993 
1994 bool nmethod::check_dependency_on(DepChange& changes) {                                                                              
1995   // What has happened:                                                                                                              
1996   // 1) a new class dependee has been added                                                                                          
1997   // 2) dependee and all its super classes have been marked                                                                          
1998   bool found_check = false;  // set true if we are upset                                                                             
1999   for (Dependencies::DepStream deps(this); deps.next(); ) {                                                                          
2000     // Evaluate only relevant dependencies.                                                                                          
2001     if (deps.spot_check_dependency_at(changes) != NULL) {                                                                            
2002       found_check = true;                                                                                                            
2003       NOT_DEBUG(break);                                                                                                              
2004     }                                                                                                                                
2005   }                                                                                                                                  
2006   return found_check;                                                                                                                
2007 }                                                                                                                                    
2008 
2009 bool nmethod::is_evol_dependent_on(Klass* dependee) {                                                                                
2010   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);                                                                        
2011   Array<Method*>* dependee_methods = dependee_ik->methods();                                                                         
2012   for (Dependencies::DepStream deps(this); deps.next(); ) {                                                                          
2013     if (deps.type() == Dependencies::evol_method) {                                                                                  
2014       Method* method = deps.method_argument(0);                                                                                      
2015       for (int j = 0; j < dependee_methods->length(); j++) {                                                                         
2016         if (dependee_methods->at(j) == method) {                                                                                     
2017           if (log_is_enabled(Debug, redefine, class, nmethod)) {                                                                     
2018             ResourceMark rm;                                                                                                         
2019             log_debug(redefine, class, nmethod)                                                                                      
2020               ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",                                       
2021                _method->method_holder()->external_name(),                                                                            
2022                _method->name()->as_C_string(),                                                                                       
2023                _method->signature()->as_C_string(),                                                                                  
2024                compile_id(),                                                                                                         
2025                method->method_holder()->external_name(),                                                                             
2026                method->name()->as_C_string(),                                                                                        
2027                method->signature()->as_C_string());                                                                                  
2028           }                                                                                                                          
2029           if (TraceDependencies || LogCompilation)                                                                                   
2030             deps.log_dependency(dependee);                                                                                           
2031           return true;                                                                                                               
2032         }                                                                                                                            
2033       }                                                                                                                              
2034     }                                                                                                                                
2035   }                                                                                                                                  
2036   return false;                                                                                                                      
2037 }                                                                                                                                    
2038 
2039 // Called from mark_for_deoptimization, when dependee is invalidated.                                                                
2040 bool nmethod::is_dependent_on_method(Method* dependee) {                                                                             
2041   for (Dependencies::DepStream deps(this); deps.next(); ) {                                                                          
2042     if (deps.type() != Dependencies::evol_method)                                                                                    
2043       continue;                                                                                                                      
2044     Method* method = deps.method_argument(0);                                                                                        
2045     if (method == dependee) return true;                                                                                             
2046   }                                                                                                                                  
2047   return false;                                                                                                                      
2048 }                                                                                                                                    
2049 
2050 
2051 bool nmethod::is_patchable_at(address instr_addr) {                                                                                  
2052   assert(insts_contains(instr_addr), "wrong nmethod used");                                                                          
2053   if (is_zombie()) {                                                                                                                 
2054     // a zombie may never be patched                                                                                                 
2055     return false;                                                                                                                    
2056   }                                                                                                                                  
2057   return true;                                                                                                                       
2058 }                                                                                                                                    
2059 
2060 
2061 address nmethod::continuation_for_implicit_exception(address pc) {                                                                   
2062   // Exception happened outside inline-cache check code => we are inside                                                             
2063   // an active nmethod => use cpc to determine a return address                                                                      
2064   int exception_offset = pc - code_begin();                                                                                          
2065   int cont_offset = ImplicitExceptionTable(this).at( exception_offset );                                                             
2066 #ifdef ASSERT                                                                                                                        
2067   if (cont_offset == 0) {                                                                                                            
2068     Thread* thread = Thread::current();                                                                                              
2069     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY                                                                  
2070     HandleMark hm(thread);                                                                                                           
2071     ResourceMark rm(thread);                                                                                                         
2072     CodeBlob* cb = CodeCache::find_blob(pc);                                                                                         
2073     assert(cb != NULL && cb == this, "");                                                                                            
2074     ttyLocker ttyl;                                                                                                                  
2075     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));                                                         
2076     print();                                                                                                                         
2077     method()->print_codes();                                                                                                         
2078     print_code();                                                                                                                    
2079     print_pcs();                                                                                                                     
2080   }                                                                                                                                  
2081 #endif                                                                                                                               
2082   if (cont_offset == 0) {                                                                                                            
2083     // Let the normal error handling report the exception                                                                            
2084     return NULL;                                                                                                                     
2085   }                                                                                                                                  
2086   return code_begin() + cont_offset;                                                                                                 
2087 }                                                                                                                                    
2088 
2089 
2090 
2091 void nmethod_init() {                                                                                                                
2092   // make sure you didn't forget to adjust the filler fields                                                                         
2093   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");                                                 
2094 }                                                                                                                                    
2095 
2096 
2097 //-------------------------------------------------------------------------------------------                                        
2098 
2099 
2100 // QQQ might we make this work from a frame??                                                                                        
2101 nmethodLocker::nmethodLocker(address pc) {                                                                                           
2102   CodeBlob* cb = CodeCache::find_blob(pc);                                                                                           
2103   guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found");                                                          
2104   _nm = cb->as_compiled_method();                                                                                                    
2105   lock_nmethod(_nm);                                                                                                                 
2106 }                                                                                                                                    
2107 
2108 // Only JvmtiDeferredEvent::compiled_method_unload_event()                                                                           
2109 // should pass zombie_ok == true.                                                                                                    
2110 void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) {                                                               
2111   if (cm == NULL)  return;                                                                                                           
2112   if (cm->is_aot()) return;  // FIXME: Revisit once _lock_count is added to aot_method                                               
2113   nmethod* nm = cm->as_nmethod();                                                                                                    
2114   Atomic::inc(&nm->_lock_count);                                                                                                     
2115   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");                                                              
2116 }                                                                                                                                    
2117 
2118 void nmethodLocker::unlock_nmethod(CompiledMethod* cm) {                                                                             
2119   if (cm == NULL)  return;                                                                                                           
2120   if (cm->is_aot()) return;  // FIXME: Revisit once _lock_count is added to aot_method                                               
2121   nmethod* nm = cm->as_nmethod();                                                                                                    
2122   Atomic::dec(&nm->_lock_count);                                                                                                     
2123   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");                                                                     
2124 }                                                                                                                                    
2125 
2126 
2127 // -----------------------------------------------------------------------------                                                     
2128 // Verification                                                                                                                      
2129 
2130 class VerifyOopsClosure: public OopClosure {                                                                                         
2131   nmethod* _nm;                                                                                                                      
2132   bool     _ok;                                                                                                                      
2133 public:                                                                                                                              
2134   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }                                                                            
2135   bool ok() { return _ok; }                                                                                                          
2136   virtual void do_oop(oop* p) {                                                                                                      
2137     if (oopDesc::is_oop_or_null(*p)) return;                                                                                         
2138     if (_ok) {                                                                                                                       
2139       _nm->print_nmethod(true);                                                                                                      
2140       _ok = false;                                                                                                                   
2141     }                                                                                                                                
2142     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",                                                  
2143                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));                                                              
2144   }                                                                                                                                  
2145   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }                                                                        
2146 };                                                                                                                                   
2147 
2148 void nmethod::verify() {                                                                                                             
2149 
2150   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant                                                         
2151   // seems odd.                                                                                                                      
2152 
2153   if (is_zombie() || is_not_entrant() || is_unloaded())                                                                              
2154     return;                                                                                                                          
2155 
2156   // Make sure all the entry points are correctly aligned for patching.                                                              
2157   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());                                                 
2158 
2159   // assert(oopDesc::is_oop(method()), "must be valid");                                                                             
2160 
2161   ResourceMark rm;                                                                                                                   
2162 
2163   if (!CodeCache::contains(this)) {                                                                                                  
2164     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));                                                                    
2165   }                                                                                                                                  
2166 
2167   if(is_native_method() )                                                                                                            
2168     return;                                                                                                                          
2169 
2170   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());                                                                     
2171   if (nm != this) {                                                                                                                  
2172     fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));                                                   
2173   }                                                                                                                                  
2174 
2175   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {                                                                  
2176     if (! p->verify(this)) {                                                                                                         
2177       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));                                                         
2178     }                                                                                                                                
2179   }                                                                                                                                  
2180 
2181   VerifyOopsClosure voc(this);                                                                                                       
2182   oops_do(&voc);                                                                                                                     
2183   assert(voc.ok(), "embedded oops must be OK");                                                                                      
2184   Universe::heap()->verify_nmethod(this);                                                                                            
2185 
2186   verify_scopes();                                                                                                                   
2187 }                                                                                                                                    
2188 
2189 
2190 void nmethod::verify_interrupt_point(address call_site) {                                                                            
2191   // Verify IC only when nmethod installation is finished.                                                                           
2192   if (!is_not_installed()) {                                                                                                         
2193     if (CompiledICLocker::is_safe(this)) {                                                                                           
2194       CompiledIC_at(this, call_site);                                                                                                
2195       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());                                                          
2196     } else {                                                                                                                         
2197       CompiledICLocker ml_verify(this);                                                                                              
2198       CompiledIC_at(this, call_site);                                                                                                
2199     }                                                                                                                                
2200   }                                                                                                                                  
2201 
2202   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());                                                               
2203   assert(pd != NULL, "PcDesc must exist");                                                                                           
2204   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),                                                                
2205                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),                       
2206                                      pd->return_oop());                                                                              
2207        !sd->is_top(); sd = sd->sender()) {                                                                                           
2208     sd->verify();                                                                                                                    
2209   }                                                                                                                                  
2210 }                                                                                                                                    
2211 
2212 void nmethod::verify_scopes() {                                                                                                      
2213   if( !method() ) return;       // Runtime stubs have no scope                                                                       
2214   if (method()->is_native()) return; // Ignore stub methods.                                                                         
2215   // iterate through all interrupt point                                                                                             
2216   // and verify the debug information is valid.                                                                                      
2217   RelocIterator iter((nmethod*)this);                                                                                                
2218   while (iter.next()) {                                                                                                              
2219     address stub = NULL;                                                                                                             
2220     switch (iter.type()) {                                                                                                           
2221       case relocInfo::virtual_call_type:                                                                                             
2222         verify_interrupt_point(iter.addr());                                                                                         
2223         break;                                                                                                                       
2224       case relocInfo::opt_virtual_call_type:                                                                                         
2225         stub = iter.opt_virtual_call_reloc()->static_stub(false);                                                                    
2226         verify_interrupt_point(iter.addr());                                                                                         
2227         break;                                                                                                                       
2228       case relocInfo::static_call_type:                                                                                              
2229         stub = iter.static_call_reloc()->static_stub(false);                                                                         
2230         //verify_interrupt_point(iter.addr());                                                                                       
2231         break;                                                                                                                       
2232       case relocInfo::runtime_call_type:                                                                                             
2233       case relocInfo::runtime_call_w_cp_type: {                                                                                      
2234         address destination = iter.reloc()->value();                                                                                 
2235         // Right now there is no way to find out which entries support                                                               
2236         // an interrupt point.  It would be nice if we had this                                                                      
2237         // information in a table.                                                                                                   
2238         break;                                                                                                                       
2239       }                                                                                                                              
2240       default:                                                                                                                       
2241         break;                                                                                                                       
2242     }                                                                                                                                
2243     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");                                            
2244   }                                                                                                                                  
2245 }                                                                                                                                    
2246 
2247 
2248 // -----------------------------------------------------------------------------                                                     
2249 // Non-product code                                                                                                                  
2250 #ifndef PRODUCT                                                                                                                      
2251 
2252 class DebugScavengeRoot: public OopClosure {                                                                                         
2253   nmethod* _nm;                                                                                                                      
2254   bool     _ok;                                                                                                                      
2255 public:                                                                                                                              
2256   DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }                                                                            
2257   bool ok() { return _ok; }                                                                                                          
2258   virtual void do_oop(oop* p) {                                                                                                      
2259     if ((*p) == NULL || !Universe::heap()->is_scavengable(*p))  return;                                                              
2260     if (_ok) {                                                                                                                       
2261       _nm->print_nmethod(true);                                                                                                      
2262       _ok = false;                                                                                                                   
2263     }                                                                                                                                
2264     tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",                                          
2265                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));                                                              
2266     (*p)->print();                                                                                                                   
2267   }                                                                                                                                  
2268   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }                                                                        
2269 };                                                                                                                                   
2270 
2271 void nmethod::verify_scavenge_root_oops() {                                                                                          
2272   if (!on_scavenge_root_list()) {                                                                                                    
2273     // Actually look inside, to verify the claim that it's clean.                                                                    
2274     DebugScavengeRoot debug_scavenge_root(this);                                                                                     
2275     oops_do(&debug_scavenge_root);                                                                                                   
2276     if (!debug_scavenge_root.ok())                                                                                                   
2277       fatal("found an unadvertised bad scavengable oop in the code cache");                                                          
2278   }                                                                                                                                  
2279   assert(scavenge_root_not_marked(), "");                                                                                            
2280 }                                                                                                                                    
2281 
2282 #endif // PRODUCT                                                                                                                    
2283 
2284 // Printing operations                                                                                                               
2285 
2286 void nmethod::print() const {                                                                                                        
2287   ResourceMark rm;                                                                                                                   
2288   ttyLocker ttyl;   // keep the following output all in one block                                                                    
2289 
2290   tty->print("Compiled method ");                                                                                                    
2291 
2292   if (is_compiled_by_c1()) {                                                                                                         
2293     tty->print("(c1) ");                                                                                                             
2294   } else if (is_compiled_by_c2()) {                                                                                                  
2295     tty->print("(c2) ");                                                                                                             
2296   } else if (is_compiled_by_jvmci()) {                                                                                               
2297     tty->print("(JVMCI) ");                                                                                                          
2298   } else {                                                                                                                           
2299     tty->print("(nm) ");                                                                                                             
2300   }                                                                                                                                  
2301 
2302   print_on(tty, NULL);                                                                                                               
2303 
2304   if (WizardMode) {                                                                                                                  
2305     tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));                                                                        
2306     tty->print(" for method " INTPTR_FORMAT , p2i(method()));                                                                        
2307     tty->print(" { ");                                                                                                               
2308     tty->print_cr("%s ", state());                                                                                                   
2309     if (on_scavenge_root_list())  tty->print("scavenge_root ");                                                                      
2310     tty->print_cr("}:");                                                                                                             
2311   }                                                                                                                                  
2312   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2313                                               p2i(this),                                                                             
2314                                               p2i(this) + size(),                                                                    
2315                                               size());                                                                               
2316   if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2317                                               p2i(relocation_begin()),                                                               
2318                                               p2i(relocation_end()),                                                                 
2319                                               relocation_size());                                                                    
2320   if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2321                                               p2i(consts_begin()),                                                                   
2322                                               p2i(consts_end()),                                                                     
2323                                               consts_size());                                                                        
2324   if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2325                                               p2i(insts_begin()),                                                                    
2326                                               p2i(insts_end()),                                                                      
2327                                               insts_size());                                                                         
2328   if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2329                                               p2i(stub_begin()),                                                                     
2330                                               p2i(stub_end()),                                                                       
2331                                               stub_size());                                                                          
2332   if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2333                                               p2i(oops_begin()),                                                                     
2334                                               p2i(oops_end()),                                                                       
2335                                               oops_size());                                                                          
2336   if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                         
2337                                               p2i(metadata_begin()),                                                                 
2338                                               p2i(metadata_end()),                                                                   
2339                                               metadata_size());                                                                      
2340   if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2341                                               p2i(scopes_data_begin()),                                                              
2342                                               p2i(scopes_data_end()),                                                                
2343                                               scopes_data_size());                                                                   
2344   if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2345                                               p2i(scopes_pcs_begin()),                                                               
2346                                               p2i(scopes_pcs_end()),                                                                 
2347                                               scopes_pcs_size());                                                                    
2348   if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2349                                               p2i(dependencies_begin()),                                                             
2350                                               p2i(dependencies_end()),                                                               
2351                                               dependencies_size());                                                                  
2352   if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2353                                               p2i(handler_table_begin()),                                                            
2354                                               p2i(handler_table_end()),                                                              
2355                                               handler_table_size());                                                                 
2356   if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",                          
2357                                               p2i(nul_chk_table_begin()),                                                            
2358                                               p2i(nul_chk_table_end()),                                                              
2359                                               nul_chk_table_size());                                                                 
2360 }                                                                                                                                    
2361 
2362 #ifndef PRODUCT                                                                                                                      
2363 
2364 void nmethod::print_scopes() {                                                                                                       
2365   // Find the first pc desc for all scopes in the code and print it.                                                                 
2366   ResourceMark rm;                                                                                                                   
2367   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {                                                                  
2368     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)                                                       
2369       continue;                                                                                                                      
2370 
2371     ScopeDesc* sd = scope_desc_at(p->real_pc(this));                                                                                 
2372     while (sd != NULL) {                                                                                                             
2373       sd->print_on(tty, p);                                                                                                          
2374       sd = sd->sender();                                                                                                             
2375     }                                                                                                                                
2376   }                                                                                                                                  
2377 }                                                                                                                                    
2378 
2379 void nmethod::print_dependencies() {                                                                                                 
2380   ResourceMark rm;                                                                                                                   
2381   ttyLocker ttyl;   // keep the following output all in one block                                                                    
2382   tty->print_cr("Dependencies:");                                                                                                    
2383   for (Dependencies::DepStream deps(this); deps.next(); ) {                                                                          
2384     deps.print_dependency();                                                                                                         
2385     Klass* ctxk = deps.context_type();                                                                                               
2386     if (ctxk != NULL) {                                                                                                              
2387       if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {                                      
2388         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());                                                               
2389       }                                                                                                                              
2390     }                                                                                                                                
2391     deps.log_dependency();  // put it into the xml log also                                                                          
2392   }                                                                                                                                  
2393 }                                                                                                                                    
2394 
2395 
2396 void nmethod::print_relocations() {                                                                                                  
2397   ResourceMark m;       // in case methods get printed via the debugger                                                              
2398   tty->print_cr("relocations:");                                                                                                     
2399   RelocIterator iter(this);                                                                                                          
2400   iter.print();                                                                                                                      
2401 }                                                                                                                                    
2402 
2403 
2404 void nmethod::print_pcs() {                                                                                                          
2405   ResourceMark m;       // in case methods get printed via debugger                                                                  
2406   tty->print_cr("pc-bytecode offsets:");                                                                                             
2407   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {                                                                  
2408     p->print(this);                                                                                                                  
2409   }                                                                                                                                  
2410 }                                                                                                                                    
2411 
2412 void nmethod::print_recorded_oops() {                                                                                                
2413   tty->print_cr("Recorded oops:");                                                                                                   
2414   for (int i = 0; i < oops_count(); i++) {                                                                                           
2415     oop o = oop_at(i);                                                                                                               
2416     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o));                                                                               
2417     if (o == Universe::non_oop_word()) {                                                                                             
2418       tty->print("non-oop word");                                                                                                    
2419     } else {                                                                                                                         
2420       if (o != NULL) {                                                                                                               
2421         o->print_value();                                                                                                            
2422       } else {                                                                                                                       
2423         tty->print_cr("NULL");                                                                                                       
2424       }                                                                                                                              
2425     }                                                                                                                                
2426     tty->cr();                                                                                                                       
2427   }                                                                                                                                  
2428 }                                                                                                                                    
2429 
2430 void nmethod::print_recorded_metadata() {                                                                                            
2431   tty->print_cr("Recorded metadata:");                                                                                               
2432   for (int i = 0; i < metadata_count(); i++) {                                                                                       
2433     Metadata* m = metadata_at(i);                                                                                                    
2434     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m));                                                                               
2435     if (m == (Metadata*)Universe::non_oop_word()) {                                                                                  
2436       tty->print("non-metadata word");                                                                                               
2437     } else {                                                                                                                         
2438       Metadata::print_value_on_maybe_null(tty, m);                                                                                   
2439     }                                                                                                                                
2440     tty->cr();                                                                                                                       
2441   }                                                                                                                                  
2442 }                                                                                                                                    
2443 
2444 #endif // PRODUCT                                                                                                                    
2445 
2446 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {                                                                  
2447   RelocIterator iter(this, begin, end);                                                                                              
2448   bool have_one = false;                                                                                                             
2449   while (iter.next()) {                                                                                                              
2450     have_one = true;                                                                                                                 
2451     switch (iter.type()) {                                                                                                           
2452         case relocInfo::none:                  return "no_reloc";                                                                    
2453         case relocInfo::oop_type: {                                                                                                  
2454           stringStream st;                                                                                                           
2455           oop_Relocation* r = iter.oop_reloc();                                                                                      
2456           oop obj = r->oop_value();                                                                                                  
2457           st.print("oop(");                                                                                                          
2458           if (obj == NULL) st.print("NULL");                                                                                         
2459           else obj->print_value_on(&st);                                                                                             
2460           st.print(")");                                                                                                             
2461           return st.as_string();                                                                                                     
2462         }                                                                                                                            
2463         case relocInfo::metadata_type: {                                                                                             
2464           stringStream st;                                                                                                           
2465           metadata_Relocation* r = iter.metadata_reloc();                                                                            
2466           Metadata* obj = r->metadata_value();                                                                                       
2467           st.print("metadata(");                                                                                                     
2468           if (obj == NULL) st.print("NULL");                                                                                         
2469           else obj->print_value_on(&st);                                                                                             
2470           st.print(")");                                                                                                             
2471           return st.as_string();                                                                                                     
2472         }                                                                                                                            
2473         case relocInfo::runtime_call_type:                                                                                           
2474         case relocInfo::runtime_call_w_cp_type: {                                                                                    
2475           stringStream st;                                                                                                           
2476           st.print("runtime_call");                                                                                                  
2477           CallRelocation* r = (CallRelocation*)iter.reloc();                                                                         
2478           address dest = r->destination();                                                                                           
2479           CodeBlob* cb = CodeCache::find_blob(dest);                                                                                 
2480           if (cb != NULL) {                                                                                                          
2481             st.print(" %s", cb->name());                                                                                             
2482           } else {                                                                                                                   
2483             ResourceMark rm;                                                                                                         
2484             const int buflen = 1024;                                                                                                 
2485             char* buf = NEW_RESOURCE_ARRAY(char, buflen);                                                                            
2486             int offset;                                                                                                              
2487             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {                                                      
2488               st.print(" %s", buf);                                                                                                  
2489               if (offset != 0) {                                                                                                     
2490                 st.print("+%d", offset);                                                                                             
2491               }                                                                                                                      
2492             }                                                                                                                        
2493           }                                                                                                                          
2494           return st.as_string();                                                                                                     
2495         }                                                                                                                            
2496         case relocInfo::virtual_call_type: {                                                                                         
2497           stringStream st;                                                                                                           
2498           st.print_raw("virtual_call");                                                                                              
2499           virtual_call_Relocation* r = iter.virtual_call_reloc();                                                                    
2500           Method* m = r->method_value();                                                                                             
2501           if (m != NULL) {                                                                                                           
2502             assert(m->is_method(), "");                                                                                              
2503             m->print_short_name(&st);                                                                                                
2504           }                                                                                                                          
2505           return st.as_string();                                                                                                     
2506         }                                                                                                                            
2507         case relocInfo::opt_virtual_call_type: {                                                                                     
2508           stringStream st;                                                                                                           
2509           st.print_raw("optimized virtual_call");                                                                                    
2510           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();                                                            
2511           Method* m = r->method_value();                                                                                             
2512           if (m != NULL) {                                                                                                           
2513             assert(m->is_method(), "");                                                                                              
2514             m->print_short_name(&st);                                                                                                
2515           }                                                                                                                          
2516           return st.as_string();                                                                                                     
2517         }                                                                                                                            
2518         case relocInfo::static_call_type: {                                                                                          
2519           stringStream st;                                                                                                           
2520           st.print_raw("static_call");                                                                                               
2521           static_call_Relocation* r = iter.static_call_reloc();                                                                      
2522           Method* m = r->method_value();                                                                                             
2523           if (m != NULL) {                                                                                                           
2524             assert(m->is_method(), "");                                                                                              
2525             m->print_short_name(&st);                                                                                                
2526           }                                                                                                                          
2527           return st.as_string();                                                                                                     
2528         }                                                                                                                            
2529         case relocInfo::static_stub_type:      return "static_stub";                                                                 
2530         case relocInfo::external_word_type:    return "external_word";                                                               
2531         case relocInfo::internal_word_type:    return "internal_word";                                                               
2532         case relocInfo::section_word_type:     return "section_word";                                                                
2533         case relocInfo::poll_type:             return "poll";                                                                        
2534         case relocInfo::poll_return_type:      return "poll_return";                                                                 
2535         case relocInfo::type_mask:             return "type_bit_mask";                                                               
2536 
2537         default:                                                                                                                     
2538           break;                                                                                                                     
2539     }                                                                                                                                
2540   }                                                                                                                                  
2541   return have_one ? "other" : NULL;                                                                                                  
2542 }                                                                                                                                    
2543 
2544 // Return a the last scope in (begin..end]                                                                                           
2545 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {                                                                      
2546   PcDesc* p = pc_desc_near(begin+1);                                                                                                 
2547   if (p != NULL && p->real_pc(this) <= end) {                                                                                        
2548     return new ScopeDesc(this, p->scope_decode_offset(),                                                                             
2549                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),                                      
2550                          p->return_oop());                                                                                           
2551   }                                                                                                                                  
2552   return NULL;                                                                                                                       
2553 }                                                                                                                                    
2554 
2555 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {                                                
2556   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");                                                   
2557   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");                                          
2558   if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin())         stream->print_cr("[Exception Handler]");       
2559   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");                                                     
2560   if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
2561 
2562   if (has_method_handle_invokes())                                                                                                   
2563     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");                                       
2564 
2565   if (block_begin == consts_begin())            stream->print_cr("[Constants]");                                                     
2566 
2567   if (block_begin == entry_point()) {                                                                                                
2568     methodHandle m = method();                                                                                                       
2569     if (m.not_null()) {                                                                                                              
2570       stream->print("  # ");                                                                                                         
2571       m->print_value_on(stream);                                                                                                     
2572       stream->cr();                                                                                                                  
2573     }                                                                                                                                
2574     if (m.not_null() && !is_osr_method()) {                                                                                          
2575       ResourceMark rm;                                                                                                               
2576       int sizeargs = m->size_of_parameters();                                                                                        
2577       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);                                                                   
2578       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);                                                                   
2579       {                                                                                                                              
2580         int sig_index = 0;                                                                                                           
2581         if (!m->is_static())                                                                                                         
2582           sig_bt[sig_index++] = T_OBJECT; // 'this'                                                                                  
2583         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {                                                  
2584           BasicType t = ss.type();                                                                                                   
2585           sig_bt[sig_index++] = t;                                                                                                   
2586           if (type2size[t] == 2) {                                                                                                   
2587             sig_bt[sig_index++] = T_VOID;                                                                                            
2588           } else {                                                                                                                   
2589             assert(type2size[t] == 1, "size is 1 or 2");                                                                             
2590           }                                                                                                                          
2591         }                                                                                                                            
2592         assert(sig_index == sizeargs, "");                                                                                           
2593       }                                                                                                                              
2594       const char* spname = "sp"; // make arch-specific?                                                                              
2595       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);                                 
2596       int stack_slot_offset = this->frame_size() * wordSize;                                                                         
2597       int tab1 = 14, tab2 = 24;                                                                                                      
2598       int sig_index = 0;                                                                                                             
2599       int arg_index = (m->is_static() ? 0 : -1);                                                                                     
2600       bool did_old_sp = false;                                                                                                       
2601       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {                                                             
2602         bool at_this = (arg_index == -1);                                                                                            
2603         bool at_old_sp = false;                                                                                                      
2604         BasicType t = (at_this ? T_OBJECT : ss.type());                                                                              
2605         assert(t == sig_bt[sig_index], "sigs in sync");                                                                              
2606         if (at_this)                                                                                                                 
2607           stream->print("  # this: ");                                                                                               
2608         else                                                                                                                         
2609           stream->print("  # parm%d: ", arg_index);                                                                                  
2610         stream->move_to(tab1);                                                                                                       
2611         VMReg fst = regs[sig_index].first();                                                                                         
2612         VMReg snd = regs[sig_index].second();                                                                                        
2613         if (fst->is_reg()) {                                                                                                         
2614           stream->print("%s", fst->name());                                                                                          
2615           if (snd->is_valid())  {                                                                                                    
2616             stream->print(":%s", snd->name());                                                                                       
2617           }                                                                                                                          
2618         } else if (fst->is_stack()) {                                                                                                
2619           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;                                            
2620           if (offset == stack_slot_offset)  at_old_sp = true;                                                                        
2621           stream->print("[%s+0x%x]", spname, offset);                                                                                
2622         } else {                                                                                                                     
2623           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);                                                       
2624         }                                                                                                                            
2625         stream->print(" ");                                                                                                          
2626         stream->move_to(tab2);                                                                                                       
2627         stream->print("= ");                                                                                                         
2628         if (at_this) {                                                                                                               
2629           m->method_holder()->print_value_on(stream);                                                                                
2630         } else {                                                                                                                     
2631           bool did_name = false;                                                                                                     
2632           if (!at_this && ss.is_object()) {                                                                                          
2633             Symbol* name = ss.as_symbol_or_null();                                                                                   
2634             if (name != NULL) {                                                                                                      
2635               name->print_value_on(stream);                                                                                          
2636               did_name = true;                                                                                                       
2637             }                                                                                                                        
2638           }                                                                                                                          
2639           if (!did_name)                                                                                                             
2640             stream->print("%s", type2name(t));                                                                                       
2641         }                                                                                                                            
2642         if (at_old_sp) {                                                                                                             
2643           stream->print("  (%s of caller)", spname);                                                                                 
2644           did_old_sp = true;                                                                                                         
2645         }                                                                                                                            
2646         stream->cr();                                                                                                                
2647         sig_index += type2size[t];                                                                                                   
2648         arg_index += 1;                                                                                                              
2649         if (!at_this)  ss.next();                                                                                                    
2650       }                                                                                                                              
2651       if (!did_old_sp) {                                                                                                             
2652         stream->print("  # ");                                                                                                       
2653         stream->move_to(tab1);                                                                                                       
2654         stream->print("[%s+0x%x]", spname, stack_slot_offset);                                                                       
2655         stream->print("  (%s of caller)", spname);                                                                                   
2656         stream->cr();                                                                                                                
2657       }                                                                                                                              
2658     }                                                                                                                                
2659   }                                                                                                                                  
2660 }                                                                                                                                    
2661 
2662 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {                                      
2663   // First, find an oopmap in (begin, end].                                                                                          
2664   // We use the odd half-closed interval so that oop maps and scope descs                                                            
2665   // which are tied to the byte after a call are printed with the call itself.                                                       
2666   address base = code_begin();                                                                                                       
2667   ImmutableOopMapSet* oms = oop_maps();                                                                                              
2668   if (oms != NULL) {                                                                                                                 
2669     for (int i = 0, imax = oms->count(); i < imax; i++) {                                                                            
2670       const ImmutableOopMapPair* pair = oms->pair_at(i);                                                                             
2671       const ImmutableOopMap* om = pair->get_from(oms);                                                                               
2672       address pc = base + pair->pc_offset();                                                                                         
2673       if (pc > begin) {                                                                                                              
2674         if (pc <= end) {                                                                                                             
2675           st->move_to(column);                                                                                                       
2676           st->print("; ");                                                                                                           
2677           om->print_on(st);                                                                                                          
2678         }                                                                                                                            
2679         break;                                                                                                                       
2680       }                                                                                                                              
2681     }                                                                                                                                
2682   }                                                                                                                                  
2683 
2684   // Print any debug info present at this pc.                                                                                        
2685   ScopeDesc* sd  = scope_desc_in(begin, end);                                                                                        
2686   if (sd != NULL) {                                                                                                                  
2687     st->move_to(column);                                                                                                             
2688     if (sd->bci() == SynchronizationEntryBCI) {                                                                                      
2689       st->print(";*synchronization entry");                                                                                          
2690     } else if (sd->bci() == AfterBci) {                                                                                              
2691       st->print(";* method exit (unlocked if synchronized)");                                                                        
2692     } else if (sd->bci() == UnwindBci) {                                                                                             
2693       st->print(";* unwind (locked if synchronized)");                                                                               
2694     } else if (sd->bci() == AfterExceptionBci) {                                                                                     
2695       st->print(";* unwind (unlocked if synchronized)");                                                                             
2696     } else if (sd->bci() == UnknownBci) {                                                                                            
2697       st->print(";* unknown");                                                                                                       
2698     } else if (sd->bci() == InvalidFrameStateBci) {                                                                                  
2699       st->print(";* invalid frame state");                                                                                           
2700     } else {                                                                                                                         
2701       if (sd->method() == NULL) {                                                                                                    
2702         st->print("method is NULL");                                                                                                 
2703       } else if (sd->method()->is_native()) {                                                                                        
2704         st->print("method is native");                                                                                               
2705       } else {                                                                                                                       
2706         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());                                                                  
2707         st->print(";*%s", Bytecodes::name(bc));                                                                                      
2708         switch (bc) {                                                                                                                
2709         case Bytecodes::_invokevirtual:                                                                                              
2710         case Bytecodes::_invokespecial:                                                                                              
2711         case Bytecodes::_invokestatic:                                                                                               
2712         case Bytecodes::_invokeinterface:                                                                                            
2713           {                                                                                                                          
2714             Bytecode_invoke invoke(sd->method(), sd->bci());                                                                         
2715             st->print(" ");                                                                                                          
2716             if (invoke.name() != NULL)                                                                                               
2717               invoke.name()->print_symbol_on(st);                                                                                    
2718             else                                                                                                                     
2719               st->print("<UNKNOWN>");                                                                                                
2720             break;                                                                                                                   
2721           }                                                                                                                          
2722         case Bytecodes::_getfield:                                                                                                   
2723         case Bytecodes::_putfield:                                                                                                   
2724         case Bytecodes::_getstatic:                                                                                                  
2725         case Bytecodes::_putstatic:                                                                                                  
2726           {                                                                                                                          
2727             Bytecode_field field(sd->method(), sd->bci());                                                                           
2728             st->print(" ");                                                                                                          
2729             if (field.name() != NULL)                                                                                                
2730               field.name()->print_symbol_on(st);                                                                                     
2731             else                                                                                                                     
2732               st->print("<UNKNOWN>");                                                                                                
2733           }                                                                                                                          
2734         default:                                                                                                                     
2735           break;                                                                                                                     
2736         }                                                                                                                            
2737       }                                                                                                                              
2738       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());      
2739     }                                                                                                                                
2740 
2741     // Print all scopes                                                                                                              
2742     for (;sd != NULL; sd = sd->sender()) {                                                                                           
2743       st->move_to(column);                                                                                                           
2744       st->print("; -");                                                                                                              
2745       if (sd->method() == NULL) {                                                                                                    
2746         st->print("method is NULL");                                                                                                 
2747       } else {                                                                                                                       
2748         sd->method()->print_short_name(st);                                                                                          
2749       }                                                                                                                              
2750       int lineno = sd->method()->line_number_from_bci(sd->bci());                                                                    
2751       if (lineno != -1) {                                                                                                            
2752         st->print("@%d (line %d)", sd->bci(), lineno);                                                                               
2753       } else {                                                                                                                       
2754         st->print("@%d", sd->bci());                                                                                                 
2755       }                                                                                                                              
2756       st->cr();                                                                                                                      
2757     }                                                                                                                                
2758   }                                                                                                                                  
2759 
2760   // Print relocation information                                                                                                    
2761   const char* str = reloc_string_for(begin, end);                                                                                    
2762   if (str != NULL) {                                                                                                                 
2763     if (sd != NULL) st->cr();                                                                                                        
2764     st->move_to(column);                                                                                                             
2765     st->print(";   {%s}", str);                                                                                                      
2766   }                                                                                                                                  
2767   int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());                                                           
2768   if (cont_offset != 0) {                                                                                                            
2769     st->move_to(column);                                                                                                             
2770     st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));                                
2771   }                                                                                                                                  
2772 
2773 }                                                                                                                                    
2774 
2775 class DirectNativeCallWrapper: public NativeCallWrapper {                                                                            
2776 private:                                                                                                                             
2777   NativeCall* _call;                                                                                                                 
2778 
2779 public:                                                                                                                              
2780   DirectNativeCallWrapper(NativeCall* call) : _call(call) {}                                                                         
2781 
2782   virtual address destination() const { return _call->destination(); }                                                               
2783   virtual address instruction_address() const { return _call->instruction_address(); }                                               
2784   virtual address next_instruction_address() const { return _call->next_instruction_address(); }                                     
2785   virtual address return_address() const { return _call->return_address(); }                                                         
2786 
2787   virtual address get_resolve_call_stub(bool is_optimized) const {                                                                   
2788     if (is_optimized) {                                                                                                              
2789       return SharedRuntime::get_resolve_opt_virtual_call_stub();                                                                     
2790     }                                                                                                                                
2791     return SharedRuntime::get_resolve_virtual_call_stub();                                                                           
2792   }                                                                                                                                  
2793 
2794   virtual void set_destination_mt_safe(address dest) {                                                                               
2795 #if INCLUDE_AOT                                                                                                                      
2796     if (UseAOT) {                                                                                                                    
2797       CodeBlob* callee = CodeCache::find_blob(dest);                                                                                 
2798       CompiledMethod* cm = callee->as_compiled_method_or_null();                                                                     
2799       if (cm != NULL && cm->is_far_code()) {                                                                                         
2800         // Temporary fix, see JDK-8143106                                                                                            
2801         CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());                                         
2802         csc->set_to_far(methodHandle(cm->method()), dest);                                                                           
2803         return;                                                                                                                      
2804       }                                                                                                                              
2805     }                                                                                                                                
2806 #endif                                                                                                                               
2807     _call->set_destination_mt_safe(dest);                                                                                            
2808   }                                                                                                                                  
2809 
2810   virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {                                                
2811     CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());                                             
2812 #if INCLUDE_AOT                                                                                                                      
2813     if (info.to_aot()) {                                                                                                             
2814       csc->set_to_far(method, info.entry());                                                                                         
2815     } else                                                                                                                           
2816 #endif                                                                                                                               
2817     {                                                                                                                                
2818       csc->set_to_interpreted(method, info.entry());                                                                                 
2819     }                                                                                                                                
2820   }                                                                                                                                  
2821 
2822   virtual void verify() const {                                                                                                      
2823     // make sure code pattern is actually a call imm32 instruction                                                                   
2824     _call->verify();                                                                                                                 
2825     _call->verify_alignment();                                                                                                       
2826   }                                                                                                                                  
2827 
2828   virtual void verify_resolve_call(address dest) const {                                                                             
2829     CodeBlob* db = CodeCache::find_blob_unsafe(dest);                                                                                
2830     assert(db != NULL && !db->is_adapter_blob(), "must use stub!");                                                                  
2831   }                                                                                                                                  
2832 
2833   virtual bool is_call_to_interpreted(address dest) const {                                                                          
2834     CodeBlob* cb = CodeCache::find_blob(_call->instruction_address());                                                               
2835     return cb->contains(dest);                                                                                                       
2836   }                                                                                                                                  
2837 
2838   virtual bool is_safe_for_patching() const { return false; }                                                                        
2839 
2840   virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const {                                                
2841     return nativeMovConstReg_at(r->cached_value());                                                                                  
2842   }                                                                                                                                  
2843 
2844   virtual void *get_data(NativeInstruction* instruction) const {                                                                     
2845     return (void*)((NativeMovConstReg*) instruction)->data();                                                                        
2846   }                                                                                                                                  
2847 
2848   virtual void set_data(NativeInstruction* instruction, intptr_t data) {                                                             
2849     ((NativeMovConstReg*) instruction)->set_data(data);                                                                              
2850   }                                                                                                                                  
2851 };                                                                                                                                   
2852 
2853 NativeCallWrapper* nmethod::call_wrapper_at(address call) const {                                                                    
2854   return new DirectNativeCallWrapper((NativeCall*) call);                                                                            
2855 }                                                                                                                                    
2856 
2857 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const {                                                           
2858   return new DirectNativeCallWrapper(nativeCall_before(return_pc));                                                                  
2859 }                                                                                                                                    
2860 
2861 address nmethod::call_instruction_address(address pc) const {                                                                        
2862   if (NativeCall::is_call_before(pc)) {                                                                                              
2863     NativeCall *ncall = nativeCall_before(pc);                                                                                       
2864     return ncall->instruction_address();                                                                                             
2865   }                                                                                                                                  
2866   return NULL;                                                                                                                       
2867 }                                                                                                                                    
2868 
2869 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const {                                                    
2870   return CompiledDirectStaticCall::at(call_site);                                                                                    
2871 }                                                                                                                                    
2872 
2873 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const {                                                        
2874   return CompiledDirectStaticCall::at(call_site);                                                                                    
2875 }                                                                                                                                    
2876 
2877 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const {                                                  
2878   return CompiledDirectStaticCall::before(return_addr);                                                                              
2879 }                                                                                                                                    
2880 
2881 #ifndef PRODUCT                                                                                                                      
2882 
2883 void nmethod::print_value_on(outputStream* st) const {                                                                               
2884   st->print("nmethod");                                                                                                              
2885   print_on(st, NULL);                                                                                                                
2886 }                                                                                                                                    
2887 
2888 void nmethod::print_calls(outputStream* st) {                                                                                        
2889   RelocIterator iter(this);                                                                                                          
2890   while (iter.next()) {                                                                                                              
2891     switch (iter.type()) {                                                                                                           
2892     case relocInfo::virtual_call_type:                                                                                               
2893     case relocInfo::opt_virtual_call_type: {                                                                                         
2894       CompiledICLocker ml_verify(this);                                                                                              
2895       CompiledIC_at(&iter)->print();                                                                                                 
2896       break;                                                                                                                         
2897     }                                                                                                                                
2898     case relocInfo::static_call_type:                                                                                                
2899       st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));                                                      
2900       CompiledDirectStaticCall::at(iter.reloc())->print();                                                                           
2901       break;                                                                                                                         
2902     default:                                                                                                                         
2903       break;                                                                                                                         
2904     }                                                                                                                                
2905   }                                                                                                                                  
2906 }                                                                                                                                    
2907 
2908 void nmethod::print_handler_table() {                                                                                                
2909   ExceptionHandlerTable(this).print();                                                                                               
2910 }                                                                                                                                    
2911 
2912 void nmethod::print_nul_chk_table() {                                                                                                
2913   ImplicitExceptionTable(this).print(code_begin());                                                                                  
2914 }                                                                                                                                    
2915 
2916 void nmethod::print_statistics() {                                                                                                   
2917   ttyLocker ttyl;                                                                                                                    
2918   if (xtty != NULL)  xtty->head("statistics type='nmethod'");                                                                        
2919   native_nmethod_stats.print_native_nmethod_stats();                                                                                 
2920 #ifdef COMPILER1                                                                                                                     
2921   c1_java_nmethod_stats.print_nmethod_stats("C1");                                                                                   
2922 #endif                                                                                                                               
2923 #ifdef COMPILER2                                                                                                                     
2924   c2_java_nmethod_stats.print_nmethod_stats("C2");                                                                                   
2925 #endif                                                                                                                               
2926 #if INCLUDE_JVMCI                                                                                                                    
2927   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");                                                                             
2928 #endif                                                                                                                               
2929   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");                                                                         
2930   DebugInformationRecorder::print_statistics();                                                                                      
2931 #ifndef PRODUCT                                                                                                                      
2932   pc_nmethod_stats.print_pc_stats();                                                                                                 
2933 #endif                                                                                                                               
2934   Dependencies::print_statistics();                                                                                                  
2935   if (xtty != NULL)  xtty->tail("statistics");                                                                                       
2936 }                                                                                                                                    
2937 
2938 #endif // !PRODUCT                                                                                                                   
2939 
2940 #if INCLUDE_JVMCI                                                                                                                    
2941 void nmethod::clear_jvmci_installed_code() {                                                                                         
2942   assert_locked_or_safepoint(Patching_lock);                                                                                         
2943   if (_jvmci_installed_code != NULL) {                                                                                               
2944     JNIHandles::destroy_weak_global(_jvmci_installed_code);                                                                          
2945     _jvmci_installed_code = NULL;                                                                                                    
2946   }                                                                                                                                  
2947 }                                                                                                                                    
2948 
2949 void nmethod::clear_speculation_log() {                                                                                              
2950   assert_locked_or_safepoint(Patching_lock);                                                                                         
2951   if (_speculation_log != NULL) {                                                                                                    
2952     JNIHandles::destroy_weak_global(_speculation_log);                                                                               
2953     _speculation_log = NULL;                                                                                                         
2954   }                                                                                                                                  
2955 }                                                                                                                                    
2956 
2957 void nmethod::maybe_invalidate_installed_code() {                                                                                    
2958   if (!is_compiled_by_jvmci()) {                                                                                                     
2959     return;                                                                                                                          
2960   }                                                                                                                                  
2961 
2962   assert(Patching_lock->is_locked() ||                                                                                               
2963          SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency");                               
2964   oop installed_code = JNIHandles::resolve(_jvmci_installed_code);                                                                   
2965   if (installed_code != NULL) {                                                                                                      
2966     // Update the values in the InstalledCode instance if it still refers to this nmethod                                            
2967     nmethod* nm = (nmethod*)InstalledCode::address(installed_code);                                                                  
2968     if (nm == this) {                                                                                                                
2969       if (!is_alive() || is_unloading()) {                                                                                           
2970         // Break the link between nmethod and InstalledCode such that the nmethod                                                    
2971         // can subsequently be flushed safely.  The link must be maintained while                                                    
2972         // the method could have live activations since invalidateInstalledCode                                                      
2973         // might want to invalidate all existing activations.                                                                        
2974         InstalledCode::set_address(installed_code, 0);                                                                               
2975         InstalledCode::set_entryPoint(installed_code, 0);                                                                            
2976       } else if (is_not_entrant()) {                                                                                                 
2977         // Remove the entry point so any invocation will fail but keep                                                               
2978         // the address link around that so that existing activations can                                                             
2979         // be invalidated.                                                                                                           
2980         InstalledCode::set_entryPoint(installed_code, 0);                                                                            
2981       }                                                                                                                              
2982     }                                                                                                                                
2983   }                                                                                                                                  
2984   if (!is_alive() || is_unloading()) {                                                                                               
2985     // Clear these out after the nmethod has been unregistered and any                                                               
2986     // updates to the InstalledCode instance have been performed.                                                                    
2987     clear_jvmci_installed_code();                                                                                                    
2988     clear_speculation_log();                                                                                                         
2989   }                                                                                                                                  
2990 }                                                                                                                                    
2991 
2992 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) {                                                               
2993   if (installedCode() == NULL) {                                                                                                     
2994     THROW(vmSymbols::java_lang_NullPointerException());                                                                              
2995   }                                                                                                                                  
2996   jlong nativeMethod = InstalledCode::address(installedCode);                                                                        
2997   nmethod* nm = (nmethod*)nativeMethod;                                                                                              
2998   if (nm == NULL) {                                                                                                                  
2999     // Nothing to do                                                                                                                 
3000     return;                                                                                                                          
3001   }                                                                                                                                  
3002 
3003   nmethodLocker nml(nm);                                                                                                             
3004 #ifdef ASSERT                                                                                                                        
3005   {                                                                                                                                  
3006     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);                                                                
3007     // This relationship can only be checked safely under a lock                                                                     
3008     assert(!nm->is_alive() || nm->is_unloading() || nm->jvmci_installed_code() == installedCode(), "sanity check");                  
3009   }                                                                                                                                  
3010 #endif                                                                                                                               
3011 
3012   if (nm->is_alive()) {                                                                                                              
3013     // Invalidating the InstalledCode means we want the nmethod                                                                      
3014     // to be deoptimized.                                                                                                            
3015     nm->mark_for_deoptimization();                                                                                                   
3016     VM_Deoptimize op;                                                                                                                
3017     VMThread::execute(&op);                                                                                                          
3018   }                                                                                                                                  
3019 
3020   // Multiple threads could reach this point so we now need to                                                                       
3021   // lock and re-check the link to the nmethod so that only one                                                                      
3022   // thread clears it.                                                                                                               
3023   MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);                                                                  
3024   if (InstalledCode::address(installedCode) == nativeMethod) {                                                                       
3025       InstalledCode::set_address(installedCode, 0);                                                                                  
3026   }                                                                                                                                  
3027 }                                                                                                                                    
3028 
3029 oop nmethod::jvmci_installed_code() {                                                                                                
3030   return JNIHandles::resolve(_jvmci_installed_code);                                                                                 
3031 }                                                                                                                                    
3032 
3033 oop nmethod::speculation_log() {                                                                                                     
3034   return JNIHandles::resolve(_speculation_log);                                                                                      
3035 }                                                                                                                                    
3036 
3037 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) const {                                                           
3038   if (!this->is_compiled_by_jvmci()) {                                                                                               
3039     return NULL;                                                                                                                     
3040   }                                                                                                                                  
3041   oop installed_code = JNIHandles::resolve(_jvmci_installed_code);                                                                   
3042   if (installed_code != NULL) {                                                                                                      
3043     oop installed_code_name = NULL;                                                                                                  
3044     if (installed_code->is_a(InstalledCode::klass())) {                                                                              
3045       installed_code_name = InstalledCode::name(installed_code);                                                                     
3046     }                                                                                                                                
3047     if (installed_code_name != NULL) {                                                                                               
3048       return java_lang_String::as_utf8_string(installed_code_name, buf, (int)buflen);                                                
3049     }                                                                                                                                
3050   }                                                                                                                                  
3051   return NULL;                                                                                                                       
3052 }                                                                                                                                    
3053 #endif                                                                                                                               
--- EOF ---