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