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