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