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