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