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