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