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