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