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