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