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