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