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