1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/cppVtables.hpp"
  27 #include "cds/metaspaceShared.hpp"
  28 #include "classfile/classLoaderDataGraph.hpp"
  29 #include "classfile/metadataOnStackMark.hpp"
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "code/codeCache.hpp"
  34 #include "code/debugInfoRec.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "gc/shared/collectedHeap.inline.hpp"
  37 #include "interpreter/bytecodeStream.hpp"
  38 #include "interpreter/bytecodeTracer.hpp"
  39 #include "interpreter/bytecodes.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "logging/log.hpp"
  43 #include "logging/logTag.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "memory/allocation.inline.hpp"
  46 #include "memory/metadataFactory.hpp"
  47 #include "memory/metaspaceClosure.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/constMethod.hpp"
  52 #include "oops/constantPool.hpp"
  53 #include "oops/klass.inline.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/methodData.hpp"
  56 #include "oops/objArrayKlass.hpp"
  57 #include "oops/objArrayOop.inline.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "oops/symbol.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "runtime/arguments.hpp"
  63 #include "runtime/atomic.hpp"
  64 #include "runtime/frame.inline.hpp"
  65 #include "runtime/handles.inline.hpp"
  66 #include "runtime/init.hpp"
  67 #include "runtime/orderAccess.hpp"
  68 #include "runtime/relocator.hpp"
  69 #include "runtime/safepointVerifiers.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/signature.hpp"
  72 #include "runtime/vm_version.hpp"
  73 #include "services/memTracker.hpp"
  74 #include "utilities/align.hpp"
  75 #include "utilities/quickSort.hpp"
  76 #include "utilities/vmError.hpp"
  77 #include "utilities/xmlstream.hpp"
  78 
  79 // Implementation of Method
  80 
  81 Method* Method::allocate(ClassLoaderData* loader_data,
  82                          int byte_code_size,
  83                          AccessFlags access_flags,
  84                          InlineTableSizes* sizes,
  85                          ConstMethod::MethodType method_type,
  86                          TRAPS) {
  87   assert(!access_flags.is_native() || byte_code_size == 0,
  88          "native methods should not contain byte codes");
  89   ConstMethod* cm = ConstMethod::allocate(loader_data,
  90                                           byte_code_size,
  91                                           sizes,
  92                                           method_type,
  93                                           CHECK_NULL);
  94   int size = Method::size(access_flags.is_native());
  95   return new (loader_data, size, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags);
  96 }
  97 
  98 Method::Method(ConstMethod* xconst, AccessFlags access_flags) {
  99   NoSafepointVerifier no_safepoint;
 100   set_constMethod(xconst);
 101   set_access_flags(access_flags);
 102   set_intrinsic_id(vmIntrinsics::_none);
 103   set_force_inline(false);
 104   set_hidden(false);
 105   set_dont_inline(false);
 106   set_has_injected_profile(false);
 107   set_method_data(NULL);
 108   clear_method_counters();
 109   set_vtable_index(Method::garbage_vtable_index);
 110 
 111   // Fix and bury in Method*
 112   set_interpreter_entry(NULL); // sets i2i entry and from_int
 113   set_adapter_entry(NULL);
 114   Method::clear_code(); // from_c/from_i get set to c2i/i2i
 115 
 116   if (access_flags.is_native()) {
 117     clear_native_function();
 118     set_signature_handler(NULL);
 119   }
 120 
 121   NOT_PRODUCT(set_compiled_invocation_count(0);)
 122 }
 123 
 124 // Release Method*.  The nmethod will be gone when we get here because
 125 // we've walked the code cache.
 126 void Method::deallocate_contents(ClassLoaderData* loader_data) {
 127   MetadataFactory::free_metadata(loader_data, constMethod());
 128   set_constMethod(NULL);
 129   MetadataFactory::free_metadata(loader_data, method_data());
 130   set_method_data(NULL);
 131   MetadataFactory::free_metadata(loader_data, method_counters());
 132   clear_method_counters();
 133   // The nmethod will be gone when we get here.
 134   if (code() != NULL) _code = NULL;
 135 }
 136 
 137 void Method::release_C_heap_structures() {
 138   if (method_data()) {
 139 #if INCLUDE_JVMCI
 140     FailedSpeculation::free_failed_speculations(method_data()->get_failed_speculations_address());
 141 #endif
 142     // Destroy MethodData
 143     method_data()->~MethodData();
 144   }
 145 }
 146 
 147 address Method::get_i2c_entry() {
 148   assert(adapter() != NULL, "must have");
 149   return adapter()->get_i2c_entry();
 150 }
 151 
 152 address Method::get_c2i_entry() {
 153   assert(adapter() != NULL, "must have");
 154   return adapter()->get_c2i_entry();
 155 }
 156 
 157 address Method::get_c2i_unverified_entry() {
 158   assert(adapter() != NULL, "must have");
 159   return adapter()->get_c2i_unverified_entry();
 160 }
 161 
 162 address Method::get_c2i_no_clinit_check_entry() {
 163   assert(VM_Version::supports_fast_class_init_checks(), "");
 164   assert(adapter() != NULL, "must have");
 165   return adapter()->get_c2i_no_clinit_check_entry();
 166 }
 167 
 168 char* Method::name_and_sig_as_C_string() const {
 169   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
 170 }
 171 
 172 char* Method::name_and_sig_as_C_string(char* buf, int size) const {
 173   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
 174 }
 175 
 176 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
 177   const char* klass_name = klass->external_name();
 178   int klass_name_len  = (int)strlen(klass_name);
 179   int method_name_len = method_name->utf8_length();
 180   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
 181   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
 182   strcpy(dest, klass_name);
 183   dest[klass_name_len] = '.';
 184   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
 185   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
 186   dest[len] = 0;
 187   return dest;
 188 }
 189 
 190 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
 191   Symbol* klass_name = klass->name();
 192   klass_name->as_klass_external_name(buf, size);
 193   int len = (int)strlen(buf);
 194 
 195   if (len < size - 1) {
 196     buf[len++] = '.';
 197 
 198     method_name->as_C_string(&(buf[len]), size - len);
 199     len = (int)strlen(buf);
 200 
 201     signature->as_C_string(&(buf[len]), size - len);
 202   }
 203 
 204   return buf;
 205 }
 206 
 207 const char* Method::external_name() const {
 208   return external_name(constants()->pool_holder(), name(), signature());
 209 }
 210 
 211 void Method::print_external_name(outputStream *os) const {
 212   print_external_name(os, constants()->pool_holder(), name(), signature());
 213 }
 214 
 215 const char* Method::external_name(Klass* klass, Symbol* method_name, Symbol* signature) {
 216   stringStream ss;
 217   print_external_name(&ss, klass, method_name, signature);
 218   return ss.as_string();
 219 }
 220 
 221 void Method::print_external_name(outputStream *os, Klass* klass, Symbol* method_name, Symbol* signature) {
 222   signature->print_as_signature_external_return_type(os);
 223   os->print(" %s.%s(", klass->external_name(), method_name->as_C_string());
 224   signature->print_as_signature_external_parameters(os);
 225   os->print(")");
 226 }
 227 
 228 int Method::fast_exception_handler_bci_for(const methodHandle& mh, Klass* ex_klass, int throw_bci, TRAPS) {
 229   if (log_is_enabled(Debug, exceptions)) {
 230     ResourceMark rm(THREAD);
 231     log_debug(exceptions)("Looking for catch handler for exception of type \"%s\" in method \"%s\"",
 232                           ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string());
 233   }
 234   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 235   // access exception table
 236   ExceptionTable table(mh());
 237   int length = table.length();
 238   // iterate through all entries sequentially
 239   constantPoolHandle pool(THREAD, mh->constants());
 240   for (int i = 0; i < length; i ++) {
 241     //reacquire the table in case a GC happened
 242     ExceptionTable table(mh());
 243     int beg_bci = table.start_pc(i);
 244     int end_bci = table.end_pc(i);
 245     assert(beg_bci <= end_bci, "inconsistent exception table");
 246     log_debug(exceptions)("  - checking exception table entry for BCI %d to %d",
 247                          beg_bci, end_bci);
 248 
 249     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 250       // exception handler bci range covers throw_bci => investigate further
 251       log_debug(exceptions)("    - entry covers throw point BCI %d", throw_bci);
 252 
 253       int handler_bci = table.handler_pc(i);
 254       int klass_index = table.catch_type_index(i);
 255       if (klass_index == 0) {
 256         if (log_is_enabled(Info, exceptions)) {
 257           ResourceMark rm(THREAD);
 258           log_info(exceptions)("Found catch-all handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 259                                ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 260         }
 261         return handler_bci;
 262       } else if (ex_klass == NULL) {
 263         // Is this even possible?
 264         if (log_is_enabled(Info, exceptions)) {
 265           ResourceMark rm(THREAD);
 266           log_info(exceptions)("NULL exception class is implicitly caught by handler in method \"%s\" at BCI: %d",
 267                                mh()->name()->as_C_string(), handler_bci);
 268         }
 269         return handler_bci;
 270       } else {
 271         if (log_is_enabled(Debug, exceptions)) {
 272           ResourceMark rm(THREAD);
 273           log_debug(exceptions)("    - resolving catch type \"%s\"",
 274                                pool->klass_name_at(klass_index)->as_C_string());
 275         }
 276         // we know the exception class => get the constraint class
 277         // this may require loading of the constraint class; if verification
 278         // fails or some other exception occurs, return handler_bci
 279         Klass* k = pool->klass_at(klass_index, THREAD);
 280         if (HAS_PENDING_EXCEPTION) {
 281           if (log_is_enabled(Debug, exceptions)) {
 282             ResourceMark rm(THREAD);
 283             log_debug(exceptions)("    - exception \"%s\" occurred resolving catch type",
 284                                  PENDING_EXCEPTION->klass()->external_name());
 285           }
 286           return handler_bci;
 287         }
 288         assert(k != NULL, "klass not loaded");
 289         if (ex_klass->is_subtype_of(k)) {
 290           if (log_is_enabled(Info, exceptions)) {
 291             ResourceMark rm(THREAD);
 292             log_info(exceptions)("Found matching handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 293                                  ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 294           }
 295           return handler_bci;
 296         }
 297       }
 298     }
 299   }
 300 
 301   if (log_is_enabled(Debug, exceptions)) {
 302     ResourceMark rm(THREAD);
 303     log_debug(exceptions)("No catch handler found for exception of type \"%s\" in method \"%s\"",
 304                           ex_klass->external_name(), mh->name()->as_C_string());
 305   }
 306 
 307   return -1;
 308 }
 309 
 310 void Method::mask_for(int bci, InterpreterOopMap* mask) {
 311   methodHandle h_this(Thread::current(), this);
 312   // Only GC uses the OopMapCache during thread stack root scanning
 313   // any other uses generate an oopmap but do not save it in the cache.
 314   if (Universe::heap()->is_gc_active()) {
 315     method_holder()->mask_for(h_this, bci, mask);
 316   } else {
 317     OopMapCache::compute_one_oop_map(h_this, bci, mask);
 318   }
 319   return;
 320 }
 321 
 322 
 323 int Method::bci_from(address bcp) const {
 324   if (is_native() && bcp == 0) {
 325     return 0;
 326   }
 327   // Do not have a ResourceMark here because AsyncGetCallTrace stack walking code
 328   // may call this after interrupting a nested ResourceMark.
 329   assert(is_native() && bcp == code_base() || contains(bcp) || VMError::is_error_reported(),
 330          "bcp doesn't belong to this method. bcp: " INTPTR_FORMAT, p2i(bcp));
 331 
 332   return bcp - code_base();
 333 }
 334 
 335 
 336 int Method::validate_bci(int bci) const {
 337   return (bci == 0 || bci < code_size()) ? bci : -1;
 338 }
 339 
 340 // Return bci if it appears to be a valid bcp
 341 // Return -1 otherwise.
 342 // Used by profiling code, when invalid data is a possibility.
 343 // The caller is responsible for validating the Method* itself.
 344 int Method::validate_bci_from_bcp(address bcp) const {
 345   // keep bci as -1 if not a valid bci
 346   int bci = -1;
 347   if (bcp == 0 || bcp == code_base()) {
 348     // code_size() may return 0 and we allow 0 here
 349     // the method may be native
 350     bci = 0;
 351   } else if (contains(bcp)) {
 352     bci = bcp - code_base();
 353   }
 354   // Assert that if we have dodged any asserts, bci is negative.
 355   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 356   return bci;
 357 }
 358 
 359 address Method::bcp_from(int bci) const {
 360   assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()),
 361          "illegal bci: %d for %s method", bci, is_native() ? "native" : "non-native");
 362   address bcp = code_base() + bci;
 363   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 364   return bcp;
 365 }
 366 
 367 address Method::bcp_from(address bcp) const {
 368   if (is_native() && bcp == NULL) {
 369     return code_base();
 370   } else {
 371     return bcp;
 372   }
 373 }
 374 
 375 int Method::size(bool is_native) {
 376   // If native, then include pointers for native_function and signature_handler
 377   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 378   int extra_words = align_up(extra_bytes, BytesPerWord) / BytesPerWord;
 379   return align_metadata_size(header_size() + extra_words);
 380 }
 381 
 382 Symbol* Method::klass_name() const {
 383   return method_holder()->name();
 384 }
 385 
 386 void Method::metaspace_pointers_do(MetaspaceClosure* it) {
 387   log_trace(cds)("Iter(Method): %p", this);
 388 
 389   if (!method_holder()->is_rewritten()) {
 390     it->push(&_constMethod, MetaspaceClosure::_writable);
 391   } else {
 392     it->push(&_constMethod);
 393   }
 394   it->push(&_method_data);
 395   it->push(&_method_counters);
 396 }
 397 
 398 // Attempt to return method to original state.  Clear any pointers
 399 // (to objects outside the shared spaces).  We won't be able to predict
 400 // where they should point in a new JVM.  Further initialize some
 401 // entries now in order allow them to be write protected later.
 402 
 403 void Method::remove_unshareable_info() {
 404   unlink_method();
 405   JFR_ONLY(REMOVE_METHOD_ID(this);)
 406 }
 407 
 408 void Method::set_vtable_index(int index) {
 409   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 410     // At runtime initialize_vtable is rerun as part of link_class_impl()
 411     // for a shared class loaded by the non-boot loader to obtain the loader
 412     // constraints based on the runtime classloaders' context.
 413     return; // don't write into the shared class
 414   } else {
 415     _vtable_index = index;
 416   }
 417 }
 418 
 419 void Method::set_itable_index(int index) {
 420   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 421     // At runtime initialize_itable is rerun as part of link_class_impl()
 422     // for a shared class loaded by the non-boot loader to obtain the loader
 423     // constraints based on the runtime classloaders' context. The dumptime
 424     // itable index should be the same as the runtime index.
 425     assert(_vtable_index == itable_index_max - index,
 426            "archived itable index is different from runtime index");
 427     return; // don’t write into the shared class
 428   } else {
 429     _vtable_index = itable_index_max - index;
 430   }
 431   assert(valid_itable_index(), "");
 432 }
 433 
 434 // The RegisterNatives call being attempted tried to register with a method that
 435 // is not native.  Ask JVM TI what prefixes have been specified.  Then check
 436 // to see if the native method is now wrapped with the prefixes.  See the
 437 // SetNativeMethodPrefix(es) functions in the JVM TI Spec for details.
 438 static Method* find_prefixed_native(Klass* k, Symbol* name, Symbol* signature, TRAPS) {
 439 #if INCLUDE_JVMTI
 440   ResourceMark rm(THREAD);
 441   Method* method;
 442   int name_len = name->utf8_length();
 443   char* name_str = name->as_utf8();
 444   int prefix_count;
 445   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
 446   for (int i = 0; i < prefix_count; i++) {
 447     char* prefix = prefixes[i];
 448     int prefix_len = (int)strlen(prefix);
 449 
 450     // try adding this prefix to the method name and see if it matches another method name
 451     int trial_len = name_len + prefix_len;
 452     char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
 453     strcpy(trial_name_str, prefix);
 454     strcat(trial_name_str, name_str);
 455     TempNewSymbol trial_name = SymbolTable::probe(trial_name_str, trial_len);
 456     if (trial_name == NULL) {
 457       continue; // no such symbol, so this prefix wasn't used, try the next prefix
 458     }
 459     method = k->lookup_method(trial_name, signature);
 460     if (method == NULL) {
 461       continue; // signature doesn't match, try the next prefix
 462     }
 463     if (method->is_native()) {
 464       method->set_is_prefixed_native();
 465       return method; // wahoo, we found a prefixed version of the method, return it
 466     }
 467     // found as non-native, so prefix is good, add it, probably just need more prefixes
 468     name_len = trial_len;
 469     name_str = trial_name_str;
 470   }
 471 #endif // INCLUDE_JVMTI
 472   return NULL; // not found
 473 }
 474 
 475 bool Method::register_native(Klass* k, Symbol* name, Symbol* signature, address entry, TRAPS) {
 476   Method* method = k->lookup_method(name, signature);
 477   if (method == NULL) {
 478     ResourceMark rm(THREAD);
 479     stringStream st;
 480     st.print("Method '");
 481     print_external_name(&st, k, name, signature);
 482     st.print("' name or signature does not match");
 483     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 484   }
 485   if (!method->is_native()) {
 486     // trying to register to a non-native method, see if a JVM TI agent has added prefix(es)
 487     method = find_prefixed_native(k, name, signature, THREAD);
 488     if (method == NULL) {
 489       ResourceMark rm(THREAD);
 490       stringStream st;
 491       st.print("Method '");
 492       print_external_name(&st, k, name, signature);
 493       st.print("' is not declared as native");
 494       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 495     }
 496   }
 497 
 498   if (entry != NULL) {
 499     method->set_native_function(entry, native_bind_event_is_interesting);
 500   } else {
 501     method->clear_native_function();
 502   }
 503   if (log_is_enabled(Debug, jni, resolve)) {
 504     ResourceMark rm(THREAD);
 505     log_debug(jni, resolve)("[Registering JNI native method %s.%s]",
 506                             method->method_holder()->external_name(),
 507                             method->name()->as_C_string());
 508   }
 509   return true;
 510 }
 511 
 512 bool Method::was_executed_more_than(int n) {
 513   // Invocation counter is reset when the Method* is compiled.
 514   // If the method has compiled code we therefore assume it has
 515   // be excuted more than n times.
 516   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 517     // interpreter doesn't bump invocation counter of trivial methods
 518     // compiler does not bump invocation counter of compiled methods
 519     return true;
 520   }
 521   else if ((method_counters() != NULL &&
 522             method_counters()->invocation_counter()->carry()) ||
 523            (method_data() != NULL &&
 524             method_data()->invocation_counter()->carry())) {
 525     // The carry bit is set when the counter overflows and causes
 526     // a compilation to occur.  We don't know how many times
 527     // the counter has been reset, so we simply assume it has
 528     // been executed more than n times.
 529     return true;
 530   } else {
 531     return invocation_count() > n;
 532   }
 533 }
 534 
 535 void Method::print_invocation_count() {
 536   //---<  compose+print method return type, klass, name, and signature  >---
 537   if (is_static()) tty->print("static ");
 538   if (is_final()) tty->print("final ");
 539   if (is_synchronized()) tty->print("synchronized ");
 540   if (is_native()) tty->print("native ");
 541   tty->print("%s::", method_holder()->external_name());
 542   name()->print_symbol_on(tty);
 543   signature()->print_symbol_on(tty);
 544 
 545   if (WizardMode) {
 546     // dump the size of the byte codes
 547     tty->print(" {%d}", code_size());
 548   }
 549   tty->cr();
 550 
 551   // Counting based on signed int counters tends to overflow with
 552   // longer-running workloads on fast machines. The counters under
 553   // consideration here, however, are limited in range by counting
 554   // logic. See InvocationCounter:count_limit for example.
 555   // No "overflow precautions" need to be implemented here.
 556   tty->print_cr ("  interpreter_invocation_count: " INT32_FORMAT_W(11), interpreter_invocation_count());
 557   tty->print_cr ("  invocation_counter:           " INT32_FORMAT_W(11), invocation_count());
 558   tty->print_cr ("  backedge_counter:             " INT32_FORMAT_W(11), backedge_count());
 559 
 560   if (method_data() != NULL) {
 561     tty->print_cr ("  decompile_count:              " UINT32_FORMAT_W(11), method_data()->decompile_count());
 562   }
 563 
 564 #ifndef PRODUCT
 565   if (CountCompiledCalls) {
 566     tty->print_cr ("  compiled_invocation_count:    " INT64_FORMAT_W(11), compiled_invocation_count());
 567   }
 568 #endif
 569 }
 570 
 571 // Build a MethodData* object to hold information about this method
 572 // collected in the interpreter.
 573 void Method::build_interpreter_method_data(const methodHandle& method, TRAPS) {
 574   // Do not profile the method if metaspace has hit an OOM previously
 575   // allocating profiling data. Callers clear pending exception so don't
 576   // add one here.
 577   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 578     return;
 579   }
 580 
 581   // Grab a lock here to prevent multiple
 582   // MethodData*s from being created.
 583   MutexLocker ml(THREAD, MethodData_lock);
 584   if (method->method_data() == NULL) {
 585     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 586     MethodData* method_data = MethodData::allocate(loader_data, method, THREAD);
 587     if (HAS_PENDING_EXCEPTION) {
 588       CompileBroker::log_metaspace_failure();
 589       ClassLoaderDataGraph::set_metaspace_oom(true);
 590       return;   // return the exception (which is cleared)
 591     }
 592 
 593     method->set_method_data(method_data);
 594     if (PrintMethodData && (Verbose || WizardMode)) {
 595       ResourceMark rm(THREAD);
 596       tty->print("build_interpreter_method_data for ");
 597       method->print_name(tty);
 598       tty->cr();
 599       // At the end of the run, the MDO, full of data, will be dumped.
 600     }
 601   }
 602 }
 603 
 604 MethodCounters* Method::build_method_counters(Thread* current, Method* m) {
 605   // Do not profile the method if metaspace has hit an OOM previously
 606   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 607     return NULL;
 608   }
 609 
 610   methodHandle mh(current, m);
 611   MethodCounters* counters;
 612   if (current->is_Java_thread()) {
 613     JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 614     // Use the TRAPS version for a JavaThread so it will adjust the GC threshold
 615     // if needed.
 616     counters = MethodCounters::allocate_with_exception(mh, THREAD);
 617     if (HAS_PENDING_EXCEPTION) {
 618       CLEAR_PENDING_EXCEPTION;
 619     }
 620   } else {
 621     // Call metaspace allocation that doesn't throw exception if the
 622     // current thread isn't a JavaThread, ie. the VMThread.
 623     counters = MethodCounters::allocate_no_exception(mh);
 624   }
 625 
 626   if (counters == NULL) {
 627     CompileBroker::log_metaspace_failure();
 628     ClassLoaderDataGraph::set_metaspace_oom(true);
 629     return NULL;
 630   }
 631 
 632   if (!mh->init_method_counters(counters)) {
 633     MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters);
 634   }
 635 
 636   if (LogTouchedMethods) {
 637     mh->log_touched(current);
 638   }
 639 
 640   return mh->method_counters();
 641 }
 642 
 643 bool Method::init_method_counters(MethodCounters* counters) {
 644   // Try to install a pointer to MethodCounters, return true on success.
 645   return Atomic::replace_if_null(&_method_counters, counters);
 646 }
 647 
 648 int Method::extra_stack_words() {
 649   // not an inline function, to avoid a header dependency on Interpreter
 650   return extra_stack_entries() * Interpreter::stackElementSize;
 651 }
 652 
 653 // Derive size of parameters, return type, and fingerprint,
 654 // all in one pass, which is run at load time.
 655 // We need the first two, and might as well grab the third.
 656 void Method::compute_from_signature(Symbol* sig) {
 657   // At this point, since we are scanning the signature,
 658   // we might as well compute the whole fingerprint.
 659   Fingerprinter fp(sig, is_static());
 660   set_size_of_parameters(fp.size_of_parameters());
 661   constMethod()->set_result_type(fp.return_type());
 662   constMethod()->set_fingerprint(fp.fingerprint());
 663 }
 664 
 665 bool Method::is_vanilla_constructor() const {
 666   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 667   // which only calls the superclass vanilla constructor and possibly does stores of
 668   // zero constants to local fields:
 669   //
 670   //   aload_0
 671   //   invokespecial
 672   //   indexbyte1
 673   //   indexbyte2
 674   //
 675   // followed by an (optional) sequence of:
 676   //
 677   //   aload_0
 678   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 679   //   putfield
 680   //   indexbyte1
 681   //   indexbyte2
 682   //
 683   // followed by:
 684   //
 685   //   return
 686 
 687   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 688   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 689   int size = code_size();
 690   // Check if size match
 691   if (size == 0 || size % 5 != 0) return false;
 692   address cb = code_base();
 693   int last = size - 1;
 694   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 695     // Does not call superclass default constructor
 696     return false;
 697   }
 698   // Check optional sequence
 699   for (int i = 4; i < last; i += 5) {
 700     if (cb[i] != Bytecodes::_aload_0) return false;
 701     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 702     if (cb[i+2] != Bytecodes::_putfield) return false;
 703   }
 704   return true;
 705 }
 706 
 707 
 708 bool Method::compute_has_loops_flag() {
 709   BytecodeStream bcs(methodHandle(Thread::current(), this));
 710   Bytecodes::Code bc;
 711 
 712   while ((bc = bcs.next()) >= 0) {
 713     switch (bc) {
 714       case Bytecodes::_ifeq:
 715       case Bytecodes::_ifnull:
 716       case Bytecodes::_iflt:
 717       case Bytecodes::_ifle:
 718       case Bytecodes::_ifne:
 719       case Bytecodes::_ifnonnull:
 720       case Bytecodes::_ifgt:
 721       case Bytecodes::_ifge:
 722       case Bytecodes::_if_icmpeq:
 723       case Bytecodes::_if_icmpne:
 724       case Bytecodes::_if_icmplt:
 725       case Bytecodes::_if_icmpgt:
 726       case Bytecodes::_if_icmple:
 727       case Bytecodes::_if_icmpge:
 728       case Bytecodes::_if_acmpeq:
 729       case Bytecodes::_if_acmpne:
 730       case Bytecodes::_goto:
 731       case Bytecodes::_jsr:
 732         if (bcs.dest() < bcs.next_bci()) _access_flags.set_has_loops();
 733         break;
 734 
 735       case Bytecodes::_goto_w:
 736       case Bytecodes::_jsr_w:
 737         if (bcs.dest_w() < bcs.next_bci()) _access_flags.set_has_loops();
 738         break;
 739 
 740       case Bytecodes::_lookupswitch: {
 741         Bytecode_lookupswitch lookupswitch(this, bcs.bcp());
 742         if (lookupswitch.default_offset() < 0) {
 743           _access_flags.set_has_loops();
 744         } else {
 745           for (int i = 0; i < lookupswitch.number_of_pairs(); ++i) {
 746             LookupswitchPair pair = lookupswitch.pair_at(i);
 747             if (pair.offset() < 0) {
 748               _access_flags.set_has_loops();
 749               break;
 750             }
 751           }
 752         }
 753         break;
 754       }
 755       case Bytecodes::_tableswitch: {
 756         Bytecode_tableswitch tableswitch(this, bcs.bcp());
 757         if (tableswitch.default_offset() < 0) {
 758           _access_flags.set_has_loops();
 759         } else {
 760           for (int i = 0; i < tableswitch.length(); ++i) {
 761             if (tableswitch.dest_offset_at(i) < 0) {
 762               _access_flags.set_has_loops();
 763             }
 764           }
 765         }
 766         break;
 767       }
 768       default:
 769         break;
 770     }
 771   }
 772   _access_flags.set_loops_flag_init();
 773   return _access_flags.has_loops();
 774 }
 775 
 776 bool Method::is_final_method(AccessFlags class_access_flags) const {
 777   // or "does_not_require_vtable_entry"
 778   // default method or overpass can occur, is not final (reuses vtable entry)
 779   // private methods in classes get vtable entries for backward class compatibility.
 780   if (is_overpass() || is_default_method())  return false;
 781   return is_final() || class_access_flags.is_final();
 782 }
 783 
 784 bool Method::is_final_method() const {
 785   return is_final_method(method_holder()->access_flags());
 786 }
 787 
 788 bool Method::is_default_method() const {
 789   if (method_holder() != NULL &&
 790       method_holder()->is_interface() &&
 791       !is_abstract() && !is_private()) {
 792     return true;
 793   } else {
 794     return false;
 795   }
 796 }
 797 
 798 bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
 799   if (is_final_method(class_access_flags))  return true;
 800 #ifdef ASSERT
 801   ResourceMark rm;
 802   bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
 803   if (class_access_flags.is_interface()) {
 804       assert(is_nonv == is_static() || is_nonv == is_private(),
 805              "nonvirtual unexpected for non-static, non-private: %s",
 806              name_and_sig_as_C_string());
 807   }
 808 #endif
 809   assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
 810   return vtable_index() == nonvirtual_vtable_index;
 811 }
 812 
 813 bool Method::can_be_statically_bound() const {
 814   return can_be_statically_bound(method_holder()->access_flags());
 815 }
 816 
 817 bool Method::can_be_statically_bound(InstanceKlass* context) const {
 818   return (method_holder() == context) && can_be_statically_bound();
 819 }
 820 
 821 /**
 822  *  Returns false if this is one of specially treated methods for
 823  *  which we have to provide stack trace in throw in compiled code.
 824  *  Returns true otherwise.
 825  */
 826 bool Method::can_omit_stack_trace() {
 827   if (klass_name() == vmSymbols::sun_invoke_util_ValueConversions()) {
 828     return false; // All methods in sun.invoke.util.ValueConversions
 829   }
 830   return true;
 831 }
 832 
 833 bool Method::is_accessor() const {
 834   return is_getter() || is_setter();
 835 }
 836 
 837 bool Method::is_getter() const {
 838   if (code_size() != 5) return false;
 839   if (size_of_parameters() != 1) return false;
 840   if (java_code_at(0) != Bytecodes::_aload_0)  return false;
 841   if (java_code_at(1) != Bytecodes::_getfield) return false;
 842   switch (java_code_at(4)) {
 843     case Bytecodes::_ireturn:
 844     case Bytecodes::_lreturn:
 845     case Bytecodes::_freturn:
 846     case Bytecodes::_dreturn:
 847     case Bytecodes::_areturn:
 848       break;
 849     default:
 850       return false;
 851   }
 852   return true;
 853 }
 854 
 855 bool Method::is_setter() const {
 856   if (code_size() != 6) return false;
 857   if (java_code_at(0) != Bytecodes::_aload_0) return false;
 858   switch (java_code_at(1)) {
 859     case Bytecodes::_iload_1:
 860     case Bytecodes::_aload_1:
 861     case Bytecodes::_fload_1:
 862       if (size_of_parameters() != 2) return false;
 863       break;
 864     case Bytecodes::_dload_1:
 865     case Bytecodes::_lload_1:
 866       if (size_of_parameters() != 3) return false;
 867       break;
 868     default:
 869       return false;
 870   }
 871   if (java_code_at(2) != Bytecodes::_putfield) return false;
 872   if (java_code_at(5) != Bytecodes::_return)   return false;
 873   return true;
 874 }
 875 
 876 bool Method::is_constant_getter() const {
 877   int last_index = code_size() - 1;
 878   // Check if the first 1-3 bytecodes are a constant push
 879   // and the last bytecode is a return.
 880   return (2 <= code_size() && code_size() <= 4 &&
 881           Bytecodes::is_const(java_code_at(0)) &&
 882           Bytecodes::length_for(java_code_at(0)) == last_index &&
 883           Bytecodes::is_return(java_code_at(last_index)));
 884 }
 885 
 886 bool Method::is_initializer() const {
 887   return is_object_initializer() || is_static_initializer();
 888 }
 889 
 890 bool Method::has_valid_initializer_flags() const {
 891   return (is_static() ||
 892           method_holder()->major_version() < 51);
 893 }
 894 
 895 bool Method::is_static_initializer() const {
 896   // For classfiles version 51 or greater, ensure that the clinit method is
 897   // static.  Non-static methods with the name "<clinit>" are not static
 898   // initializers. (older classfiles exempted for backward compatibility)
 899   return name() == vmSymbols::class_initializer_name() &&
 900          has_valid_initializer_flags();
 901 }
 902 
 903 bool Method::is_object_initializer() const {
 904    return name() == vmSymbols::object_initializer_name();
 905 }
 906 
 907 bool Method::needs_clinit_barrier() const {
 908   return is_static() && !method_holder()->is_initialized();
 909 }
 910 
 911 objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
 912   int length = method->checked_exceptions_length();
 913   if (length == 0) {  // common case
 914     return objArrayHandle(THREAD, Universe::the_empty_class_array());
 915   } else {
 916     methodHandle h_this(THREAD, method);
 917     objArrayOop m_oop = oopFactory::new_objArray(vmClasses::Class_klass(), length, CHECK_(objArrayHandle()));
 918     objArrayHandle mirrors (THREAD, m_oop);
 919     for (int i = 0; i < length; i++) {
 920       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 921       Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 922       if (log_is_enabled(Warning, exceptions) &&
 923           !k->is_subclass_of(vmClasses::Throwable_klass())) {
 924         ResourceMark rm(THREAD);
 925         log_warning(exceptions)(
 926           "Class %s in throws clause of method %s is not a subtype of class java.lang.Throwable",
 927           k->external_name(), method->external_name());
 928       }
 929       mirrors->obj_at_put(i, k->java_mirror());
 930     }
 931     return mirrors;
 932   }
 933 };
 934 
 935 
 936 int Method::line_number_from_bci(int bci) const {
 937   int best_bci  =  0;
 938   int best_line = -1;
 939   if (bci == SynchronizationEntryBCI) bci = 0;
 940   if (0 <= bci && bci < code_size() && has_linenumber_table()) {
 941     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 942     // Not necessarily sorted and not necessarily one-to-one.
 943     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 944     while (stream.read_pair()) {
 945       if (stream.bci() == bci) {
 946         // perfect match
 947         return stream.line();
 948       } else {
 949         // update best_bci/line
 950         if (stream.bci() < bci && stream.bci() >= best_bci) {
 951           best_bci  = stream.bci();
 952           best_line = stream.line();
 953         }
 954       }
 955     }
 956   }
 957   return best_line;
 958 }
 959 
 960 
 961 bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
 962   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 963     Thread *thread = Thread::current();
 964     Symbol* klass_name = constants()->klass_name_at(klass_index);
 965     Handle loader(thread, method_holder()->class_loader());
 966     Handle prot  (thread, method_holder()->protection_domain());
 967     return SystemDictionary::find_instance_klass(klass_name, loader, prot) != NULL;
 968   } else {
 969     return true;
 970   }
 971 }
 972 
 973 
 974 bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 975   int klass_index = constants()->klass_ref_index_at(refinfo_index);
 976   if (must_be_resolved) {
 977     // Make sure klass is resolved in constantpool.
 978     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 979   }
 980   return is_klass_loaded_by_klass_index(klass_index);
 981 }
 982 
 983 
 984 void Method::set_native_function(address function, bool post_event_flag) {
 985   assert(function != NULL, "use clear_native_function to unregister natives");
 986   assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
 987   address* native_function = native_function_addr();
 988 
 989   // We can see racers trying to place the same native function into place. Once
 990   // is plenty.
 991   address current = *native_function;
 992   if (current == function) return;
 993   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 994       function != NULL) {
 995     // native_method_throw_unsatisfied_link_error_entry() should only
 996     // be passed when post_event_flag is false.
 997     assert(function !=
 998       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 999       "post_event_flag mis-match");
1000 
1001     // post the bind event, and possible change the bind function
1002     JvmtiExport::post_native_method_bind(this, &function);
1003   }
1004   *native_function = function;
1005   // This function can be called more than once. We must make sure that we always
1006   // use the latest registered method -> check if a stub already has been generated.
1007   // If so, we have to make it not_entrant.
1008   CompiledMethod* nm = code(); // Put it into local variable to guard against concurrent updates
1009   if (nm != NULL) {
1010     nm->make_not_entrant();
1011   }
1012 }
1013 
1014 
1015 bool Method::has_native_function() const {
1016   if (is_method_handle_intrinsic())
1017     return false;  // special-cased in SharedRuntime::generate_native_wrapper
1018   address func = native_function();
1019   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1020 }
1021 
1022 
1023 void Method::clear_native_function() {
1024   // Note: is_method_handle_intrinsic() is allowed here.
1025   set_native_function(
1026     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
1027     !native_bind_event_is_interesting);
1028   this->unlink_code();
1029 }
1030 
1031 
1032 void Method::set_signature_handler(address handler) {
1033   address* signature_handler =  signature_handler_addr();
1034   *signature_handler = handler;
1035 }
1036 
1037 
1038 void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
1039   assert(reason != NULL, "must provide a reason");
1040   if (PrintCompilation && report) {
1041     ttyLocker ttyl;
1042     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
1043     if (comp_level == CompLevel_all) {
1044       tty->print("all levels ");
1045     } else {
1046       tty->print("level %d ", comp_level);
1047     }
1048     this->print_short_name(tty);
1049     int size = this->code_size();
1050     if (size > 0) {
1051       tty->print(" (%d bytes)", size);
1052     }
1053     if (reason != NULL) {
1054       tty->print("   %s", reason);
1055     }
1056     tty->cr();
1057   }
1058   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
1059     ttyLocker ttyl;
1060     xtty->begin_elem("make_not_compilable thread='" UINTX_FORMAT "' osr='%d' level='%d'",
1061                      os::current_thread_id(), is_osr, comp_level);
1062     if (reason != NULL) {
1063       xtty->print(" reason=\'%s\'", reason);
1064     }
1065     xtty->method(this);
1066     xtty->stamp();
1067     xtty->end_elem();
1068   }
1069 }
1070 
1071 bool Method::is_always_compilable() const {
1072   // Generated adapters must be compiled
1073   if (is_method_handle_intrinsic() && is_synthetic()) {
1074     assert(!is_not_c1_compilable(), "sanity check");
1075     assert(!is_not_c2_compilable(), "sanity check");
1076     return true;
1077   }
1078 
1079   return false;
1080 }
1081 
1082 bool Method::is_not_compilable(int comp_level) const {
1083   if (number_of_breakpoints() > 0)
1084     return true;
1085   if (is_always_compilable())
1086     return false;
1087   if (comp_level == CompLevel_any)
1088     return is_not_c1_compilable() && is_not_c2_compilable();
1089   if (is_c1_compile(comp_level))
1090     return is_not_c1_compilable();
1091   if (is_c2_compile(comp_level))
1092     return is_not_c2_compilable();
1093   return false;
1094 }
1095 
1096 // call this when compiler finds that this method is not compilable
1097 void Method::set_not_compilable(const char* reason, int comp_level, bool report) {
1098   if (is_always_compilable()) {
1099     // Don't mark a method which should be always compilable
1100     return;
1101   }
1102   print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
1103   if (comp_level == CompLevel_all) {
1104     set_not_c1_compilable();
1105     set_not_c2_compilable();
1106   } else {
1107     if (is_c1_compile(comp_level))
1108       set_not_c1_compilable();
1109     if (is_c2_compile(comp_level))
1110       set_not_c2_compilable();
1111   }
1112   assert(!CompilationPolicy::can_be_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1113 }
1114 
1115 bool Method::is_not_osr_compilable(int comp_level) const {
1116   if (is_not_compilable(comp_level))
1117     return true;
1118   if (comp_level == CompLevel_any)
1119     return is_not_c1_osr_compilable() && is_not_c2_osr_compilable();
1120   if (is_c1_compile(comp_level))
1121     return is_not_c1_osr_compilable();
1122   if (is_c2_compile(comp_level))
1123     return is_not_c2_osr_compilable();
1124   return false;
1125 }
1126 
1127 void Method::set_not_osr_compilable(const char* reason, int comp_level, bool report) {
1128   print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
1129   if (comp_level == CompLevel_all) {
1130     set_not_c1_osr_compilable();
1131     set_not_c2_osr_compilable();
1132   } else {
1133     if (is_c1_compile(comp_level))
1134       set_not_c1_osr_compilable();
1135     if (is_c2_compile(comp_level))
1136       set_not_c2_osr_compilable();
1137   }
1138   assert(!CompilationPolicy::can_be_osr_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1139 }
1140 
1141 // Revert to using the interpreter and clear out the nmethod
1142 void Method::clear_code() {
1143   // this may be NULL if c2i adapters have not been made yet
1144   // Only should happen at allocate time.
1145   if (adapter() == NULL) {
1146     _from_compiled_entry    = NULL;
1147   } else {
1148     _from_compiled_entry    = adapter()->get_c2i_entry();
1149   }
1150   OrderAccess::storestore();
1151   _from_interpreted_entry = _i2i_entry;
1152   OrderAccess::storestore();
1153   _code = NULL;
1154 }
1155 
1156 void Method::unlink_code(CompiledMethod *compare) {
1157   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1158   // We need to check if either the _code or _from_compiled_code_entry_point
1159   // refer to this nmethod because there is a race in setting these two fields
1160   // in Method* as seen in bugid 4947125.
1161   // If the vep() points to the zombie nmethod, the memory for the nmethod
1162   // could be flushed and the compiler and vtable stubs could still call
1163   // through it.
1164   if (code() == compare ||
1165       from_compiled_entry() == compare->verified_entry_point()) {
1166     clear_code();
1167   }
1168 }
1169 
1170 void Method::unlink_code() {
1171   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1172   clear_code();
1173 }
1174 
1175 #if INCLUDE_CDS
1176 // Called by class data sharing to remove any entry points (which are not shared)
1177 void Method::unlink_method() {
1178   Arguments::assert_is_dumping_archive();
1179   _code = NULL;
1180   _adapter = NULL;
1181   _i2i_entry = NULL;
1182   _from_compiled_entry = NULL;
1183   _from_interpreted_entry = NULL;
1184 
1185   if (is_native()) {
1186     *native_function_addr() = NULL;
1187     set_signature_handler(NULL);
1188   }
1189   NOT_PRODUCT(set_compiled_invocation_count(0);)
1190 
1191   set_method_data(NULL);
1192   clear_method_counters();
1193 }
1194 #endif
1195 
1196 // Called when the method_holder is getting linked. Setup entrypoints so the method
1197 // is ready to be called from interpreter, compiler, and vtables.
1198 void Method::link_method(const methodHandle& h_method, TRAPS) {
1199   // If the code cache is full, we may reenter this function for the
1200   // leftover methods that weren't linked.
1201   if (_i2i_entry != NULL) {
1202     return;
1203   }
1204   assert( _code == NULL, "nothing compiled yet" );
1205 
1206   // Setup interpreter entrypoint
1207   assert(this == h_method(), "wrong h_method()" );
1208 
1209   assert(adapter() == NULL, "init'd to NULL");
1210   address entry = Interpreter::entry_for_method(h_method);
1211   assert(entry != NULL, "interpreter entry must be non-null");
1212   // Sets both _i2i_entry and _from_interpreted_entry
1213   set_interpreter_entry(entry);
1214 
1215   // Don't overwrite already registered native entries.
1216   if (is_native() && !has_native_function()) {
1217     set_native_function(
1218       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
1219       !native_bind_event_is_interesting);
1220   }
1221 
1222   // Setup compiler entrypoint.  This is made eagerly, so we do not need
1223   // special handling of vtables.  An alternative is to make adapters more
1224   // lazily by calling make_adapter() from from_compiled_entry() for the
1225   // normal calls.  For vtable calls life gets more complicated.  When a
1226   // call-site goes mega-morphic we need adapters in all methods which can be
1227   // called from the vtable.  We need adapters on such methods that get loaded
1228   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
1229   // problem we'll make these lazily later.
1230   (void) make_adapters(h_method, CHECK);
1231 
1232   // ONLY USE the h_method now as make_adapter may have blocked
1233 }
1234 
1235 address Method::make_adapters(const methodHandle& mh, TRAPS) {
1236   // Adapters for compiled code are made eagerly here.  They are fairly
1237   // small (generally < 100 bytes) and quick to make (and cached and shared)
1238   // so making them eagerly shouldn't be too expensive.
1239   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
1240   if (adapter == NULL ) {
1241     if (!is_init_completed()) {
1242       // Don't throw exceptions during VM initialization because java.lang.* classes
1243       // might not have been initialized, causing problems when constructing the
1244       // Java exception object.
1245       vm_exit_during_initialization("Out of space in CodeCache for adapters");
1246     } else {
1247       THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for adapters");
1248     }
1249   }
1250 
1251   mh->set_adapter_entry(adapter);
1252   mh->_from_compiled_entry = adapter->get_c2i_entry();
1253   return adapter->get_c2i_entry();
1254 }
1255 
1256 void Method::restore_unshareable_info(TRAPS) {
1257   assert(is_method() && is_valid_method(this), "ensure C++ vtable is restored");
1258 }
1259 
1260 address Method::from_compiled_entry_no_trampoline() const {
1261   CompiledMethod *code = Atomic::load_acquire(&_code);
1262   if (code) {
1263     return code->verified_entry_point();
1264   } else {
1265     return adapter()->get_c2i_entry();
1266   }
1267 }
1268 
1269 // The verified_code_entry() must be called when a invoke is resolved
1270 // on this method.
1271 
1272 // It returns the compiled code entry point, after asserting not null.
1273 // This function is called after potential safepoints so that nmethod
1274 // or adapter that it points to is still live and valid.
1275 // This function must not hit a safepoint!
1276 address Method::verified_code_entry() {
1277   debug_only(NoSafepointVerifier nsv;)
1278   assert(_from_compiled_entry != NULL, "must be set");
1279   return _from_compiled_entry;
1280 }
1281 
1282 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
1283 // (could be racing a deopt).
1284 // Not inline to avoid circular ref.
1285 bool Method::check_code() const {
1286   // cached in a register or local.  There's a race on the value of the field.
1287   CompiledMethod *code = Atomic::load_acquire(&_code);
1288   return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
1289 }
1290 
1291 // Install compiled code.  Instantly it can execute.
1292 void Method::set_code(const methodHandle& mh, CompiledMethod *code) {
1293   assert_lock_strong(CompiledMethod_lock);
1294   assert( code, "use clear_code to remove code" );
1295   assert( mh->check_code(), "" );
1296 
1297   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
1298 
1299   // These writes must happen in this order, because the interpreter will
1300   // directly jump to from_interpreted_entry which jumps to an i2c adapter
1301   // which jumps to _from_compiled_entry.
1302   mh->_code = code;             // Assign before allowing compiled code to exec
1303 
1304   int comp_level = code->comp_level();
1305   // In theory there could be a race here. In practice it is unlikely
1306   // and not worth worrying about.
1307   if (comp_level > mh->highest_comp_level()) {
1308     mh->set_highest_comp_level(comp_level);
1309   }
1310 
1311   OrderAccess::storestore();
1312   mh->_from_compiled_entry = code->verified_entry_point();
1313   OrderAccess::storestore();
1314   // Instantly compiled code can execute.
1315   if (!mh->is_method_handle_intrinsic())
1316     mh->_from_interpreted_entry = mh->get_i2c_entry();
1317 }
1318 
1319 
1320 bool Method::is_overridden_in(Klass* k) const {
1321   InstanceKlass* ik = InstanceKlass::cast(k);
1322 
1323   if (ik->is_interface()) return false;
1324 
1325   // If method is an interface, we skip it - except if it
1326   // is a miranda method
1327   if (method_holder()->is_interface()) {
1328     // Check that method is not a miranda method
1329     if (ik->lookup_method(name(), signature()) == NULL) {
1330       // No implementation exist - so miranda method
1331       return false;
1332     }
1333     return true;
1334   }
1335 
1336   assert(ik->is_subclass_of(method_holder()), "should be subklass");
1337   if (!has_vtable_index()) {
1338     return false;
1339   } else {
1340     Method* vt_m = ik->method_at_vtable(vtable_index());
1341     return vt_m != this;
1342   }
1343 }
1344 
1345 
1346 // give advice about whether this Method* should be cached or not
1347 bool Method::should_not_be_cached() const {
1348   if (is_old()) {
1349     // This method has been redefined. It is either EMCP or obsolete
1350     // and we don't want to cache it because that would pin the method
1351     // down and prevent it from being collectible if and when it
1352     // finishes executing.
1353     return true;
1354   }
1355 
1356   // caching this method should be just fine
1357   return false;
1358 }
1359 
1360 
1361 /**
1362  *  Returns true if this is one of the specially treated methods for
1363  *  security related stack walks (like Reflection.getCallerClass).
1364  */
1365 bool Method::is_ignored_by_security_stack_walk() const {
1366   if (intrinsic_id() == vmIntrinsics::_invoke) {
1367     // This is Method.invoke() -- ignore it
1368     return true;
1369   }
1370   if (method_holder()->is_subclass_of(vmClasses::reflect_MethodAccessorImpl_klass())) {
1371     // This is an auxilary frame -- ignore it
1372     return true;
1373   }
1374   if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
1375     // This is an internal adapter frame for method handles -- ignore it
1376     return true;
1377   }
1378   return false;
1379 }
1380 
1381 
1382 // Constant pool structure for invoke methods:
1383 enum {
1384   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1385   _imcp_invoke_signature,       // utf8: (variable Symbol*)
1386   _imcp_limit
1387 };
1388 
1389 // Test if this method is an MH adapter frame generated by Java code.
1390 // Cf. java/lang/invoke/InvokerBytecodeGenerator
1391 bool Method::is_compiled_lambda_form() const {
1392   return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
1393 }
1394 
1395 // Test if this method is an internal MH primitive method.
1396 bool Method::is_method_handle_intrinsic() const {
1397   vmIntrinsics::ID iid = intrinsic_id();
1398   return (MethodHandles::is_signature_polymorphic(iid) &&
1399           MethodHandles::is_signature_polymorphic_intrinsic(iid));
1400 }
1401 
1402 bool Method::has_member_arg() const {
1403   vmIntrinsics::ID iid = intrinsic_id();
1404   return (MethodHandles::is_signature_polymorphic(iid) &&
1405           MethodHandles::has_member_arg(iid));
1406 }
1407 
1408 // Make an instance of a signature-polymorphic internal MH primitive.
1409 methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1410                                                          Symbol* signature,
1411                                                          TRAPS) {
1412   ResourceMark rm(THREAD);
1413   methodHandle empty;
1414 
1415   InstanceKlass* holder = vmClasses::MethodHandle_klass();
1416   Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
1417   assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1418 
1419   log_info(methodhandles)("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1420 
1421   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
1422   name->increment_refcount();
1423   signature->increment_refcount();
1424 
1425   int cp_length = _imcp_limit;
1426   ClassLoaderData* loader_data = holder->class_loader_data();
1427   constantPoolHandle cp;
1428   {
1429     ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1430     cp = constantPoolHandle(THREAD, cp_oop);
1431   }
1432   cp->copy_fields(holder->constants());
1433   cp->set_pool_holder(holder);
1434   cp->symbol_at_put(_imcp_invoke_name,       name);
1435   cp->symbol_at_put(_imcp_invoke_signature,  signature);
1436   cp->set_has_preresolution();
1437 
1438   // decide on access bits:  public or not?
1439   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
1440   bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
1441   if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
1442   assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
1443 
1444   methodHandle m;
1445   {
1446     InlineTableSizes sizes;
1447     Method* m_oop = Method::allocate(loader_data, 0,
1448                                      accessFlags_from(flags_bits), &sizes,
1449                                      ConstMethod::NORMAL, CHECK_(empty));
1450     m = methodHandle(THREAD, m_oop);
1451   }
1452   m->set_constants(cp());
1453   m->set_name_index(_imcp_invoke_name);
1454   m->set_signature_index(_imcp_invoke_signature);
1455   assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1456   assert(m->signature() == signature, "");
1457   m->compute_from_signature(signature);
1458   m->init_intrinsic_id(klass_id_for_intrinsics(m->method_holder()));
1459   assert(m->is_method_handle_intrinsic(), "");
1460 #ifdef ASSERT
1461   if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
1462   assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
1463   assert(m->intrinsic_id() == iid, "correctly predicted iid");
1464 #endif //ASSERT
1465 
1466   // Finally, set up its entry points.
1467   assert(m->can_be_statically_bound(), "");
1468   m->set_vtable_index(Method::nonvirtual_vtable_index);
1469   m->link_method(m, CHECK_(empty));
1470 
1471   if (iid == vmIntrinsics::_linkToNative) {
1472     m->set_interpreter_entry(m->adapter()->get_i2c_entry());
1473   }
1474   if (log_is_enabled(Info, methodhandles) && (Verbose || WizardMode)) {
1475     LogTarget(Info, methodhandles) lt;
1476     LogStream ls(lt);
1477     m->print_on(&ls);
1478   }
1479 
1480   return m;
1481 }
1482 
1483 Klass* Method::check_non_bcp_klass(Klass* klass) {
1484   if (klass != NULL && klass->class_loader() != NULL) {
1485     if (klass->is_objArray_klass())
1486       klass = ObjArrayKlass::cast(klass)->bottom_klass();
1487     return klass;
1488   }
1489   return NULL;
1490 }
1491 
1492 
1493 methodHandle Method::clone_with_new_data(const methodHandle& m, u_char* new_code, int new_code_length,
1494                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1495   // Code below does not work for native methods - they should never get rewritten anyway
1496   assert(!m->is_native(), "cannot rewrite native methods");
1497   // Allocate new Method*
1498   AccessFlags flags = m->access_flags();
1499 
1500   ConstMethod* cm = m->constMethod();
1501   int checked_exceptions_len = cm->checked_exceptions_length();
1502   int localvariable_len = cm->localvariable_table_length();
1503   int exception_table_len = cm->exception_table_length();
1504   int method_parameters_len = cm->method_parameters_length();
1505   int method_annotations_len = cm->method_annotations_length();
1506   int parameter_annotations_len = cm->parameter_annotations_length();
1507   int type_annotations_len = cm->type_annotations_length();
1508   int default_annotations_len = cm->default_annotations_length();
1509 
1510   InlineTableSizes sizes(
1511       localvariable_len,
1512       new_compressed_linenumber_size,
1513       exception_table_len,
1514       checked_exceptions_len,
1515       method_parameters_len,
1516       cm->generic_signature_index(),
1517       method_annotations_len,
1518       parameter_annotations_len,
1519       type_annotations_len,
1520       default_annotations_len,
1521       0);
1522 
1523   ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1524   Method* newm_oop = Method::allocate(loader_data,
1525                                       new_code_length,
1526                                       flags,
1527                                       &sizes,
1528                                       m->method_type(),
1529                                       CHECK_(methodHandle()));
1530   methodHandle newm (THREAD, newm_oop);
1531 
1532   // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
1533   ConstMethod* newcm = newm->constMethod();
1534   int new_const_method_size = newm->constMethod()->size();
1535 
1536   // This works because the source and target are both Methods. Some compilers
1537   // (e.g., clang) complain that the target vtable pointer will be stomped,
1538   // so cast away newm()'s and m()'s Methodness.
1539   memcpy((void*)newm(), (void*)m(), sizeof(Method));
1540 
1541   // Create shallow copy of ConstMethod.
1542   memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1543 
1544   // Reset correct method/const method, method size, and parameter info
1545   newm->set_constMethod(newcm);
1546   newm->constMethod()->set_code_size(new_code_length);
1547   newm->constMethod()->set_constMethod_size(new_const_method_size);
1548   assert(newm->code_size() == new_code_length, "check");
1549   assert(newm->method_parameters_length() == method_parameters_len, "check");
1550   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1551   assert(newm->exception_table_length() == exception_table_len, "check");
1552   assert(newm->localvariable_table_length() == localvariable_len, "check");
1553   // Copy new byte codes
1554   memcpy(newm->code_base(), new_code, new_code_length);
1555   // Copy line number table
1556   if (new_compressed_linenumber_size > 0) {
1557     memcpy(newm->compressed_linenumber_table(),
1558            new_compressed_linenumber_table,
1559            new_compressed_linenumber_size);
1560   }
1561   // Copy method_parameters
1562   if (method_parameters_len > 0) {
1563     memcpy(newm->method_parameters_start(),
1564            m->method_parameters_start(),
1565            method_parameters_len * sizeof(MethodParametersElement));
1566   }
1567   // Copy checked_exceptions
1568   if (checked_exceptions_len > 0) {
1569     memcpy(newm->checked_exceptions_start(),
1570            m->checked_exceptions_start(),
1571            checked_exceptions_len * sizeof(CheckedExceptionElement));
1572   }
1573   // Copy exception table
1574   if (exception_table_len > 0) {
1575     memcpy(newm->exception_table_start(),
1576            m->exception_table_start(),
1577            exception_table_len * sizeof(ExceptionTableElement));
1578   }
1579   // Copy local variable number table
1580   if (localvariable_len > 0) {
1581     memcpy(newm->localvariable_table_start(),
1582            m->localvariable_table_start(),
1583            localvariable_len * sizeof(LocalVariableTableElement));
1584   }
1585   // Copy stackmap table
1586   if (m->has_stackmap_table()) {
1587     int code_attribute_length = m->stackmap_data()->length();
1588     Array<u1>* stackmap_data =
1589       MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_(methodHandle()));
1590     memcpy((void*)stackmap_data->adr_at(0),
1591            (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
1592     newm->set_stackmap_data(stackmap_data);
1593   }
1594 
1595   // copy annotations over to new method
1596   newcm->copy_annotations_from(loader_data, cm, CHECK_(methodHandle()));
1597   return newm;
1598 }
1599 
1600 vmSymbolID Method::klass_id_for_intrinsics(const Klass* holder) {
1601   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1602   // because we are not loading from core libraries
1603   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1604   // which does not use the class default class loader so we check for its loader here
1605   const InstanceKlass* ik = InstanceKlass::cast(holder);
1606   if ((ik->class_loader() != NULL) && !SystemDictionary::is_platform_class_loader(ik->class_loader())) {
1607     return vmSymbolID::NO_SID;   // regardless of name, no intrinsics here
1608   }
1609 
1610   // see if the klass name is well-known:
1611   Symbol* klass_name = ik->name();
1612   vmSymbolID id = vmSymbols::find_sid(klass_name);
1613   if (id != vmSymbolID::NO_SID && vmIntrinsics::class_has_intrinsics(id)) {
1614     return id;
1615   } else {
1616     return vmSymbolID::NO_SID;
1617   }
1618 }
1619 
1620 void Method::init_intrinsic_id(vmSymbolID klass_id) {
1621   assert(_intrinsic_id == static_cast<int>(vmIntrinsics::_none), "do this just once");
1622   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1623   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1624   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1625 
1626   // the klass name is well-known:
1627   assert(klass_id == klass_id_for_intrinsics(method_holder()), "must be");
1628   assert(klass_id != vmSymbolID::NO_SID, "caller responsibility");
1629 
1630   // ditto for method and signature:
1631   vmSymbolID name_id = vmSymbols::find_sid(name());
1632   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1633       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1634       && name_id == vmSymbolID::NO_SID) {
1635     return;
1636   }
1637   vmSymbolID sig_id = vmSymbols::find_sid(signature());
1638   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1639       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1640       && sig_id == vmSymbolID::NO_SID) {
1641     return;
1642   }
1643   jshort flags = access_flags().as_short();
1644 
1645   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1646   if (id != vmIntrinsics::_none) {
1647     set_intrinsic_id(id);
1648     if (id == vmIntrinsics::_Class_cast) {
1649       // Even if the intrinsic is rejected, we want to inline this simple method.
1650       set_force_inline(true);
1651     }
1652     return;
1653   }
1654 
1655   // A few slightly irregular cases:
1656   switch (klass_id) {
1657   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*., VarHandle
1658   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1659   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle):
1660     if (!is_native())  break;
1661     id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1662     if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1663       id = vmIntrinsics::_none;
1664     break;
1665 
1666   default:
1667     break;
1668   }
1669 
1670   if (id != vmIntrinsics::_none) {
1671     // Set up its iid.  It is an alias method.
1672     set_intrinsic_id(id);
1673     return;
1674   }
1675 }
1676 
1677 bool Method::load_signature_classes(const methodHandle& m, TRAPS) {
1678   if (!THREAD->can_call_java()) {
1679     // There is nothing useful this routine can do from within the Compile thread.
1680     // Hopefully, the signature contains only well-known classes.
1681     // We could scan for this and return true/false, but the caller won't care.
1682     return false;
1683   }
1684   bool sig_is_loaded = true;
1685   ResourceMark rm(THREAD);
1686   for (ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) {
1687     if (ss.is_reference()) {
1688       // load everything, including arrays "[Lfoo;"
1689       Klass* klass = ss.as_klass(SignatureStream::ReturnNull, THREAD);
1690       // We are loading classes eagerly. If a ClassNotFoundException or
1691       // a LinkageError was generated, be sure to ignore it.
1692       if (HAS_PENDING_EXCEPTION) {
1693         if (PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass()) ||
1694             PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1695           CLEAR_PENDING_EXCEPTION;
1696         } else {
1697           return false;
1698         }
1699       }
1700       if( klass == NULL) { sig_is_loaded = false; }
1701     }
1702   }
1703   return sig_is_loaded;
1704 }
1705 
1706 bool Method::has_unloaded_classes_in_signature(const methodHandle& m, TRAPS) {
1707   ResourceMark rm(THREAD);
1708   for(ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) {
1709     if (ss.type() == T_OBJECT) {
1710       // Do not use ss.is_reference() here, since we don't care about
1711       // unloaded array component types.
1712       Klass* klass = ss.as_klass_if_loaded(THREAD);
1713       assert(!HAS_PENDING_EXCEPTION, "as_klass_if_loaded contract");
1714       if (klass == NULL) return true;
1715     }
1716   }
1717   return false;
1718 }
1719 
1720 // Exposed so field engineers can debug VM
1721 void Method::print_short_name(outputStream* st) {
1722   ResourceMark rm;
1723 #ifdef PRODUCT
1724   st->print(" %s::", method_holder()->external_name());
1725 #else
1726   st->print(" %s::", method_holder()->internal_name());
1727 #endif
1728   name()->print_symbol_on(st);
1729   if (WizardMode) signature()->print_symbol_on(st);
1730   else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1731     MethodHandles::print_as_basic_type_signature_on(st, signature());
1732 }
1733 
1734 // Comparer for sorting an object array containing
1735 // Method*s.
1736 static int method_comparator(Method* a, Method* b) {
1737   return a->name()->fast_compare(b->name());
1738 }
1739 
1740 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1741 // default_methods also uses this without the ordering for fast find_method
1742 void Method::sort_methods(Array<Method*>* methods, bool set_idnums, method_comparator_func func) {
1743   int length = methods->length();
1744   if (length > 1) {
1745     if (func == NULL) {
1746       func = method_comparator;
1747     }
1748     {
1749       NoSafepointVerifier nsv;
1750       QuickSort::sort(methods->data(), length, func, /*idempotent=*/false);
1751     }
1752     // Reset method ordering
1753     if (set_idnums) {
1754       for (int i = 0; i < length; i++) {
1755         Method* m = methods->at(i);
1756         m->set_method_idnum(i);
1757         m->set_orig_method_idnum(i);
1758       }
1759     }
1760   }
1761 }
1762 
1763 //-----------------------------------------------------------------------------------
1764 // Non-product code unless JVM/TI needs it
1765 
1766 #if !defined(PRODUCT) || INCLUDE_JVMTI
1767 class SignatureTypePrinter : public SignatureTypeNames {
1768  private:
1769   outputStream* _st;
1770   bool _use_separator;
1771 
1772   void type_name(const char* name) {
1773     if (_use_separator) _st->print(", ");
1774     _st->print("%s", name);
1775     _use_separator = true;
1776   }
1777 
1778  public:
1779   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1780     _st = st;
1781     _use_separator = false;
1782   }
1783 
1784   void print_parameters()              { _use_separator = false; do_parameters_on(this); }
1785   void print_returntype()              { _use_separator = false; do_type(return_type()); }
1786 };
1787 
1788 
1789 void Method::print_name(outputStream* st) {
1790   Thread *thread = Thread::current();
1791   ResourceMark rm(thread);
1792   st->print("%s ", is_static() ? "static" : "virtual");
1793   if (WizardMode) {
1794     st->print("%s.", method_holder()->internal_name());
1795     name()->print_symbol_on(st);
1796     signature()->print_symbol_on(st);
1797   } else {
1798     SignatureTypePrinter sig(signature(), st);
1799     sig.print_returntype();
1800     st->print(" %s.", method_holder()->internal_name());
1801     name()->print_symbol_on(st);
1802     st->print("(");
1803     sig.print_parameters();
1804     st->print(")");
1805   }
1806 }
1807 #endif // !PRODUCT || INCLUDE_JVMTI
1808 
1809 
1810 void Method::print_codes_on(outputStream* st) const {
1811   print_codes_on(0, code_size(), st);
1812 }
1813 
1814 void Method::print_codes_on(int from, int to, outputStream* st) const {
1815   Thread *thread = Thread::current();
1816   ResourceMark rm(thread);
1817   methodHandle mh (thread, (Method*)this);
1818   BytecodeStream s(mh);
1819   s.set_interval(from, to);
1820   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1821   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1822 }
1823 
1824 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1825   _bci = 0;
1826   _line = 0;
1827 };
1828 
1829 bool CompressedLineNumberReadStream::read_pair() {
1830   jubyte next = read_byte();
1831   // Check for terminator
1832   if (next == 0) return false;
1833   if (next == 0xFF) {
1834     // Escape character, regular compression used
1835     _bci  += read_signed_int();
1836     _line += read_signed_int();
1837   } else {
1838     // Single byte compression used
1839     _bci  += next >> 3;
1840     _line += next & 0x7;
1841   }
1842   return true;
1843 }
1844 
1845 #if INCLUDE_JVMTI
1846 
1847 Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1848   BreakpointInfo* bp = method_holder()->breakpoints();
1849   for (; bp != NULL; bp = bp->next()) {
1850     if (bp->match(this, bci)) {
1851       return bp->orig_bytecode();
1852     }
1853   }
1854   {
1855     ResourceMark rm;
1856     fatal("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci);
1857   }
1858   return Bytecodes::_shouldnotreachhere;
1859 }
1860 
1861 void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1862   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1863   BreakpointInfo* bp = method_holder()->breakpoints();
1864   for (; bp != NULL; bp = bp->next()) {
1865     if (bp->match(this, bci)) {
1866       bp->set_orig_bytecode(code);
1867       // and continue, in case there is more than one
1868     }
1869   }
1870 }
1871 
1872 void Method::set_breakpoint(int bci) {
1873   InstanceKlass* ik = method_holder();
1874   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1875   bp->set_next(ik->breakpoints());
1876   ik->set_breakpoints(bp);
1877   // do this last:
1878   bp->set(this);
1879 }
1880 
1881 static void clear_matches(Method* m, int bci) {
1882   InstanceKlass* ik = m->method_holder();
1883   BreakpointInfo* prev_bp = NULL;
1884   BreakpointInfo* next_bp;
1885   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1886     next_bp = bp->next();
1887     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1888     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1889       // do this first:
1890       bp->clear(m);
1891       // unhook it
1892       if (prev_bp != NULL)
1893         prev_bp->set_next(next_bp);
1894       else
1895         ik->set_breakpoints(next_bp);
1896       delete bp;
1897       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1898       // at same location. So we have multiple matching (method_index and bci)
1899       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1900       // breakpoint for clear_breakpoint request and keep all other method versions
1901       // BreakpointInfo for future clear_breakpoint request.
1902       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1903       // which is being called when class is unloaded. We delete all the Breakpoint
1904       // information for all versions of method. We may not correctly restore the original
1905       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1906       // so these methods won't be used anymore.
1907       if (bci >= 0) {
1908         break;
1909       }
1910     } else {
1911       // This one is a keeper.
1912       prev_bp = bp;
1913     }
1914   }
1915 }
1916 
1917 void Method::clear_breakpoint(int bci) {
1918   assert(bci >= 0, "");
1919   clear_matches(this, bci);
1920 }
1921 
1922 void Method::clear_all_breakpoints() {
1923   clear_matches(this, -1);
1924 }
1925 
1926 #endif // INCLUDE_JVMTI
1927 
1928 int Method::invocation_count() const {
1929   MethodCounters* mcs = method_counters();
1930   MethodData* mdo = method_data();
1931   if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
1932       ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1933     return InvocationCounter::count_limit;
1934   } else {
1935     return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
1936            ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1937   }
1938 }
1939 
1940 int Method::backedge_count() const {
1941   MethodCounters* mcs = method_counters();
1942   MethodData* mdo = method_data();
1943   if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
1944       ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1945     return InvocationCounter::count_limit;
1946   } else {
1947     return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
1948            ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1949   }
1950 }
1951 
1952 int Method::highest_comp_level() const {
1953   const MethodCounters* mcs = method_counters();
1954   if (mcs != NULL) {
1955     return mcs->highest_comp_level();
1956   } else {
1957     return CompLevel_none;
1958   }
1959 }
1960 
1961 int Method::highest_osr_comp_level() const {
1962   const MethodCounters* mcs = method_counters();
1963   if (mcs != NULL) {
1964     return mcs->highest_osr_comp_level();
1965   } else {
1966     return CompLevel_none;
1967   }
1968 }
1969 
1970 void Method::set_highest_comp_level(int level) {
1971   MethodCounters* mcs = method_counters();
1972   if (mcs != NULL) {
1973     mcs->set_highest_comp_level(level);
1974   }
1975 }
1976 
1977 void Method::set_highest_osr_comp_level(int level) {
1978   MethodCounters* mcs = method_counters();
1979   if (mcs != NULL) {
1980     mcs->set_highest_osr_comp_level(level);
1981   }
1982 }
1983 
1984 #if INCLUDE_JVMTI
1985 
1986 BreakpointInfo::BreakpointInfo(Method* m, int bci) {
1987   _bci = bci;
1988   _name_index = m->name_index();
1989   _signature_index = m->signature_index();
1990   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1991   if (_orig_bytecode == Bytecodes::_breakpoint)
1992     _orig_bytecode = m->orig_bytecode_at(_bci);
1993   _next = NULL;
1994 }
1995 
1996 void BreakpointInfo::set(Method* method) {
1997 #ifdef ASSERT
1998   {
1999     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
2000     if (code == Bytecodes::_breakpoint)
2001       code = method->orig_bytecode_at(_bci);
2002     assert(orig_bytecode() == code, "original bytecode must be the same");
2003   }
2004 #endif
2005   Thread *thread = Thread::current();
2006   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
2007   method->incr_number_of_breakpoints(thread);
2008   {
2009     // Deoptimize all dependents on this method
2010     HandleMark hm(thread);
2011     methodHandle mh(thread, method);
2012     CodeCache::flush_dependents_on_method(mh);
2013   }
2014 }
2015 
2016 void BreakpointInfo::clear(Method* method) {
2017   *method->bcp_from(_bci) = orig_bytecode();
2018   assert(method->number_of_breakpoints() > 0, "must not go negative");
2019   method->decr_number_of_breakpoints(Thread::current());
2020 }
2021 
2022 #endif // INCLUDE_JVMTI
2023 
2024 // jmethodID handling
2025 
2026 // This is a block allocating object, sort of like JNIHandleBlock, only a
2027 // lot simpler.
2028 // It's allocated on the CHeap because once we allocate a jmethodID, we can
2029 // never get rid of it.
2030 
2031 static const int min_block_size = 8;
2032 
2033 class JNIMethodBlockNode : public CHeapObj<mtClass> {
2034   friend class JNIMethodBlock;
2035   Method**        _methods;
2036   int             _number_of_methods;
2037   int             _top;
2038   JNIMethodBlockNode* _next;
2039 
2040  public:
2041 
2042   JNIMethodBlockNode(int num_methods = min_block_size);
2043 
2044   ~JNIMethodBlockNode() { FREE_C_HEAP_ARRAY(Method*, _methods); }
2045 
2046   void ensure_methods(int num_addl_methods) {
2047     if (_top < _number_of_methods) {
2048       num_addl_methods -= _number_of_methods - _top;
2049       if (num_addl_methods <= 0) {
2050         return;
2051       }
2052     }
2053     if (_next == NULL) {
2054       _next = new JNIMethodBlockNode(MAX2(num_addl_methods, min_block_size));
2055     } else {
2056       _next->ensure_methods(num_addl_methods);
2057     }
2058   }
2059 };
2060 
2061 class JNIMethodBlock : public CHeapObj<mtClass> {
2062   JNIMethodBlockNode _head;
2063   JNIMethodBlockNode *_last_free;
2064  public:
2065   static Method* const _free_method;
2066 
2067   JNIMethodBlock(int initial_capacity = min_block_size)
2068       : _head(initial_capacity), _last_free(&_head) {}
2069 
2070   void ensure_methods(int num_addl_methods) {
2071     _last_free->ensure_methods(num_addl_methods);
2072   }
2073 
2074   Method** add_method(Method* m) {
2075     for (JNIMethodBlockNode* b = _last_free; b != NULL; b = b->_next) {
2076       if (b->_top < b->_number_of_methods) {
2077         // top points to the next free entry.
2078         int i = b->_top;
2079         b->_methods[i] = m;
2080         b->_top++;
2081         _last_free = b;
2082         return &(b->_methods[i]);
2083       } else if (b->_top == b->_number_of_methods) {
2084         // if the next free entry ran off the block see if there's a free entry
2085         for (int i = 0; i < b->_number_of_methods; i++) {
2086           if (b->_methods[i] == _free_method) {
2087             b->_methods[i] = m;
2088             _last_free = b;
2089             return &(b->_methods[i]);
2090           }
2091         }
2092         // Only check each block once for frees.  They're very unlikely.
2093         // Increment top past the end of the block.
2094         b->_top++;
2095       }
2096       // need to allocate a next block.
2097       if (b->_next == NULL) {
2098         b->_next = _last_free = new JNIMethodBlockNode();
2099       }
2100     }
2101     guarantee(false, "Should always allocate a free block");
2102     return NULL;
2103   }
2104 
2105   bool contains(Method** m) {
2106     if (m == NULL) return false;
2107     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2108       if (b->_methods <= m && m < b->_methods + b->_number_of_methods) {
2109         // This is a bit of extra checking, for two reasons.  One is
2110         // that contains() deals with pointers that are passed in by
2111         // JNI code, so making sure that the pointer is aligned
2112         // correctly is valuable.  The other is that <= and > are
2113         // technically not defined on pointers, so the if guard can
2114         // pass spuriously; no modern compiler is likely to make that
2115         // a problem, though (and if one did, the guard could also
2116         // fail spuriously, which would be bad).
2117         ptrdiff_t idx = m - b->_methods;
2118         if (b->_methods + idx == m) {
2119           return true;
2120         }
2121       }
2122     }
2123     return false;  // not found
2124   }
2125 
2126   // Doesn't really destroy it, just marks it as free so it can be reused.
2127   void destroy_method(Method** m) {
2128 #ifdef ASSERT
2129     assert(contains(m), "should be a methodID");
2130 #endif // ASSERT
2131     *m = _free_method;
2132   }
2133 
2134   // During class unloading the methods are cleared, which is different
2135   // than freed.
2136   void clear_all_methods() {
2137     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2138       for (int i = 0; i< b->_number_of_methods; i++) {
2139         b->_methods[i] = NULL;
2140       }
2141     }
2142   }
2143 #ifndef PRODUCT
2144   int count_methods() {
2145     // count all allocated methods
2146     int count = 0;
2147     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2148       for (int i = 0; i< b->_number_of_methods; i++) {
2149         if (b->_methods[i] != _free_method) count++;
2150       }
2151     }
2152     return count;
2153   }
2154 #endif // PRODUCT
2155 };
2156 
2157 // Something that can't be mistaken for an address or a markWord
2158 Method* const JNIMethodBlock::_free_method = (Method*)55;
2159 
2160 JNIMethodBlockNode::JNIMethodBlockNode(int num_methods) : _top(0), _next(NULL) {
2161   _number_of_methods = MAX2(num_methods, min_block_size);
2162   _methods = NEW_C_HEAP_ARRAY(Method*, _number_of_methods, mtInternal);
2163   for (int i = 0; i < _number_of_methods; i++) {
2164     _methods[i] = JNIMethodBlock::_free_method;
2165   }
2166 }
2167 
2168 void Method::ensure_jmethod_ids(ClassLoaderData* loader_data, int capacity) {
2169   ClassLoaderData* cld = loader_data;
2170   if (!SafepointSynchronize::is_at_safepoint()) {
2171     // Have to add jmethod_ids() to class loader data thread-safely.
2172     // Also have to add the method to the list safely, which the lock
2173     // protects as well.
2174     MutexLocker ml(JmethodIdCreation_lock,  Mutex::_no_safepoint_check_flag);
2175     if (cld->jmethod_ids() == NULL) {
2176       cld->set_jmethod_ids(new JNIMethodBlock(capacity));
2177     } else {
2178       cld->jmethod_ids()->ensure_methods(capacity);
2179     }
2180   } else {
2181     // At safepoint, we are single threaded and can set this.
2182     if (cld->jmethod_ids() == NULL) {
2183       cld->set_jmethod_ids(new JNIMethodBlock(capacity));
2184     } else {
2185       cld->jmethod_ids()->ensure_methods(capacity);
2186     }
2187   }
2188 }
2189 
2190 // Add a method id to the jmethod_ids
2191 jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
2192   ClassLoaderData* cld = loader_data;
2193 
2194   if (!SafepointSynchronize::is_at_safepoint()) {
2195     // Have to add jmethod_ids() to class loader data thread-safely.
2196     // Also have to add the method to the list safely, which the lock
2197     // protects as well.
2198     MutexLocker ml(JmethodIdCreation_lock,  Mutex::_no_safepoint_check_flag);
2199     if (cld->jmethod_ids() == NULL) {
2200       cld->set_jmethod_ids(new JNIMethodBlock());
2201     }
2202     // jmethodID is a pointer to Method*
2203     return (jmethodID)cld->jmethod_ids()->add_method(m);
2204   } else {
2205     // At safepoint, we are single threaded and can set this.
2206     if (cld->jmethod_ids() == NULL) {
2207       cld->set_jmethod_ids(new JNIMethodBlock());
2208     }
2209     // jmethodID is a pointer to Method*
2210     return (jmethodID)cld->jmethod_ids()->add_method(m);
2211   }
2212 }
2213 
2214 jmethodID Method::jmethod_id() {
2215   methodHandle mh(Thread::current(), this);
2216   return method_holder()->get_jmethod_id(mh);
2217 }
2218 
2219 // Mark a jmethodID as free.  This is called when there is a data race in
2220 // InstanceKlass while creating the jmethodID cache.
2221 void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
2222   ClassLoaderData* cld = loader_data;
2223   Method** ptr = (Method**)m;
2224   assert(cld->jmethod_ids() != NULL, "should have method handles");
2225   cld->jmethod_ids()->destroy_method(ptr);
2226 }
2227 
2228 void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
2229   // Can't assert the method_holder is the same because the new method has the
2230   // scratch method holder.
2231   assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
2232            == new_method->method_holder()->class_loader() ||
2233            new_method->method_holder()->class_loader() == NULL, // allow Unsafe substitution
2234          "changing to a different class loader");
2235   // Just change the method in place, jmethodID pointer doesn't change.
2236   *((Method**)jmid) = new_method;
2237 }
2238 
2239 bool Method::is_method_id(jmethodID mid) {
2240   Method* m = resolve_jmethod_id(mid);
2241   assert(m != NULL, "should be called with non-null method");
2242   InstanceKlass* ik = m->method_holder();
2243   ClassLoaderData* cld = ik->class_loader_data();
2244   if (cld->jmethod_ids() == NULL) return false;
2245   return (cld->jmethod_ids()->contains((Method**)mid));
2246 }
2247 
2248 Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
2249   if (mid == NULL) return NULL;
2250   Method* o = resolve_jmethod_id(mid);
2251   if (o == NULL || o == JNIMethodBlock::_free_method) {
2252     return NULL;
2253   }
2254   // Method should otherwise be valid. Assert for testing.
2255   assert(is_valid_method(o), "should be valid jmethodid");
2256   // If the method's class holder object is unreferenced, but not yet marked as
2257   // unloaded, we need to return NULL here too because after a safepoint, its memory
2258   // will be reclaimed.
2259   return o->method_holder()->is_loader_alive() ? o : NULL;
2260 };
2261 
2262 void Method::set_on_stack(const bool value) {
2263   // Set both the method itself and its constant pool.  The constant pool
2264   // on stack means some method referring to it is also on the stack.
2265   constants()->set_on_stack(value);
2266 
2267   bool already_set = on_stack();
2268   _access_flags.set_on_stack(value);
2269   if (value && !already_set) {
2270     MetadataOnStackMark::record(this);
2271   }
2272 }
2273 
2274 // Called when the class loader is unloaded to make all methods weak.
2275 void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
2276   loader_data->jmethod_ids()->clear_all_methods();
2277 }
2278 
2279 bool Method::has_method_vptr(const void* ptr) {
2280   Method m;
2281   // This assumes that the vtbl pointer is the first word of a C++ object.
2282   return dereference_vptr(&m) == dereference_vptr(ptr);
2283 }
2284 
2285 // Check that this pointer is valid by checking that the vtbl pointer matches
2286 bool Method::is_valid_method(const Method* m) {
2287   if (m == NULL) {
2288     return false;
2289   } else if ((intptr_t(m) & (wordSize-1)) != 0) {
2290     // Quick sanity check on pointer.
2291     return false;
2292   } else if (m->is_shared()) {
2293     return CppVtables::is_valid_shared_method(m);
2294   } else if (Metaspace::contains_non_shared(m)) {
2295     return has_method_vptr((const void*)m);
2296   } else {
2297     return false;
2298   }
2299 }
2300 
2301 #ifndef PRODUCT
2302 void Method::print_jmethod_ids_count(const ClassLoaderData* loader_data, outputStream* out) {
2303   out->print("%d", loader_data->jmethod_ids()->count_methods());
2304 }
2305 #endif // PRODUCT
2306 
2307 
2308 // Printing
2309 
2310 #ifndef PRODUCT
2311 
2312 void Method::print_on(outputStream* st) const {
2313   ResourceMark rm;
2314   assert(is_method(), "must be method");
2315   st->print_cr("%s", internal_name());
2316   st->print_cr(" - this oop:          " INTPTR_FORMAT, p2i(this));
2317   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
2318   st->print   (" - constants:         " INTPTR_FORMAT " ", p2i(constants()));
2319   constants()->print_value_on(st); st->cr();
2320   st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
2321   st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
2322   st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
2323   st->print_cr(" - max stack:         %d",   max_stack());
2324   st->print_cr(" - max locals:        %d",   max_locals());
2325   st->print_cr(" - size of params:    %d",   size_of_parameters());
2326   st->print_cr(" - method size:       %d",   method_size());
2327   if (intrinsic_id() != vmIntrinsics::_none)
2328     st->print_cr(" - intrinsic id:      %d %s", vmIntrinsics::as_int(intrinsic_id()), vmIntrinsics::name_at(intrinsic_id()));
2329   if (highest_comp_level() != CompLevel_none)
2330     st->print_cr(" - highest level:     %d", highest_comp_level());
2331   st->print_cr(" - vtable index:      %d",   _vtable_index);
2332   st->print_cr(" - i2i entry:         " INTPTR_FORMAT, p2i(interpreter_entry()));
2333   st->print(   " - adapters:          ");
2334   AdapterHandlerEntry* a = ((Method*)this)->adapter();
2335   if (a == NULL)
2336     st->print_cr(INTPTR_FORMAT, p2i(a));
2337   else
2338     a->print_adapter_on(st);
2339   st->print_cr(" - compiled entry     " INTPTR_FORMAT, p2i(from_compiled_entry()));
2340   st->print_cr(" - code size:         %d",   code_size());
2341   if (code_size() != 0) {
2342     st->print_cr(" - code start:        " INTPTR_FORMAT, p2i(code_base()));
2343     st->print_cr(" - code end (excl):   " INTPTR_FORMAT, p2i(code_base() + code_size()));
2344   }
2345   if (method_data() != NULL) {
2346     st->print_cr(" - method data:       " INTPTR_FORMAT, p2i(method_data()));
2347   }
2348   st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
2349   if (checked_exceptions_length() > 0) {
2350     CheckedExceptionElement* table = checked_exceptions_start();
2351     st->print_cr(" - checked ex start:  " INTPTR_FORMAT, p2i(table));
2352     if (Verbose) {
2353       for (int i = 0; i < checked_exceptions_length(); i++) {
2354         st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
2355       }
2356     }
2357   }
2358   if (has_linenumber_table()) {
2359     u_char* table = compressed_linenumber_table();
2360     st->print_cr(" - linenumber start:  " INTPTR_FORMAT, p2i(table));
2361     if (Verbose) {
2362       CompressedLineNumberReadStream stream(table);
2363       while (stream.read_pair()) {
2364         st->print_cr("   - line %d: %d", stream.line(), stream.bci());
2365       }
2366     }
2367   }
2368   st->print_cr(" - localvar length:   %d",   localvariable_table_length());
2369   if (localvariable_table_length() > 0) {
2370     LocalVariableTableElement* table = localvariable_table_start();
2371     st->print_cr(" - localvar start:    " INTPTR_FORMAT, p2i(table));
2372     if (Verbose) {
2373       for (int i = 0; i < localvariable_table_length(); i++) {
2374         int bci = table[i].start_bci;
2375         int len = table[i].length;
2376         const char* name = constants()->printable_name_at(table[i].name_cp_index);
2377         const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
2378         int slot = table[i].slot;
2379         st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
2380       }
2381     }
2382   }
2383   if (code() != NULL) {
2384     st->print   (" - compiled code: ");
2385     code()->print_value_on(st);
2386   }
2387   if (is_native()) {
2388     st->print_cr(" - native function:   " INTPTR_FORMAT, p2i(native_function()));
2389     st->print_cr(" - signature handler: " INTPTR_FORMAT, p2i(signature_handler()));
2390   }
2391 }
2392 
2393 void Method::print_linkage_flags(outputStream* st) {
2394   access_flags().print_on(st);
2395   if (is_default_method()) {
2396     st->print("default ");
2397   }
2398   if (is_overpass()) {
2399     st->print("overpass ");
2400   }
2401 }
2402 #endif //PRODUCT
2403 
2404 void Method::print_value_on(outputStream* st) const {
2405   assert(is_method(), "must be method");
2406   st->print("%s", internal_name());
2407   print_address_on(st);
2408   st->print(" ");
2409   name()->print_value_on(st);
2410   st->print(" ");
2411   signature()->print_value_on(st);
2412   st->print(" in ");
2413   method_holder()->print_value_on(st);
2414   if (WizardMode) st->print("#%d", _vtable_index);
2415   if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
2416   if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
2417 }
2418 
2419 // LogTouchedMethods and PrintTouchedMethods
2420 
2421 // TouchedMethodRecord -- we can't use a HashtableEntry<Method*> because
2422 // the Method may be garbage collected. Let's roll our own hash table.
2423 class TouchedMethodRecord : CHeapObj<mtTracing> {
2424 public:
2425   // It's OK to store Symbols here because they will NOT be GC'ed if
2426   // LogTouchedMethods is enabled.
2427   TouchedMethodRecord* _next;
2428   Symbol* _class_name;
2429   Symbol* _method_name;
2430   Symbol* _method_signature;
2431 };
2432 
2433 static const int TOUCHED_METHOD_TABLE_SIZE = 20011;
2434 static TouchedMethodRecord** _touched_method_table = NULL;
2435 
2436 void Method::log_touched(Thread* current) {
2437 
2438   const int table_size = TOUCHED_METHOD_TABLE_SIZE;
2439   Symbol* my_class = klass_name();
2440   Symbol* my_name  = name();
2441   Symbol* my_sig   = signature();
2442 
2443   unsigned int hash = my_class->identity_hash() +
2444                       my_name->identity_hash() +
2445                       my_sig->identity_hash();
2446   juint index = juint(hash) % table_size;
2447 
2448   MutexLocker ml(current, TouchedMethodLog_lock);
2449   if (_touched_method_table == NULL) {
2450     _touched_method_table = NEW_C_HEAP_ARRAY2(TouchedMethodRecord*, table_size,
2451                                               mtTracing, CURRENT_PC);
2452     memset(_touched_method_table, 0, sizeof(TouchedMethodRecord*)*table_size);
2453   }
2454 
2455   TouchedMethodRecord* ptr = _touched_method_table[index];
2456   while (ptr) {
2457     if (ptr->_class_name       == my_class &&
2458         ptr->_method_name      == my_name &&
2459         ptr->_method_signature == my_sig) {
2460       return;
2461     }
2462     if (ptr->_next == NULL) break;
2463     ptr = ptr->_next;
2464   }
2465   TouchedMethodRecord* nptr = NEW_C_HEAP_OBJ(TouchedMethodRecord, mtTracing);
2466   my_class->increment_refcount();
2467   my_name->increment_refcount();
2468   my_sig->increment_refcount();
2469   nptr->_class_name         = my_class;
2470   nptr->_method_name        = my_name;
2471   nptr->_method_signature   = my_sig;
2472   nptr->_next               = NULL;
2473 
2474   if (ptr == NULL) {
2475     // first
2476     _touched_method_table[index] = nptr;
2477   } else {
2478     ptr->_next = nptr;
2479   }
2480 }
2481 
2482 void Method::print_touched_methods(outputStream* out) {
2483   MutexLocker ml(Thread::current()->is_VM_thread() ? NULL : TouchedMethodLog_lock);
2484   out->print_cr("# Method::print_touched_methods version 1");
2485   if (_touched_method_table) {
2486     for (int i = 0; i < TOUCHED_METHOD_TABLE_SIZE; i++) {
2487       TouchedMethodRecord* ptr = _touched_method_table[i];
2488       while(ptr) {
2489         ptr->_class_name->print_symbol_on(out);       out->print(".");
2490         ptr->_method_name->print_symbol_on(out);      out->print(":");
2491         ptr->_method_signature->print_symbol_on(out); out->cr();
2492         ptr = ptr->_next;
2493       }
2494     }
2495   }
2496 }
2497 
2498 // Verification
2499 
2500 void Method::verify_on(outputStream* st) {
2501   guarantee(is_method(), "object must be method");
2502   guarantee(constants()->is_constantPool(), "should be constant pool");
2503   MethodData* md = method_data();
2504   guarantee(md == NULL ||
2505       md->is_methodData(), "should be method data");
2506 }