1 /*
   2  * Copyright (c) 1997, 2021, 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 "prims/jvmtiExport.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "runtime/arguments.hpp"
  63 #include "runtime/atomic.hpp"
  64 #include "runtime/frame.inline.hpp"
  65 #include "runtime/handles.inline.hpp"
  66 #include "runtime/init.hpp"
  67 #include "runtime/orderAccess.hpp"
  68 #include "runtime/relocator.hpp"
  69 #include "runtime/safepointVerifiers.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/signature.hpp"
  72 #include "runtime/vm_version.hpp"
  73 #include "services/memTracker.hpp"
  74 #include "utilities/align.hpp"
  75 #include "utilities/quickSort.hpp"
  76 #include "utilities/vmError.hpp"
  77 #include "utilities/xmlstream.hpp"
  78 
  79 // Implementation of Method
  80 
  81 Method* Method::allocate(ClassLoaderData* loader_data,
  82                          int byte_code_size,
  83                          AccessFlags access_flags,
  84                          InlineTableSizes* sizes,
  85                          ConstMethod::MethodType method_type,
  86                          TRAPS) {
  87   assert(!access_flags.is_native() || byte_code_size == 0,
  88          "native methods should not contain byte codes");
  89   ConstMethod* cm = ConstMethod::allocate(loader_data,
  90                                           byte_code_size,
  91                                           sizes,
  92                                           method_type,
  93                                           CHECK_NULL);
  94   int size = Method::size(access_flags.is_native());
  95   return new (loader_data, size, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags);
  96 }
  97 
  98 Method::Method(ConstMethod* xconst, AccessFlags access_flags) {
  99   NoSafepointVerifier no_safepoint;
 100   set_constMethod(xconst);
 101   set_access_flags(access_flags);
 102   set_intrinsic_id(vmIntrinsics::_none);
 103   set_force_inline(false);
 104   set_hidden(false);
 105   set_dont_inline(false);
 106   set_changes_current_thread(false);
 107   set_has_injected_profile(false);
 108   set_method_data(NULL);
 109   clear_method_counters();
 110   set_vtable_index(Method::garbage_vtable_index);
 111 
 112   // Fix and bury in Method*
 113   set_interpreter_entry(NULL); // sets i2i entry and from_int
 114   set_adapter_entry(NULL);
 115   Method::clear_code(); // from_c/from_i get set to c2i/i2i
 116 
 117   if (access_flags.is_native()) {
 118     clear_native_function();
 119     set_signature_handler(NULL);
 120   }
 121 
 122   NOT_PRODUCT(set_compiled_invocation_count(0);)
 123 }
 124 
 125 // Release Method*.  The nmethod will be gone when we get here because
 126 // we've walked the code cache.
 127 void Method::deallocate_contents(ClassLoaderData* loader_data) {
 128   MetadataFactory::free_metadata(loader_data, constMethod());
 129   set_constMethod(NULL);
 130   MetadataFactory::free_metadata(loader_data, method_data());
 131   set_method_data(NULL);
 132   MetadataFactory::free_metadata(loader_data, method_counters());
 133   clear_method_counters();
 134   // The nmethod will be gone when we get here.
 135   if (code() != NULL) _code = NULL;
 136 }
 137 
 138 void Method::release_C_heap_structures() {
 139   if (method_data()) {
 140 #if INCLUDE_JVMCI
 141     FailedSpeculation::free_failed_speculations(method_data()->get_failed_speculations_address());
 142 #endif
 143     // Destroy MethodData
 144     method_data()->~MethodData();
 145   }
 146 }
 147 
 148 address Method::get_i2c_entry() {
 149   assert(adapter() != NULL, "must have");
 150   return adapter()->get_i2c_entry();
 151 }
 152 
 153 address Method::get_c2i_entry() {
 154   assert(adapter() != NULL, "must have");
 155   return adapter()->get_c2i_entry();
 156 }
 157 
 158 address Method::get_c2i_unverified_entry() {
 159   assert(adapter() != NULL, "must have");
 160   return adapter()->get_c2i_unverified_entry();
 161 }
 162 
 163 address Method::get_c2i_no_clinit_check_entry() {
 164   assert(VM_Version::supports_fast_class_init_checks(), "");
 165   assert(adapter() != NULL, "must have");
 166   return adapter()->get_c2i_no_clinit_check_entry();
 167 }
 168 
 169 char* Method::name_and_sig_as_C_string() const {
 170   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
 171 }
 172 
 173 char* Method::name_and_sig_as_C_string(char* buf, int size) const {
 174   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
 175 }
 176 
 177 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
 178   const char* klass_name = klass->external_name();
 179   int klass_name_len  = (int)strlen(klass_name);
 180   int method_name_len = method_name->utf8_length();
 181   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
 182   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
 183   strcpy(dest, klass_name);
 184   dest[klass_name_len] = '.';
 185   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
 186   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
 187   dest[len] = 0;
 188   return dest;
 189 }
 190 
 191 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
 192   Symbol* klass_name = klass->name();
 193   klass_name->as_klass_external_name(buf, size);
 194   int len = (int)strlen(buf);
 195 
 196   if (len < size - 1) {
 197     buf[len++] = '.';
 198 
 199     method_name->as_C_string(&(buf[len]), size - len);
 200     len = (int)strlen(buf);
 201 
 202     signature->as_C_string(&(buf[len]), size - len);
 203   }
 204 
 205   return buf;
 206 }
 207 
 208 const char* Method::external_name() const {
 209   return external_name(constants()->pool_holder(), name(), signature());
 210 }
 211 
 212 void Method::print_external_name(outputStream *os) const {
 213   print_external_name(os, constants()->pool_holder(), name(), signature());
 214 }
 215 
 216 const char* Method::external_name(Klass* klass, Symbol* method_name, Symbol* signature) {
 217   stringStream ss;
 218   print_external_name(&ss, klass, method_name, signature);
 219   return ss.as_string();
 220 }
 221 
 222 void Method::print_external_name(outputStream *os, Klass* klass, Symbol* method_name, Symbol* signature) {
 223   signature->print_as_signature_external_return_type(os);
 224   os->print(" %s.%s(", klass->external_name(), method_name->as_C_string());
 225   signature->print_as_signature_external_parameters(os);
 226   os->print(")");
 227 }
 228 
 229 int Method::fast_exception_handler_bci_for(const methodHandle& mh, Klass* ex_klass, int throw_bci, TRAPS) {
 230   if (log_is_enabled(Debug, exceptions)) {
 231     ResourceMark rm(THREAD);
 232     log_debug(exceptions)("Looking for catch handler for exception of type \"%s\" in method \"%s\"",
 233                           ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string());
 234   }
 235   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 236   // access exception table
 237   ExceptionTable table(mh());
 238   int length = table.length();
 239   // iterate through all entries sequentially
 240   constantPoolHandle pool(THREAD, mh->constants());
 241   for (int i = 0; i < length; i ++) {
 242     //reacquire the table in case a GC happened
 243     ExceptionTable table(mh());
 244     int beg_bci = table.start_pc(i);
 245     int end_bci = table.end_pc(i);
 246     assert(beg_bci <= end_bci, "inconsistent exception table");
 247     log_debug(exceptions)("  - checking exception table entry for BCI %d to %d",
 248                          beg_bci, end_bci);
 249 
 250     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 251       // exception handler bci range covers throw_bci => investigate further
 252       log_debug(exceptions)("    - entry covers throw point BCI %d", throw_bci);
 253 
 254       int handler_bci = table.handler_pc(i);
 255       int klass_index = table.catch_type_index(i);
 256       if (klass_index == 0) {
 257         if (log_is_enabled(Info, exceptions)) {
 258           ResourceMark rm(THREAD);
 259           log_info(exceptions)("Found catch-all handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 260                                ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 261         }
 262         return handler_bci;
 263       } else if (ex_klass == NULL) {
 264         // Is this even possible?
 265         if (log_is_enabled(Info, exceptions)) {
 266           ResourceMark rm(THREAD);
 267           log_info(exceptions)("NULL exception class is implicitly caught by handler in method \"%s\" at BCI: %d",
 268                                mh()->name()->as_C_string(), handler_bci);
 269         }
 270         return handler_bci;
 271       } else {
 272         if (log_is_enabled(Debug, exceptions)) {
 273           ResourceMark rm(THREAD);
 274           log_debug(exceptions)("    - resolving catch type \"%s\"",
 275                                pool->klass_name_at(klass_index)->as_C_string());
 276         }
 277         // we know the exception class => get the constraint class
 278         // this may require loading of the constraint class; if verification
 279         // fails or some other exception occurs, return handler_bci
 280         Klass* k = pool->klass_at(klass_index, THREAD);
 281         if (HAS_PENDING_EXCEPTION) {
 282           if (log_is_enabled(Debug, exceptions)) {
 283             ResourceMark rm(THREAD);
 284             log_debug(exceptions)("    - exception \"%s\" occurred resolving catch type",
 285                                  PENDING_EXCEPTION->klass()->external_name());
 286           }
 287           return handler_bci;
 288         }
 289         assert(k != NULL, "klass not loaded");
 290         if (ex_klass->is_subtype_of(k)) {
 291           if (log_is_enabled(Info, exceptions)) {
 292             ResourceMark rm(THREAD);
 293             log_info(exceptions)("Found matching handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 294                                  ex_klass == NULL ? "NULL" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 295           }
 296           return handler_bci;
 297         }
 298       }
 299     }
 300   }
 301 
 302   if (log_is_enabled(Debug, exceptions)) {
 303     ResourceMark rm(THREAD);
 304     log_debug(exceptions)("No catch handler found for exception of type \"%s\" in method \"%s\"",
 305                           ex_klass->external_name(), mh->name()->as_C_string());
 306   }
 307 
 308   return -1;
 309 }
 310 
 311 void Method::mask_for(int bci, InterpreterOopMap* mask) {
 312   methodHandle h_this(Thread::current(), this);
 313   // Only GC uses the OopMapCache during thread stack root scanning
 314   // any other uses generate an oopmap but do not save it in the cache.
 315   if (Universe::heap()->is_gc_active()) {
 316     method_holder()->mask_for(h_this, bci, mask);
 317   } else {
 318     OopMapCache::compute_one_oop_map(h_this, bci, mask);
 319   }
 320   return;
 321 }
 322 
 323 
 324 int Method::bci_from(address bcp) const {
 325   if (is_native() && bcp == 0) {
 326     return 0;
 327   }
 328 #ifdef ASSERT
 329   {
 330     ResourceMark rm;
 331     assert(is_native() && bcp == code_base() || contains(bcp) || VMError::is_error_reported(),
 332            "bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s",
 333            p2i(bcp), name_and_sig_as_C_string());
 334   }
 335 #endif
 336   return bcp - code_base();
 337 }
 338 
 339 
 340 int Method::validate_bci(int bci) const {
 341   return (bci == 0 || bci < code_size()) ? bci : -1;
 342 }
 343 
 344 // Return bci if it appears to be a valid bcp
 345 // Return -1 otherwise.
 346 // Used by profiling code, when invalid data is a possibility.
 347 // The caller is responsible for validating the Method* itself.
 348 int Method::validate_bci_from_bcp(address bcp) const {
 349   // keep bci as -1 if not a valid bci
 350   int bci = -1;
 351   if (bcp == 0 || bcp == code_base()) {
 352     // code_size() may return 0 and we allow 0 here
 353     // the method may be native
 354     bci = 0;
 355   } else if (contains(bcp)) {
 356     bci = bcp - code_base();
 357   }
 358   // Assert that if we have dodged any asserts, bci is negative.
 359   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 360   return bci;
 361 }
 362 
 363 address Method::bcp_from(int bci) const {
 364   assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()),
 365          "illegal bci: %d for %s method", bci, is_native() ? "native" : "non-native");
 366   address bcp = code_base() + bci;
 367   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 368   return bcp;
 369 }
 370 
 371 address Method::bcp_from(address bcp) const {
 372   if (is_native() && bcp == NULL) {
 373     return code_base();
 374   } else {
 375     return bcp;
 376   }
 377 }
 378 
 379 int Method::size(bool is_native) {
 380   // If native, then include pointers for native_function and signature_handler
 381   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 382   int extra_words = align_up(extra_bytes, BytesPerWord) / BytesPerWord;
 383   return align_metadata_size(header_size() + extra_words);
 384 }
 385 
 386 Symbol* Method::klass_name() const {
 387   return method_holder()->name();
 388 }
 389 
 390 void Method::metaspace_pointers_do(MetaspaceClosure* it) {
 391   log_trace(cds)("Iter(Method): %p", this);
 392 
 393   if (!method_holder()->is_rewritten()) {
 394     it->push(&_constMethod, MetaspaceClosure::_writable);
 395   } else {
 396     it->push(&_constMethod);
 397   }
 398   it->push(&_method_data);
 399   it->push(&_method_counters);
 400 }
 401 
 402 // Attempt to return method to original state.  Clear any pointers
 403 // (to objects outside the shared spaces).  We won't be able to predict
 404 // where they should point in a new JVM.  Further initialize some
 405 // entries now in order allow them to be write protected later.
 406 
 407 void Method::remove_unshareable_info() {
 408   unlink_method();
 409   JFR_ONLY(REMOVE_METHOD_ID(this);)
 410 }
 411 
 412 void Method::set_vtable_index(int index) {
 413   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 414     // At runtime initialize_vtable is rerun as part of link_class_impl()
 415     // for a shared class loaded by the non-boot loader to obtain the loader
 416     // constraints based on the runtime classloaders' context.
 417     return; // don't write into the shared class
 418   } else {
 419     _vtable_index = index;
 420   }
 421 }
 422 
 423 void Method::set_itable_index(int index) {
 424   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 425     // At runtime initialize_itable is rerun as part of link_class_impl()
 426     // for a shared class loaded by the non-boot loader to obtain the loader
 427     // constraints based on the runtime classloaders' context. The dumptime
 428     // itable index should be the same as the runtime index.
 429     assert(_vtable_index == itable_index_max - index,
 430            "archived itable index is different from runtime index");
 431     return; // don’t write into the shared class
 432   } else {
 433     _vtable_index = itable_index_max - index;
 434   }
 435   assert(valid_itable_index(), "");
 436 }
 437 
 438 // The RegisterNatives call being attempted tried to register with a method that
 439 // is not native.  Ask JVM TI what prefixes have been specified.  Then check
 440 // to see if the native method is now wrapped with the prefixes.  See the
 441 // SetNativeMethodPrefix(es) functions in the JVM TI Spec for details.
 442 static Method* find_prefixed_native(Klass* k, Symbol* name, Symbol* signature, TRAPS) {
 443 #if INCLUDE_JVMTI
 444   ResourceMark rm(THREAD);
 445   Method* method;
 446   int name_len = name->utf8_length();
 447   char* name_str = name->as_utf8();
 448   int prefix_count;
 449   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
 450   for (int i = 0; i < prefix_count; i++) {
 451     char* prefix = prefixes[i];
 452     int prefix_len = (int)strlen(prefix);
 453 
 454     // try adding this prefix to the method name and see if it matches another method name
 455     int trial_len = name_len + prefix_len;
 456     char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
 457     strcpy(trial_name_str, prefix);
 458     strcat(trial_name_str, name_str);
 459     TempNewSymbol trial_name = SymbolTable::probe(trial_name_str, trial_len);
 460     if (trial_name == NULL) {
 461       continue; // no such symbol, so this prefix wasn't used, try the next prefix
 462     }
 463     method = k->lookup_method(trial_name, signature);
 464     if (method == NULL) {
 465       continue; // signature doesn't match, try the next prefix
 466     }
 467     if (method->is_native()) {
 468       method->set_is_prefixed_native();
 469       return method; // wahoo, we found a prefixed version of the method, return it
 470     }
 471     // found as non-native, so prefix is good, add it, probably just need more prefixes
 472     name_len = trial_len;
 473     name_str = trial_name_str;
 474   }
 475 #endif // INCLUDE_JVMTI
 476   return NULL; // not found
 477 }
 478 
 479 bool Method::register_native(Klass* k, Symbol* name, Symbol* signature, address entry, TRAPS) {
 480   Method* method = k->lookup_method(name, signature);
 481   if (method == NULL) {
 482     ResourceMark rm(THREAD);
 483     stringStream st;
 484     st.print("Method '");
 485     print_external_name(&st, k, name, signature);
 486     st.print("' name or signature does not match");
 487     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 488   }
 489   if (!method->is_native()) {
 490     // trying to register to a non-native method, see if a JVM TI agent has added prefix(es)
 491     method = find_prefixed_native(k, name, signature, THREAD);
 492     if (method == NULL) {
 493       ResourceMark rm(THREAD);
 494       stringStream st;
 495       st.print("Method '");
 496       print_external_name(&st, k, name, signature);
 497       st.print("' is not declared as native");
 498       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 499     }
 500   }
 501 
 502   if (entry != NULL) {
 503     method->set_native_function(entry, native_bind_event_is_interesting);
 504   } else {
 505     method->clear_native_function();
 506   }
 507   if (log_is_enabled(Debug, jni, resolve)) {
 508     ResourceMark rm(THREAD);
 509     log_debug(jni, resolve)("[Registering JNI native method %s.%s]",
 510                             method->method_holder()->external_name(),
 511                             method->name()->as_C_string());
 512   }
 513   return true;
 514 }
 515 
 516 bool Method::was_executed_more_than(int n) {
 517   // Invocation counter is reset when the Method* is compiled.
 518   // If the method has compiled code we therefore assume it has
 519   // be excuted more than n times.
 520   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 521     // interpreter doesn't bump invocation counter of trivial methods
 522     // compiler does not bump invocation counter of compiled methods
 523     return true;
 524   }
 525   else if ((method_counters() != NULL &&
 526             method_counters()->invocation_counter()->carry()) ||
 527            (method_data() != NULL &&
 528             method_data()->invocation_counter()->carry())) {
 529     // The carry bit is set when the counter overflows and causes
 530     // a compilation to occur.  We don't know how many times
 531     // the counter has been reset, so we simply assume it has
 532     // been executed more than n times.
 533     return true;
 534   } else {
 535     return invocation_count() > n;
 536   }
 537 }
 538 
 539 void Method::print_invocation_count() {
 540   //---<  compose+print method return type, klass, name, and signature  >---
 541   if (is_static()) tty->print("static ");
 542   if (is_final()) tty->print("final ");
 543   if (is_synchronized()) tty->print("synchronized ");
 544   if (is_native()) tty->print("native ");
 545   tty->print("%s::", method_holder()->external_name());
 546   name()->print_symbol_on(tty);
 547   signature()->print_symbol_on(tty);
 548 
 549   if (WizardMode) {
 550     // dump the size of the byte codes
 551     tty->print(" {%d}", code_size());
 552   }
 553   tty->cr();
 554 
 555   // Counting based on signed int counters tends to overflow with
 556   // longer-running workloads on fast machines. The counters under
 557   // consideration here, however, are limited in range by counting
 558   // logic. See InvocationCounter:count_limit for example.
 559   // No "overflow precautions" need to be implemented here.
 560   tty->print_cr ("  interpreter_invocation_count: " INT32_FORMAT_W(11), interpreter_invocation_count());
 561   tty->print_cr ("  invocation_counter:           " INT32_FORMAT_W(11), invocation_count());
 562   tty->print_cr ("  backedge_counter:             " INT32_FORMAT_W(11), backedge_count());
 563 
 564   if (method_data() != NULL) {
 565     tty->print_cr ("  decompile_count:              " UINT32_FORMAT_W(11), method_data()->decompile_count());
 566   }
 567 
 568 #ifndef PRODUCT
 569   if (CountCompiledCalls) {
 570     tty->print_cr ("  compiled_invocation_count:    " INT64_FORMAT_W(11), compiled_invocation_count());
 571   }
 572 #endif
 573 }
 574 
 575 // Build a MethodData* object to hold information about this method
 576 // collected in the interpreter.
 577 void Method::build_interpreter_method_data(const methodHandle& method, TRAPS) {
 578   // Do not profile the method if metaspace has hit an OOM previously
 579   // allocating profiling data. Callers clear pending exception so don't
 580   // add one here.
 581   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 582     return;
 583   }
 584 
 585   // Grab a lock here to prevent multiple
 586   // MethodData*s from being created.
 587   MutexLocker ml(THREAD, MethodData_lock);
 588   if (method->method_data() == NULL) {
 589     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 590     MethodData* method_data = MethodData::allocate(loader_data, method, THREAD);
 591     if (HAS_PENDING_EXCEPTION) {
 592       CompileBroker::log_metaspace_failure();
 593       ClassLoaderDataGraph::set_metaspace_oom(true);
 594       return;   // return the exception (which is cleared)
 595     }
 596 
 597     method->set_method_data(method_data);
 598     if (PrintMethodData && (Verbose || WizardMode)) {
 599       ResourceMark rm(THREAD);
 600       tty->print("build_interpreter_method_data for ");
 601       method->print_name(tty);
 602       tty->cr();
 603       // At the end of the run, the MDO, full of data, will be dumped.
 604     }
 605   }
 606 }
 607 
 608 MethodCounters* Method::build_method_counters(Thread* current, Method* m) {
 609   // Do not profile the method if metaspace has hit an OOM previously
 610   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 611     return NULL;
 612   }
 613 
 614   methodHandle mh(current, m);
 615   MethodCounters* counters;
 616   if (current->is_Java_thread()) {
 617     JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 618     // Use the TRAPS version for a JavaThread so it will adjust the GC threshold
 619     // if needed.
 620     counters = MethodCounters::allocate_with_exception(mh, THREAD);
 621     if (HAS_PENDING_EXCEPTION) {
 622       CLEAR_PENDING_EXCEPTION;
 623     }
 624   } else {
 625     // Call metaspace allocation that doesn't throw exception if the
 626     // current thread isn't a JavaThread, ie. the VMThread.
 627     counters = MethodCounters::allocate_no_exception(mh);
 628   }
 629 
 630   if (counters == NULL) {
 631     CompileBroker::log_metaspace_failure();
 632     ClassLoaderDataGraph::set_metaspace_oom(true);
 633     return NULL;
 634   }
 635 
 636   if (!mh->init_method_counters(counters)) {
 637     MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters);
 638   }
 639 
 640   if (LogTouchedMethods) {
 641     mh->log_touched(current);
 642   }
 643 
 644   return mh->method_counters();
 645 }
 646 
 647 bool Method::init_method_counters(MethodCounters* counters) {
 648   // Try to install a pointer to MethodCounters, return true on success.
 649   return Atomic::replace_if_null(&_method_counters, counters);
 650 }
 651 
 652 int Method::extra_stack_words() {
 653   // not an inline function, to avoid a header dependency on Interpreter
 654   return extra_stack_entries() * Interpreter::stackElementSize;
 655 }
 656 
 657 // Derive size of parameters, return type, and fingerprint,
 658 // all in one pass, which is run at load time.
 659 // We need the first two, and might as well grab the third.
 660 void Method::compute_from_signature(Symbol* sig) {
 661   // At this point, since we are scanning the signature,
 662   // we might as well compute the whole fingerprint.
 663   Fingerprinter fp(sig, is_static());
 664   set_size_of_parameters(fp.size_of_parameters());
 665   constMethod()->set_result_type(fp.return_type());
 666   constMethod()->set_fingerprint(fp.fingerprint());
 667 }
 668 
 669 bool Method::is_vanilla_constructor() const {
 670   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 671   // which only calls the superclass vanilla constructor and possibly does stores of
 672   // zero constants to local fields:
 673   //
 674   //   aload_0
 675   //   invokespecial
 676   //   indexbyte1
 677   //   indexbyte2
 678   //
 679   // followed by an (optional) sequence of:
 680   //
 681   //   aload_0
 682   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 683   //   putfield
 684   //   indexbyte1
 685   //   indexbyte2
 686   //
 687   // followed by:
 688   //
 689   //   return
 690 
 691   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 692   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 693   int size = code_size();
 694   // Check if size match
 695   if (size == 0 || size % 5 != 0) return false;
 696   address cb = code_base();
 697   int last = size - 1;
 698   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 699     // Does not call superclass default constructor
 700     return false;
 701   }
 702   // Check optional sequence
 703   for (int i = 4; i < last; i += 5) {
 704     if (cb[i] != Bytecodes::_aload_0) return false;
 705     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 706     if (cb[i+2] != Bytecodes::_putfield) return false;
 707   }
 708   return true;
 709 }
 710 
 711 
 712 bool Method::compute_has_loops_flag() {
 713   BytecodeStream bcs(methodHandle(Thread::current(), this));
 714   Bytecodes::Code bc;
 715 
 716   while ((bc = bcs.next()) >= 0) {
 717     switch (bc) {
 718       case Bytecodes::_ifeq:
 719       case Bytecodes::_ifnull:
 720       case Bytecodes::_iflt:
 721       case Bytecodes::_ifle:
 722       case Bytecodes::_ifne:
 723       case Bytecodes::_ifnonnull:
 724       case Bytecodes::_ifgt:
 725       case Bytecodes::_ifge:
 726       case Bytecodes::_if_icmpeq:
 727       case Bytecodes::_if_icmpne:
 728       case Bytecodes::_if_icmplt:
 729       case Bytecodes::_if_icmpgt:
 730       case Bytecodes::_if_icmple:
 731       case Bytecodes::_if_icmpge:
 732       case Bytecodes::_if_acmpeq:
 733       case Bytecodes::_if_acmpne:
 734       case Bytecodes::_goto:
 735       case Bytecodes::_jsr:
 736         if (bcs.dest() < bcs.next_bci()) _access_flags.set_has_loops();
 737         break;
 738 
 739       case Bytecodes::_goto_w:
 740       case Bytecodes::_jsr_w:
 741         if (bcs.dest_w() < bcs.next_bci()) _access_flags.set_has_loops();
 742         break;
 743 
 744       case Bytecodes::_lookupswitch: {
 745         Bytecode_lookupswitch lookupswitch(this, bcs.bcp());
 746         if (lookupswitch.default_offset() < 0) {
 747           _access_flags.set_has_loops();
 748         } else {
 749           for (int i = 0; i < lookupswitch.number_of_pairs(); ++i) {
 750             LookupswitchPair pair = lookupswitch.pair_at(i);
 751             if (pair.offset() < 0) {
 752               _access_flags.set_has_loops();
 753               break;
 754             }
 755           }
 756         }
 757         break;
 758       }
 759       case Bytecodes::_tableswitch: {
 760         Bytecode_tableswitch tableswitch(this, bcs.bcp());
 761         if (tableswitch.default_offset() < 0) {
 762           _access_flags.set_has_loops();
 763         } else {
 764           for (int i = 0; i < tableswitch.length(); ++i) {
 765             if (tableswitch.dest_offset_at(i) < 0) {
 766               _access_flags.set_has_loops();
 767             }
 768           }
 769         }
 770         break;
 771       }
 772       default:
 773         break;
 774     }
 775   }
 776   _access_flags.set_loops_flag_init();
 777   return _access_flags.has_loops();
 778 }
 779 
 780 bool Method::is_final_method(AccessFlags class_access_flags) const {
 781   // or "does_not_require_vtable_entry"
 782   // default method or overpass can occur, is not final (reuses vtable entry)
 783   // private methods in classes get vtable entries for backward class compatibility.
 784   if (is_overpass() || is_default_method())  return false;
 785   return is_final() || class_access_flags.is_final();
 786 }
 787 
 788 bool Method::is_final_method() const {
 789   return is_final_method(method_holder()->access_flags());
 790 }
 791 
 792 bool Method::is_default_method() const {
 793   if (method_holder() != NULL &&
 794       method_holder()->is_interface() &&
 795       !is_abstract() && !is_private()) {
 796     return true;
 797   } else {
 798     return false;
 799   }
 800 }
 801 
 802 bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
 803   if (is_final_method(class_access_flags))  return true;
 804 #ifdef ASSERT
 805   ResourceMark rm;
 806   bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
 807   if (class_access_flags.is_interface()) {
 808       assert(is_nonv == is_static() || is_nonv == is_private(),
 809              "nonvirtual unexpected for non-static, non-private: %s",
 810              name_and_sig_as_C_string());
 811   }
 812 #endif
 813   assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
 814   return vtable_index() == nonvirtual_vtable_index;
 815 }
 816 
 817 bool Method::can_be_statically_bound() const {
 818   return can_be_statically_bound(method_holder()->access_flags());
 819 }
 820 
 821 bool Method::can_be_statically_bound(InstanceKlass* context) const {
 822   return (method_holder() == context) && can_be_statically_bound();
 823 }
 824 
 825 bool Method::is_accessor() const {
 826   return is_getter() || is_setter();
 827 }
 828 
 829 bool Method::is_getter() const {
 830   if (code_size() != 5) return false;
 831   if (size_of_parameters() != 1) return false;
 832   if (java_code_at(0) != Bytecodes::_aload_0)  return false;
 833   if (java_code_at(1) != Bytecodes::_getfield) return false;
 834   switch (java_code_at(4)) {
 835     case Bytecodes::_ireturn:
 836     case Bytecodes::_lreturn:
 837     case Bytecodes::_freturn:
 838     case Bytecodes::_dreturn:
 839     case Bytecodes::_areturn:
 840       break;
 841     default:
 842       return false;
 843   }
 844   return true;
 845 }
 846 
 847 bool Method::is_setter() const {
 848   if (code_size() != 6) return false;
 849   if (java_code_at(0) != Bytecodes::_aload_0) return false;
 850   switch (java_code_at(1)) {
 851     case Bytecodes::_iload_1:
 852     case Bytecodes::_aload_1:
 853     case Bytecodes::_fload_1:
 854       if (size_of_parameters() != 2) return false;
 855       break;
 856     case Bytecodes::_dload_1:
 857     case Bytecodes::_lload_1:
 858       if (size_of_parameters() != 3) return false;
 859       break;
 860     default:
 861       return false;
 862   }
 863   if (java_code_at(2) != Bytecodes::_putfield) return false;
 864   if (java_code_at(5) != Bytecodes::_return)   return false;
 865   return true;
 866 }
 867 
 868 bool Method::is_constant_getter() const {
 869   int last_index = code_size() - 1;
 870   // Check if the first 1-3 bytecodes are a constant push
 871   // and the last bytecode is a return.
 872   return (2 <= code_size() && code_size() <= 4 &&
 873           Bytecodes::is_const(java_code_at(0)) &&
 874           Bytecodes::length_for(java_code_at(0)) == last_index &&
 875           Bytecodes::is_return(java_code_at(last_index)));
 876 }
 877 
 878 bool Method::is_initializer() const {
 879   return is_object_initializer() || is_static_initializer();
 880 }
 881 
 882 bool Method::has_valid_initializer_flags() const {
 883   return (is_static() ||
 884           method_holder()->major_version() < 51);
 885 }
 886 
 887 bool Method::is_static_initializer() const {
 888   // For classfiles version 51 or greater, ensure that the clinit method is
 889   // static.  Non-static methods with the name "<clinit>" are not static
 890   // initializers. (older classfiles exempted for backward compatibility)
 891   return name() == vmSymbols::class_initializer_name() &&
 892          has_valid_initializer_flags();
 893 }
 894 
 895 bool Method::is_object_initializer() const {
 896    return name() == vmSymbols::object_initializer_name();
 897 }
 898 
 899 bool Method::needs_clinit_barrier() const {
 900   return is_static() && !method_holder()->is_initialized();
 901 }
 902 
 903 objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
 904   int length = method->checked_exceptions_length();
 905   if (length == 0) {  // common case
 906     return objArrayHandle(THREAD, Universe::the_empty_class_array());
 907   } else {
 908     methodHandle h_this(THREAD, method);
 909     objArrayOop m_oop = oopFactory::new_objArray(vmClasses::Class_klass(), length, CHECK_(objArrayHandle()));
 910     objArrayHandle mirrors (THREAD, m_oop);
 911     for (int i = 0; i < length; i++) {
 912       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 913       Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 914       if (log_is_enabled(Warning, exceptions) &&
 915           !k->is_subclass_of(vmClasses::Throwable_klass())) {
 916         ResourceMark rm(THREAD);
 917         log_warning(exceptions)(
 918           "Class %s in throws clause of method %s is not a subtype of class java.lang.Throwable",
 919           k->external_name(), method->external_name());
 920       }
 921       mirrors->obj_at_put(i, k->java_mirror());
 922     }
 923     return mirrors;
 924   }
 925 };
 926 
 927 
 928 int Method::line_number_from_bci(int bci) const {
 929   int best_bci  =  0;
 930   int best_line = -1;
 931   if (bci == SynchronizationEntryBCI) bci = 0;
 932   if (0 <= bci && bci < code_size() && has_linenumber_table()) {
 933     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 934     // Not necessarily sorted and not necessarily one-to-one.
 935     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 936     while (stream.read_pair()) {
 937       if (stream.bci() == bci) {
 938         // perfect match
 939         return stream.line();
 940       } else {
 941         // update best_bci/line
 942         if (stream.bci() < bci && stream.bci() >= best_bci) {
 943           best_bci  = stream.bci();
 944           best_line = stream.line();
 945         }
 946       }
 947     }
 948   }
 949   return best_line;
 950 }
 951 
 952 
 953 bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
 954   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 955     Thread *thread = Thread::current();
 956     Symbol* klass_name = constants()->klass_name_at(klass_index);
 957     Handle loader(thread, method_holder()->class_loader());
 958     Handle prot  (thread, method_holder()->protection_domain());
 959     return SystemDictionary::find_instance_klass(klass_name, loader, prot) != NULL;
 960   } else {
 961     return true;
 962   }
 963 }
 964 
 965 
 966 bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 967   int klass_index = constants()->klass_ref_index_at(refinfo_index);
 968   if (must_be_resolved) {
 969     // Make sure klass is resolved in constantpool.
 970     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 971   }
 972   return is_klass_loaded_by_klass_index(klass_index);
 973 }
 974 

 975 void Method::set_native_function(address function, bool post_event_flag) {
 976   assert(function != NULL, "use clear_native_function to unregister natives");
 977   assert(!is_special_native_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
 978   address* native_function = native_function_addr();
 979 
 980   // We can see racers trying to place the same native function into place. Once
 981   // is plenty.
 982   address current = *native_function;
 983   if (current == function) return;
 984   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 985       function != NULL) {
 986     // native_method_throw_unsatisfied_link_error_entry() should only
 987     // be passed when post_event_flag is false.
 988     assert(function !=
 989       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 990       "post_event_flag mis-match");
 991 
 992     // post the bind event, and possible change the bind function
 993     JvmtiExport::post_native_method_bind(this, &function);
 994   }
 995   *native_function = function;
 996   // This function can be called more than once. We must make sure that we always
 997   // use the latest registered method -> check if a stub already has been generated.
 998   // If so, we have to make it not_entrant.
 999   CompiledMethod* nm = code(); // Put it into local variable to guard against concurrent updates
1000   if (nm != NULL) {
1001     nm->make_not_entrant();
1002   }
1003 }
1004 
1005 
1006 bool Method::has_native_function() const {
1007   if (is_special_native_intrinsic())
1008     return false;  // special-cased in SharedRuntime::generate_native_wrapper
1009   address func = native_function();
1010   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1011 }
1012 
1013 
1014 void Method::clear_native_function() {
1015   // Note: is_method_handle_intrinsic() is allowed here.
1016   set_native_function(
1017     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
1018     !native_bind_event_is_interesting);
1019   this->unlink_code();
1020 }
1021 
1022 
1023 void Method::set_signature_handler(address handler) {
1024   address* signature_handler =  signature_handler_addr();
1025   *signature_handler = handler;
1026 }
1027 
1028 
1029 void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
1030   assert(reason != NULL, "must provide a reason");
1031   if (PrintCompilation && report) {
1032     ttyLocker ttyl;
1033     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
1034     if (comp_level == CompLevel_all) {
1035       tty->print("all levels ");
1036     } else {
1037       tty->print("level %d ", comp_level);
1038     }
1039     this->print_short_name(tty);
1040     int size = this->code_size();
1041     if (size > 0) {
1042       tty->print(" (%d bytes)", size);
1043     }
1044     if (reason != NULL) {
1045       tty->print("   %s", reason);
1046     }
1047     tty->cr();
1048   }
1049   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
1050     ttyLocker ttyl;
1051     xtty->begin_elem("make_not_compilable thread='" UINTX_FORMAT "' osr='%d' level='%d'",
1052                      os::current_thread_id(), is_osr, comp_level);
1053     if (reason != NULL) {
1054       xtty->print(" reason=\'%s\'", reason);
1055     }
1056     xtty->method(this);
1057     xtty->stamp();
1058     xtty->end_elem();
1059   }
1060 }
1061 
1062 bool Method::is_always_compilable() const {
1063   // Generated adapters must be compiled
1064   if (is_method_handle_intrinsic() && is_synthetic()) {
1065     assert(!is_not_c1_compilable(), "sanity check");
1066     assert(!is_not_c2_compilable(), "sanity check");
1067     return true;
1068   }
1069 
1070   return false;
1071 }
1072 
1073 bool Method::is_not_compilable(int comp_level) const {
1074   if (number_of_breakpoints() > 0)
1075     return true;
1076   if (is_always_compilable())
1077     return false;
1078   if (comp_level == CompLevel_any)
1079     return is_not_c1_compilable() && is_not_c2_compilable();
1080   if (is_c1_compile(comp_level))
1081     return is_not_c1_compilable();
1082   if (is_c2_compile(comp_level))
1083     return is_not_c2_compilable();
1084   return false;
1085 }
1086 
1087 // call this when compiler finds that this method is not compilable
1088 void Method::set_not_compilable(const char* reason, int comp_level, bool report) {
1089   if (is_always_compilable()) {
1090     // Don't mark a method which should be always compilable
1091     return;
1092   }
1093   print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
1094   if (comp_level == CompLevel_all) {
1095     set_not_c1_compilable();
1096     set_not_c2_compilable();
1097   } else {
1098     if (is_c1_compile(comp_level))
1099       set_not_c1_compilable();
1100     if (is_c2_compile(comp_level))
1101       set_not_c2_compilable();
1102   }
1103   assert(!CompilationPolicy::can_be_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1104 }
1105 
1106 bool Method::is_not_osr_compilable(int comp_level) const {
1107   if (is_not_compilable(comp_level))
1108     return true;
1109   if (comp_level == CompLevel_any)
1110     return is_not_c1_osr_compilable() && is_not_c2_osr_compilable();
1111   if (is_c1_compile(comp_level))
1112     return is_not_c1_osr_compilable();
1113   if (is_c2_compile(comp_level))
1114     return is_not_c2_osr_compilable();
1115   return false;
1116 }
1117 
1118 void Method::set_not_osr_compilable(const char* reason, int comp_level, bool report) {
1119   print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
1120   if (comp_level == CompLevel_all) {
1121     set_not_c1_osr_compilable();
1122     set_not_c2_osr_compilable();
1123   } else {
1124     if (is_c1_compile(comp_level))
1125       set_not_c1_osr_compilable();
1126     if (is_c2_compile(comp_level))
1127       set_not_c2_osr_compilable();
1128   }
1129   assert(!CompilationPolicy::can_be_osr_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1130 }
1131 
1132 // Revert to using the interpreter and clear out the nmethod
1133 void Method::clear_code() {
1134   // this may be NULL if c2i adapters have not been made yet
1135   // Only should happen at allocate time.
1136   if (adapter() == NULL) {
1137     _from_compiled_entry    = NULL;
1138   } else {
1139     _from_compiled_entry    = adapter()->get_c2i_entry();
1140   }
1141   OrderAccess::storestore();
1142   _from_interpreted_entry = _i2i_entry;
1143   OrderAccess::storestore();
1144   _code = NULL;
1145 }
1146 
1147 void Method::unlink_code(CompiledMethod *compare) {
1148   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1149   // We need to check if either the _code or _from_compiled_code_entry_point
1150   // refer to this nmethod because there is a race in setting these two fields
1151   // in Method* as seen in bugid 4947125.
1152   // If the vep() points to the zombie nmethod, the memory for the nmethod
1153   // could be flushed and the compiler and vtable stubs could still call
1154   // through it.
1155   if (code() == compare ||
1156       from_compiled_entry() == compare->verified_entry_point()) {
1157     clear_code();
1158   }
1159 }
1160 
1161 void Method::unlink_code() {
1162   MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1163   clear_code();
1164 }
1165 
1166 #if INCLUDE_CDS
1167 // Called by class data sharing to remove any entry points (which are not shared)
1168 void Method::unlink_method() {
1169   Arguments::assert_is_dumping_archive();
1170   _code = NULL;
1171   _adapter = NULL;
1172   _i2i_entry = NULL;
1173   _from_compiled_entry = NULL;
1174   _from_interpreted_entry = NULL;
1175 
1176   if (is_native()) {
1177     *native_function_addr() = NULL;
1178     set_signature_handler(NULL);
1179   }
1180   NOT_PRODUCT(set_compiled_invocation_count(0);)
1181 
1182   set_method_data(NULL);
1183   clear_method_counters();
1184 }
1185 #endif
1186 
1187 // Called when the method_holder is getting linked. Setup entrypoints so the method
1188 // is ready to be called from interpreter, compiler, and vtables.
1189 void Method::link_method(const methodHandle& h_method, TRAPS) {
1190   // If the code cache is full, we may reenter this function for the
1191   // leftover methods that weren't linked.
1192   if (_i2i_entry != NULL) {
1193     return;
1194   }
1195   assert( _code == NULL, "nothing compiled yet" );
1196 
1197   // Setup interpreter entrypoint
1198   assert(this == h_method(), "wrong h_method()" );
1199 
1200   assert(adapter() == NULL, "init'd to NULL");
1201   address entry = Interpreter::entry_for_method(h_method);
1202   assert(entry != NULL, "interpreter entry must be non-null");
1203   // Sets both _i2i_entry and _from_interpreted_entry
1204   set_interpreter_entry(entry);
1205 
1206   // Don't overwrite already registered native entries.
1207   if (is_native() && !has_native_function()) {
1208     set_native_function(
1209       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
1210       !native_bind_event_is_interesting);
1211   }
1212 
1213   // Setup compiler entrypoint.  This is made eagerly, so we do not need
1214   // special handling of vtables.  An alternative is to make adapters more
1215   // lazily by calling make_adapter() from from_compiled_entry() for the
1216   // normal calls.  For vtable calls life gets more complicated.  When a
1217   // call-site goes mega-morphic we need adapters in all methods which can be
1218   // called from the vtable.  We need adapters on such methods that get loaded
1219   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
1220   // problem we'll make these lazily later.
1221   (void) make_adapters(h_method, CHECK);
1222 
1223   set_num_stack_arg_slots();
1224 
1225   // ONLY USE the h_method now as make_adapter may have blocked
1226 }
1227 
1228 address Method::make_adapters(const methodHandle& mh, TRAPS) {
1229   // Adapters for compiled code are made eagerly here.  They are fairly
1230   // small (generally < 100 bytes) and quick to make (and cached and shared)
1231   // so making them eagerly shouldn't be too expensive.
1232   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
1233   if (adapter == NULL ) {
1234     if (!is_init_completed()) {
1235       // Don't throw exceptions during VM initialization because java.lang.* classes
1236       // might not have been initialized, causing problems when constructing the
1237       // Java exception object.
1238       vm_exit_during_initialization("Out of space in CodeCache for adapters");
1239     } else {
1240       THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "Out of space in CodeCache for adapters");
1241     }
1242   }
1243 
1244   mh->set_adapter_entry(adapter);
1245   mh->_from_compiled_entry = adapter->get_c2i_entry();
1246   return adapter->get_c2i_entry();
1247 }
1248 
1249 void Method::restore_unshareable_info(TRAPS) {
1250   assert(is_method() && is_valid_method(this), "ensure C++ vtable is restored");
1251 }
1252 
1253 address Method::from_compiled_entry_no_trampoline() const {
1254   CompiledMethod *code = Atomic::load_acquire(&_code);
1255   if (code) {
1256     return code->verified_entry_point();
1257   } else {
1258     return adapter()->get_c2i_entry();
1259   }
1260 }
1261 
1262 // The verified_code_entry() must be called when a invoke is resolved
1263 // on this method.
1264 
1265 // It returns the compiled code entry point, after asserting not null.
1266 // This function is called after potential safepoints so that nmethod
1267 // or adapter that it points to is still live and valid.
1268 // This function must not hit a safepoint!
1269 address Method::verified_code_entry() {
1270   debug_only(NoSafepointVerifier nsv;)
1271   assert(_from_compiled_entry != NULL, "must be set");
1272   return _from_compiled_entry;
1273 }
1274 
1275 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
1276 // (could be racing a deopt).
1277 // Not inline to avoid circular ref.
1278 bool Method::check_code() const {
1279   // cached in a register or local.  There's a race on the value of the field.
1280   CompiledMethod *code = Atomic::load_acquire(&_code);
1281   return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
1282 }
1283 
1284 // Install compiled code.  Instantly it can execute.
1285 void Method::set_code(const methodHandle& mh, CompiledMethod *code) {
1286   assert_lock_strong(CompiledMethod_lock);
1287   assert( code, "use clear_code to remove code" );
1288   assert( mh->check_code(), "" );
1289 
1290   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
1291 
1292   // These writes must happen in this order, because the interpreter will
1293   // directly jump to from_interpreted_entry which jumps to an i2c adapter
1294   // which jumps to _from_compiled_entry.
1295   mh->_code = code;             // Assign before allowing compiled code to exec
1296 
1297   int comp_level = code->comp_level();
1298   // In theory there could be a race here. In practice it is unlikely
1299   // and not worth worrying about.
1300   if (comp_level > mh->highest_comp_level()) {
1301     mh->set_highest_comp_level(comp_level);
1302   }
1303 
1304   OrderAccess::storestore();
1305   mh->_from_compiled_entry = code->verified_entry_point();
1306   OrderAccess::storestore();
1307   // Instantly compiled code can execute.
1308   if (!mh->is_method_handle_intrinsic())
1309     mh->_from_interpreted_entry = mh->get_i2c_entry();
1310   if (mh->is_continuation_enter_intrinsic()) {
1311     mh->_i2i_entry = mh->get_i2c_entry(); // this is the entry used when we're in interpreter-only mode; see InterpreterMacroAssembler::jump_from_interpreted
1312     mh->_from_interpreted_entry = mh->get_i2c_entry();
1313   }
1314 }
1315 
1316 
1317 bool Method::is_overridden_in(Klass* k) const {
1318   InstanceKlass* ik = InstanceKlass::cast(k);
1319 
1320   if (ik->is_interface()) return false;
1321 
1322   // If method is an interface, we skip it - except if it
1323   // is a miranda method
1324   if (method_holder()->is_interface()) {
1325     // Check that method is not a miranda method
1326     if (ik->lookup_method(name(), signature()) == NULL) {
1327       // No implementation exist - so miranda method
1328       return false;
1329     }
1330     return true;
1331   }
1332 
1333   assert(ik->is_subclass_of(method_holder()), "should be subklass");
1334   if (!has_vtable_index()) {
1335     return false;
1336   } else {
1337     Method* vt_m = ik->method_at_vtable(vtable_index());
1338     return vt_m != this;
1339   }
1340 }
1341 
1342 
1343 // give advice about whether this Method* should be cached or not
1344 bool Method::should_not_be_cached() const {
1345   if (is_old()) {
1346     // This method has been redefined. It is either EMCP or obsolete
1347     // and we don't want to cache it because that would pin the method
1348     // down and prevent it from being collectible if and when it
1349     // finishes executing.
1350     return true;
1351   }
1352 
1353   // caching this method should be just fine
1354   return false;
1355 }
1356 
1357 
1358 /**
1359  *  Returns true if this is one of the specially treated methods for
1360  *  security related stack walks (like Reflection.getCallerClass).
1361  */
1362 bool Method::is_ignored_by_security_stack_walk() const {
1363   if (intrinsic_id() == vmIntrinsics::_invoke) {
1364     // This is Method.invoke() -- ignore it
1365     return true;
1366   }
1367   if (method_holder()->is_subclass_of(vmClasses::reflect_MethodAccessorImpl_klass())) {
1368     // This is an auxilary frame -- ignore it
1369     return true;
1370   }
1371   if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
1372     // This is an internal adapter frame for method handles -- ignore it
1373     return true;
1374   }
1375   return false;
1376 }
1377 
1378 
1379 // Constant pool structure for invoke methods:
1380 enum {
1381   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1382   _imcp_invoke_signature,       // utf8: (variable Symbol*)
1383   _imcp_limit
1384 };
1385 
1386 // Test if this method is an MH adapter frame generated by Java code.
1387 // Cf. java/lang/invoke/InvokerBytecodeGenerator
1388 bool Method::is_compiled_lambda_form() const {
1389   return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
1390 }
1391 
1392 // Test if this method is an internal MH primitive method.
1393 bool Method::is_method_handle_intrinsic() const {
1394   vmIntrinsics::ID iid = intrinsic_id();
1395   return (MethodHandles::is_signature_polymorphic(iid) &&
1396           MethodHandles::is_signature_polymorphic_intrinsic(iid));
1397 }
1398 
1399 bool Method::has_member_arg() const {
1400   vmIntrinsics::ID iid = intrinsic_id();
1401   return (MethodHandles::is_signature_polymorphic(iid) &&
1402           MethodHandles::has_member_arg(iid));
1403 }
1404 
1405 // Make an instance of a signature-polymorphic internal MH primitive.
1406 methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1407                                                          Symbol* signature,
1408                                                          TRAPS) {
1409   ResourceMark rm(THREAD);
1410   methodHandle empty;
1411 
1412   InstanceKlass* holder = vmClasses::MethodHandle_klass();
1413   Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
1414   assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1415 
1416   log_info(methodhandles)("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1417 
1418   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
1419   name->increment_refcount();
1420   signature->increment_refcount();
1421 
1422   int cp_length = _imcp_limit;
1423   ClassLoaderData* loader_data = holder->class_loader_data();
1424   constantPoolHandle cp;
1425   {
1426     ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1427     cp = constantPoolHandle(THREAD, cp_oop);
1428   }
1429   cp->copy_fields(holder->constants());
1430   cp->set_pool_holder(holder);
1431   cp->symbol_at_put(_imcp_invoke_name,       name);
1432   cp->symbol_at_put(_imcp_invoke_signature,  signature);
1433   cp->set_has_preresolution();
1434 
1435   // decide on access bits:  public or not?
1436   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
1437   bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
1438   if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
1439   assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
1440 
1441   methodHandle m;
1442   {
1443     InlineTableSizes sizes;
1444     Method* m_oop = Method::allocate(loader_data, 0,
1445                                      accessFlags_from(flags_bits), &sizes,
1446                                      ConstMethod::NORMAL, CHECK_(empty));
1447     m = methodHandle(THREAD, m_oop);
1448   }
1449   m->set_constants(cp());
1450   m->set_name_index(_imcp_invoke_name);
1451   m->set_signature_index(_imcp_invoke_signature);
1452   assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1453   assert(m->signature() == signature, "");
1454   m->compute_from_signature(signature);
1455   m->init_intrinsic_id(klass_id_for_intrinsics(m->method_holder()));
1456   assert(m->is_method_handle_intrinsic(), "");
1457 #ifdef ASSERT
1458   if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
1459   assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
1460   assert(m->intrinsic_id() == iid, "correctly predicted iid");
1461 #endif //ASSERT
1462 
1463   // Finally, set up its entry points.
1464   assert(m->can_be_statically_bound(), "");
1465   m->set_vtable_index(Method::nonvirtual_vtable_index);
1466   m->link_method(m, CHECK_(empty));
1467 
1468   if (iid == vmIntrinsics::_linkToNative) {
1469     m->set_interpreter_entry(m->adapter()->get_i2c_entry());
1470   }
1471   if (log_is_enabled(Info, methodhandles) && (Verbose || WizardMode)) {
1472     LogTarget(Info, methodhandles) lt;
1473     LogStream ls(lt);
1474     m->print_on(&ls);
1475   }
1476 
1477   return m;
1478 }
1479 
1480 Klass* Method::check_non_bcp_klass(Klass* klass) {
1481   if (klass != NULL && klass->class_loader() != NULL) {
1482     if (klass->is_objArray_klass())
1483       klass = ObjArrayKlass::cast(klass)->bottom_klass();
1484     return klass;
1485   }
1486   return NULL;
1487 }
1488 
1489 
1490 methodHandle Method::clone_with_new_data(const methodHandle& m, u_char* new_code, int new_code_length,
1491                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1492   // Code below does not work for native methods - they should never get rewritten anyway
1493   assert(!m->is_native(), "cannot rewrite native methods");
1494   // Allocate new Method*
1495   AccessFlags flags = m->access_flags();
1496 
1497   ConstMethod* cm = m->constMethod();
1498   int checked_exceptions_len = cm->checked_exceptions_length();
1499   int localvariable_len = cm->localvariable_table_length();
1500   int exception_table_len = cm->exception_table_length();
1501   int method_parameters_len = cm->method_parameters_length();
1502   int method_annotations_len = cm->method_annotations_length();
1503   int parameter_annotations_len = cm->parameter_annotations_length();
1504   int type_annotations_len = cm->type_annotations_length();
1505   int default_annotations_len = cm->default_annotations_length();
1506 
1507   InlineTableSizes sizes(
1508       localvariable_len,
1509       new_compressed_linenumber_size,
1510       exception_table_len,
1511       checked_exceptions_len,
1512       method_parameters_len,
1513       cm->generic_signature_index(),
1514       method_annotations_len,
1515       parameter_annotations_len,
1516       type_annotations_len,
1517       default_annotations_len,
1518       0);
1519 
1520   ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1521   Method* newm_oop = Method::allocate(loader_data,
1522                                       new_code_length,
1523                                       flags,
1524                                       &sizes,
1525                                       m->method_type(),
1526                                       CHECK_(methodHandle()));
1527   methodHandle newm (THREAD, newm_oop);
1528 
1529   // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
1530   ConstMethod* newcm = newm->constMethod();
1531   int new_const_method_size = newm->constMethod()->size();
1532 
1533   // This works because the source and target are both Methods. Some compilers
1534   // (e.g., clang) complain that the target vtable pointer will be stomped,
1535   // so cast away newm()'s and m()'s Methodness.
1536   memcpy((void*)newm(), (void*)m(), sizeof(Method));
1537 
1538   // Create shallow copy of ConstMethod.
1539   memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1540 
1541   // Reset correct method/const method, method size, and parameter info
1542   newm->set_constMethod(newcm);
1543   newm->constMethod()->set_code_size(new_code_length);
1544   newm->constMethod()->set_constMethod_size(new_const_method_size);
1545   assert(newm->code_size() == new_code_length, "check");
1546   assert(newm->method_parameters_length() == method_parameters_len, "check");
1547   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1548   assert(newm->exception_table_length() == exception_table_len, "check");
1549   assert(newm->localvariable_table_length() == localvariable_len, "check");
1550   // Copy new byte codes
1551   memcpy(newm->code_base(), new_code, new_code_length);
1552   // Copy line number table
1553   if (new_compressed_linenumber_size > 0) {
1554     memcpy(newm->compressed_linenumber_table(),
1555            new_compressed_linenumber_table,
1556            new_compressed_linenumber_size);
1557   }
1558   // Copy method_parameters
1559   if (method_parameters_len > 0) {
1560     memcpy(newm->method_parameters_start(),
1561            m->method_parameters_start(),
1562            method_parameters_len * sizeof(MethodParametersElement));
1563   }
1564   // Copy checked_exceptions
1565   if (checked_exceptions_len > 0) {
1566     memcpy(newm->checked_exceptions_start(),
1567            m->checked_exceptions_start(),
1568            checked_exceptions_len * sizeof(CheckedExceptionElement));
1569   }
1570   // Copy exception table
1571   if (exception_table_len > 0) {
1572     memcpy(newm->exception_table_start(),
1573            m->exception_table_start(),
1574            exception_table_len * sizeof(ExceptionTableElement));
1575   }
1576   // Copy local variable number table
1577   if (localvariable_len > 0) {
1578     memcpy(newm->localvariable_table_start(),
1579            m->localvariable_table_start(),
1580            localvariable_len * sizeof(LocalVariableTableElement));
1581   }
1582   // Copy stackmap table
1583   if (m->has_stackmap_table()) {
1584     int code_attribute_length = m->stackmap_data()->length();
1585     Array<u1>* stackmap_data =
1586       MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_(methodHandle()));
1587     memcpy((void*)stackmap_data->adr_at(0),
1588            (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
1589     newm->set_stackmap_data(stackmap_data);
1590   }
1591 
1592   // copy annotations over to new method
1593   newcm->copy_annotations_from(loader_data, cm, CHECK_(methodHandle()));
1594   return newm;
1595 }
1596 
1597 vmSymbolID Method::klass_id_for_intrinsics(const Klass* holder) {
1598   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1599   // because we are not loading from core libraries
1600   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1601   // which does not use the class default class loader so we check for its loader here
1602   const InstanceKlass* ik = InstanceKlass::cast(holder);
1603   if ((ik->class_loader() != NULL) && !SystemDictionary::is_platform_class_loader(ik->class_loader())) {
1604     return vmSymbolID::NO_SID;   // regardless of name, no intrinsics here
1605   }
1606 
1607   // see if the klass name is well-known:
1608   Symbol* klass_name = ik->name();
1609   vmSymbolID id = vmSymbols::find_sid(klass_name);
1610   if (id != vmSymbolID::NO_SID && vmIntrinsics::class_has_intrinsics(id)) {
1611     return id;
1612   } else {
1613     return vmSymbolID::NO_SID;
1614   }
1615 }
1616 
1617 void Method::init_intrinsic_id(vmSymbolID klass_id) {
1618   assert(_intrinsic_id == static_cast<int>(vmIntrinsics::_none), "do this just once");
1619   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1620   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1621   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1622 
1623   // the klass name is well-known:
1624   assert(klass_id == klass_id_for_intrinsics(method_holder()), "must be");
1625   assert(klass_id != vmSymbolID::NO_SID, "caller responsibility");
1626 
1627   // ditto for method and signature:
1628   vmSymbolID name_id = vmSymbols::find_sid(name());
1629   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1630       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1631       && name_id == vmSymbolID::NO_SID) {
1632     return;
1633   }
1634   vmSymbolID sig_id = vmSymbols::find_sid(signature());
1635   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1636       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1637       && sig_id == vmSymbolID::NO_SID) {
1638     return;
1639   }
1640   jshort flags = access_flags().as_short();
1641 
1642   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1643   if (id != vmIntrinsics::_none) {
1644     set_intrinsic_id(id);
1645     if (id == vmIntrinsics::_Class_cast) {
1646       // Even if the intrinsic is rejected, we want to inline this simple method.
1647       set_force_inline(true);
1648     }
1649     return;
1650   }
1651 
1652   // A few slightly irregular cases:
1653   switch (klass_id) {
1654   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*., VarHandle
1655   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1656   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle):
1657     if (!is_native())  break;
1658     id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1659     if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1660       id = vmIntrinsics::_none;
1661     break;
1662 
1663   default:
1664     break;
1665   }
1666 
1667   if (id != vmIntrinsics::_none) {
1668     // Set up its iid.  It is an alias method.
1669     set_intrinsic_id(id);
1670     return;
1671   }
1672 }
1673 
1674 bool Method::load_signature_classes(const methodHandle& m, TRAPS) {
1675   if (!THREAD->can_call_java()) {
1676     // There is nothing useful this routine can do from within the Compile thread.
1677     // Hopefully, the signature contains only well-known classes.
1678     // We could scan for this and return true/false, but the caller won't care.
1679     return false;
1680   }
1681   bool sig_is_loaded = true;
1682   ResourceMark rm(THREAD);
1683   for (ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) {
1684     if (ss.is_reference()) {
1685       // load everything, including arrays "[Lfoo;"
1686       Klass* klass = ss.as_klass(SignatureStream::ReturnNull, THREAD);
1687       // We are loading classes eagerly. If a ClassNotFoundException or
1688       // a LinkageError was generated, be sure to ignore it.
1689       if (HAS_PENDING_EXCEPTION) {
1690         if (PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass()) ||
1691             PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1692           CLEAR_PENDING_EXCEPTION;
1693         } else {
1694           return false;
1695         }
1696       }
1697       if( klass == NULL) { sig_is_loaded = false; }
1698     }
1699   }
1700   return sig_is_loaded;
1701 }
1702 
1703 bool Method::has_unloaded_classes_in_signature(const methodHandle& m, TRAPS) {
1704   ResourceMark rm(THREAD);
1705   for(ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) {
1706     if (ss.type() == T_OBJECT) {
1707       // Do not use ss.is_reference() here, since we don't care about
1708       // unloaded array component types.
1709       Klass* klass = ss.as_klass_if_loaded(THREAD);
1710       assert(!HAS_PENDING_EXCEPTION, "as_klass_if_loaded contract");
1711       if (klass == NULL) return true;
1712     }
1713   }
1714   return false;
1715 }
1716 
1717 // Exposed so field engineers can debug VM
1718 void Method::print_short_name(outputStream* st) const {
1719   ResourceMark rm;
1720 #ifdef PRODUCT
1721   st->print(" %s::", method_holder()->external_name());
1722 #else
1723   st->print(" %s::", method_holder()->internal_name());
1724 #endif
1725   name()->print_symbol_on(st);
1726   if (WizardMode) signature()->print_symbol_on(st);
1727   else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1728     MethodHandles::print_as_basic_type_signature_on(st, signature());
1729 }
1730 
1731 // Comparer for sorting an object array containing
1732 // Method*s.
1733 static int method_comparator(Method* a, Method* b) {
1734   return a->name()->fast_compare(b->name());
1735 }
1736 
1737 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1738 // default_methods also uses this without the ordering for fast find_method
1739 void Method::sort_methods(Array<Method*>* methods, bool set_idnums, method_comparator_func func) {
1740   int length = methods->length();
1741   if (length > 1) {
1742     if (func == NULL) {
1743       func = method_comparator;
1744     }
1745     {
1746       NoSafepointVerifier nsv;
1747       QuickSort::sort(methods->data(), length, func, /*idempotent=*/false);
1748     }
1749     // Reset method ordering
1750     if (set_idnums) {
1751       for (int i = 0; i < length; i++) {
1752         Method* m = methods->at(i);
1753         m->set_method_idnum(i);
1754         m->set_orig_method_idnum(i);
1755       }
1756     }
1757   }
1758 }
1759 
1760 void Method::set_num_stack_arg_slots() {
1761   ResourceMark rm;
1762   int sizeargs = size_of_parameters();
1763   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
1764   VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
1765 
1766   int sig_index = 0;
1767   if (!is_static()) sig_bt[sig_index++] = T_OBJECT; // 'this'
1768   for (SignatureStream ss(signature()); !ss.at_return_type(); ss.next()) {
1769     BasicType t = ss.type();
1770     assert(type2size[t] == 1 || type2size[t] == 2, "size is 1 or 2");
1771     sig_bt[sig_index++] = t;
1772     if (type2size[t] == 2) sig_bt[sig_index++] = T_VOID;
1773   }
1774   assert(sig_index == sizeargs, "");
1775 
1776   _num_stack_arg_slots = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
1777 }
1778 
1779 //-----------------------------------------------------------------------------------
1780 // Non-product code unless JVM/TI needs it
1781 
1782 #if !defined(PRODUCT) || INCLUDE_JVMTI
1783 class SignatureTypePrinter : public SignatureTypeNames {
1784  private:
1785   outputStream* _st;
1786   bool _use_separator;
1787 
1788   void type_name(const char* name) {
1789     if (_use_separator) _st->print(", ");
1790     _st->print("%s", name);
1791     _use_separator = true;
1792   }
1793 
1794  public:
1795   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1796     _st = st;
1797     _use_separator = false;
1798   }
1799 
1800   void print_parameters()              { _use_separator = false; do_parameters_on(this); }
1801   void print_returntype()              { _use_separator = false; do_type(return_type()); }
1802 };
1803 
1804 
1805 void Method::print_name(outputStream* st) const {
1806   Thread *thread = Thread::current();
1807   ResourceMark rm(thread);
1808   st->print("%s ", is_static() ? "static" : "virtual");
1809   if (WizardMode) {
1810     st->print("%s.", method_holder()->internal_name());
1811     name()->print_symbol_on(st);
1812     signature()->print_symbol_on(st);
1813   } else {
1814     SignatureTypePrinter sig(signature(), st);
1815     sig.print_returntype();
1816     st->print(" %s.", method_holder()->internal_name());
1817     name()->print_symbol_on(st);
1818     st->print("(");
1819     sig.print_parameters();
1820     st->print(")");
1821   }
1822 }
1823 #endif // !PRODUCT || INCLUDE_JVMTI
1824 
1825 
1826 void Method::print_codes_on(outputStream* st) const {
1827   print_codes_on(0, code_size(), st);
1828 }
1829 
1830 void Method::print_codes_on(int from, int to, outputStream* st) const {
1831   Thread *thread = Thread::current();
1832   ResourceMark rm(thread);
1833   methodHandle mh (thread, (Method*)this);
1834   BytecodeStream s(mh);
1835   s.set_interval(from, to);
1836   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1837   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1838 }
1839 
1840 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1841   _bci = 0;
1842   _line = 0;
1843 };
1844 
1845 bool CompressedLineNumberReadStream::read_pair() {
1846   jubyte next = read_byte();
1847   // Check for terminator
1848   if (next == 0) return false;
1849   if (next == 0xFF) {
1850     // Escape character, regular compression used
1851     _bci  += read_signed_int();
1852     _line += read_signed_int();
1853   } else {
1854     // Single byte compression used
1855     _bci  += next >> 3;
1856     _line += next & 0x7;
1857   }
1858   return true;
1859 }
1860 
1861 #if INCLUDE_JVMTI
1862 
1863 Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1864   BreakpointInfo* bp = method_holder()->breakpoints();
1865   for (; bp != NULL; bp = bp->next()) {
1866     if (bp->match(this, bci)) {
1867       return bp->orig_bytecode();
1868     }
1869   }
1870   {
1871     ResourceMark rm;
1872     fatal("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci);
1873   }
1874   return Bytecodes::_shouldnotreachhere;
1875 }
1876 
1877 void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1878   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1879   BreakpointInfo* bp = method_holder()->breakpoints();
1880   for (; bp != NULL; bp = bp->next()) {
1881     if (bp->match(this, bci)) {
1882       bp->set_orig_bytecode(code);
1883       // and continue, in case there is more than one
1884     }
1885   }
1886 }
1887 
1888 void Method::set_breakpoint(int bci) {
1889   InstanceKlass* ik = method_holder();
1890   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1891   bp->set_next(ik->breakpoints());
1892   ik->set_breakpoints(bp);
1893   // do this last:
1894   bp->set(this);
1895 }
1896 
1897 static void clear_matches(Method* m, int bci) {
1898   InstanceKlass* ik = m->method_holder();
1899   BreakpointInfo* prev_bp = NULL;
1900   BreakpointInfo* next_bp;
1901   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1902     next_bp = bp->next();
1903     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1904     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1905       // do this first:
1906       bp->clear(m);
1907       // unhook it
1908       if (prev_bp != NULL)
1909         prev_bp->set_next(next_bp);
1910       else
1911         ik->set_breakpoints(next_bp);
1912       delete bp;
1913       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1914       // at same location. So we have multiple matching (method_index and bci)
1915       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1916       // breakpoint for clear_breakpoint request and keep all other method versions
1917       // BreakpointInfo for future clear_breakpoint request.
1918       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1919       // which is being called when class is unloaded. We delete all the Breakpoint
1920       // information for all versions of method. We may not correctly restore the original
1921       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1922       // so these methods won't be used anymore.
1923       if (bci >= 0) {
1924         break;
1925       }
1926     } else {
1927       // This one is a keeper.
1928       prev_bp = bp;
1929     }
1930   }
1931 }
1932 
1933 void Method::clear_breakpoint(int bci) {
1934   assert(bci >= 0, "");
1935   clear_matches(this, bci);
1936 }
1937 
1938 void Method::clear_all_breakpoints() {
1939   clear_matches(this, -1);
1940 }
1941 
1942 #endif // INCLUDE_JVMTI
1943 
1944 int Method::invocation_count() const {
1945   MethodCounters* mcs = method_counters();
1946   MethodData* mdo = method_data();
1947   if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
1948       ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1949     return InvocationCounter::count_limit;
1950   } else {
1951     return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
1952            ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1953   }
1954 }
1955 
1956 int Method::backedge_count() const {
1957   MethodCounters* mcs = method_counters();
1958   MethodData* mdo = method_data();
1959   if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
1960       ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1961     return InvocationCounter::count_limit;
1962   } else {
1963     return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
1964            ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1965   }
1966 }
1967 
1968 int Method::highest_comp_level() const {
1969   const MethodCounters* mcs = method_counters();
1970   if (mcs != NULL) {
1971     return mcs->highest_comp_level();
1972   } else {
1973     return CompLevel_none;
1974   }
1975 }
1976 
1977 int Method::highest_osr_comp_level() const {
1978   const MethodCounters* mcs = method_counters();
1979   if (mcs != NULL) {
1980     return mcs->highest_osr_comp_level();
1981   } else {
1982     return CompLevel_none;
1983   }
1984 }
1985 
1986 void Method::set_highest_comp_level(int level) {
1987   MethodCounters* mcs = method_counters();
1988   if (mcs != NULL) {
1989     mcs->set_highest_comp_level(level);
1990   }
1991 }
1992 
1993 void Method::set_highest_osr_comp_level(int level) {
1994   MethodCounters* mcs = method_counters();
1995   if (mcs != NULL) {
1996     mcs->set_highest_osr_comp_level(level);
1997   }
1998 }
1999 
2000 #if INCLUDE_JVMTI
2001 
2002 BreakpointInfo::BreakpointInfo(Method* m, int bci) {
2003   _bci = bci;
2004   _name_index = m->name_index();
2005   _signature_index = m->signature_index();
2006   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
2007   if (_orig_bytecode == Bytecodes::_breakpoint)
2008     _orig_bytecode = m->orig_bytecode_at(_bci);
2009   _next = NULL;
2010 }
2011 
2012 void BreakpointInfo::set(Method* method) {
2013 #ifdef ASSERT
2014   {
2015     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
2016     if (code == Bytecodes::_breakpoint)
2017       code = method->orig_bytecode_at(_bci);
2018     assert(orig_bytecode() == code, "original bytecode must be the same");
2019   }
2020 #endif
2021   Thread *thread = Thread::current();
2022   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
2023   method->incr_number_of_breakpoints(thread);
2024   {
2025     // Deoptimize all dependents on this method
2026     HandleMark hm(thread);
2027     methodHandle mh(thread, method);
2028     CodeCache::flush_dependents_on_method(mh);
2029   }
2030 }
2031 
2032 void BreakpointInfo::clear(Method* method) {
2033   *method->bcp_from(_bci) = orig_bytecode();
2034   assert(method->number_of_breakpoints() > 0, "must not go negative");
2035   method->decr_number_of_breakpoints(Thread::current());
2036 }
2037 
2038 #endif // INCLUDE_JVMTI
2039 
2040 // jmethodID handling
2041 
2042 // This is a block allocating object, sort of like JNIHandleBlock, only a
2043 // lot simpler.
2044 // It's allocated on the CHeap because once we allocate a jmethodID, we can
2045 // never get rid of it.
2046 
2047 static const int min_block_size = 8;
2048 
2049 class JNIMethodBlockNode : public CHeapObj<mtClass> {
2050   friend class JNIMethodBlock;
2051   Method**        _methods;
2052   int             _number_of_methods;
2053   int             _top;
2054   JNIMethodBlockNode* _next;
2055 
2056  public:
2057 
2058   JNIMethodBlockNode(int num_methods = min_block_size);
2059 
2060   ~JNIMethodBlockNode() { FREE_C_HEAP_ARRAY(Method*, _methods); }
2061 
2062   void ensure_methods(int num_addl_methods) {
2063     if (_top < _number_of_methods) {
2064       num_addl_methods -= _number_of_methods - _top;
2065       if (num_addl_methods <= 0) {
2066         return;
2067       }
2068     }
2069     if (_next == NULL) {
2070       _next = new JNIMethodBlockNode(MAX2(num_addl_methods, min_block_size));
2071     } else {
2072       _next->ensure_methods(num_addl_methods);
2073     }
2074   }
2075 };
2076 
2077 class JNIMethodBlock : public CHeapObj<mtClass> {
2078   JNIMethodBlockNode _head;
2079   JNIMethodBlockNode *_last_free;
2080  public:
2081   static Method* const _free_method;
2082 
2083   JNIMethodBlock(int initial_capacity = min_block_size)
2084       : _head(initial_capacity), _last_free(&_head) {}
2085 
2086   void ensure_methods(int num_addl_methods) {
2087     _last_free->ensure_methods(num_addl_methods);
2088   }
2089 
2090   Method** add_method(Method* m) {
2091     for (JNIMethodBlockNode* b = _last_free; b != NULL; b = b->_next) {
2092       if (b->_top < b->_number_of_methods) {
2093         // top points to the next free entry.
2094         int i = b->_top;
2095         b->_methods[i] = m;
2096         b->_top++;
2097         _last_free = b;
2098         return &(b->_methods[i]);
2099       } else if (b->_top == b->_number_of_methods) {
2100         // if the next free entry ran off the block see if there's a free entry
2101         for (int i = 0; i < b->_number_of_methods; i++) {
2102           if (b->_methods[i] == _free_method) {
2103             b->_methods[i] = m;
2104             _last_free = b;
2105             return &(b->_methods[i]);
2106           }
2107         }
2108         // Only check each block once for frees.  They're very unlikely.
2109         // Increment top past the end of the block.
2110         b->_top++;
2111       }
2112       // need to allocate a next block.
2113       if (b->_next == NULL) {
2114         b->_next = _last_free = new JNIMethodBlockNode();
2115       }
2116     }
2117     guarantee(false, "Should always allocate a free block");
2118     return NULL;
2119   }
2120 
2121   bool contains(Method** m) {
2122     if (m == NULL) return false;
2123     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2124       if (b->_methods <= m && m < b->_methods + b->_number_of_methods) {
2125         // This is a bit of extra checking, for two reasons.  One is
2126         // that contains() deals with pointers that are passed in by
2127         // JNI code, so making sure that the pointer is aligned
2128         // correctly is valuable.  The other is that <= and > are
2129         // technically not defined on pointers, so the if guard can
2130         // pass spuriously; no modern compiler is likely to make that
2131         // a problem, though (and if one did, the guard could also
2132         // fail spuriously, which would be bad).
2133         ptrdiff_t idx = m - b->_methods;
2134         if (b->_methods + idx == m) {
2135           return true;
2136         }
2137       }
2138     }
2139     return false;  // not found
2140   }
2141 
2142   // Doesn't really destroy it, just marks it as free so it can be reused.
2143   void destroy_method(Method** m) {
2144 #ifdef ASSERT
2145     assert(contains(m), "should be a methodID");
2146 #endif // ASSERT
2147     *m = _free_method;
2148   }
2149 
2150   // During class unloading the methods are cleared, which is different
2151   // than freed.
2152   void clear_all_methods() {
2153     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2154       for (int i = 0; i< b->_number_of_methods; i++) {
2155         b->_methods[i] = NULL;
2156       }
2157     }
2158   }
2159 #ifndef PRODUCT
2160   int count_methods() {
2161     // count all allocated methods
2162     int count = 0;
2163     for (JNIMethodBlockNode* b = &_head; b != NULL; b = b->_next) {
2164       for (int i = 0; i< b->_number_of_methods; i++) {
2165         if (b->_methods[i] != _free_method) count++;
2166       }
2167     }
2168     return count;
2169   }
2170 #endif // PRODUCT
2171 };
2172 
2173 // Something that can't be mistaken for an address or a markWord
2174 Method* const JNIMethodBlock::_free_method = (Method*)55;
2175 
2176 JNIMethodBlockNode::JNIMethodBlockNode(int num_methods) : _top(0), _next(NULL) {
2177   _number_of_methods = MAX2(num_methods, min_block_size);
2178   _methods = NEW_C_HEAP_ARRAY(Method*, _number_of_methods, mtInternal);
2179   for (int i = 0; i < _number_of_methods; i++) {
2180     _methods[i] = JNIMethodBlock::_free_method;
2181   }
2182 }
2183 
2184 void Method::ensure_jmethod_ids(ClassLoaderData* loader_data, int capacity) {
2185   ClassLoaderData* cld = loader_data;
2186   if (!SafepointSynchronize::is_at_safepoint()) {
2187     // Have to add jmethod_ids() to class loader data thread-safely.
2188     // Also have to add the method to the list safely, which the lock
2189     // protects as well.
2190     MutexLocker ml(JmethodIdCreation_lock,  Mutex::_no_safepoint_check_flag);
2191     if (cld->jmethod_ids() == NULL) {
2192       cld->set_jmethod_ids(new JNIMethodBlock(capacity));
2193     } else {
2194       cld->jmethod_ids()->ensure_methods(capacity);
2195     }
2196   } else {
2197     // At safepoint, we are single threaded and can set this.
2198     if (cld->jmethod_ids() == NULL) {
2199       cld->set_jmethod_ids(new JNIMethodBlock(capacity));
2200     } else {
2201       cld->jmethod_ids()->ensure_methods(capacity);
2202     }
2203   }
2204 }
2205 
2206 // Add a method id to the jmethod_ids
2207 jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
2208   ClassLoaderData* cld = loader_data;
2209 
2210   if (!SafepointSynchronize::is_at_safepoint()) {
2211     // Have to add jmethod_ids() to class loader data thread-safely.
2212     // Also have to add the method to the list safely, which the lock
2213     // protects as well.
2214     MutexLocker ml(JmethodIdCreation_lock,  Mutex::_no_safepoint_check_flag);
2215     if (cld->jmethod_ids() == NULL) {
2216       cld->set_jmethod_ids(new JNIMethodBlock());
2217     }
2218     // jmethodID is a pointer to Method*
2219     return (jmethodID)cld->jmethod_ids()->add_method(m);
2220   } else {
2221     // At safepoint, we are single threaded and can set this.
2222     if (cld->jmethod_ids() == NULL) {
2223       cld->set_jmethod_ids(new JNIMethodBlock());
2224     }
2225     // jmethodID is a pointer to Method*
2226     return (jmethodID)cld->jmethod_ids()->add_method(m);
2227   }
2228 }
2229 
2230 jmethodID Method::jmethod_id() {
2231   methodHandle mh(Thread::current(), this);
2232   return method_holder()->get_jmethod_id(mh);
2233 }
2234 
2235 // Mark a jmethodID as free.  This is called when there is a data race in
2236 // InstanceKlass while creating the jmethodID cache.
2237 void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
2238   ClassLoaderData* cld = loader_data;
2239   Method** ptr = (Method**)m;
2240   assert(cld->jmethod_ids() != NULL, "should have method handles");
2241   cld->jmethod_ids()->destroy_method(ptr);
2242 }
2243 
2244 void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
2245   // Can't assert the method_holder is the same because the new method has the
2246   // scratch method holder.
2247   assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
2248            == new_method->method_holder()->class_loader() ||
2249            new_method->method_holder()->class_loader() == NULL, // allow Unsafe substitution
2250          "changing to a different class loader");
2251   // Just change the method in place, jmethodID pointer doesn't change.
2252   *((Method**)jmid) = new_method;
2253 }
2254 
2255 bool Method::is_method_id(jmethodID mid) {
2256   Method* m = resolve_jmethod_id(mid);
2257   assert(m != NULL, "should be called with non-null method");
2258   InstanceKlass* ik = m->method_holder();
2259   ClassLoaderData* cld = ik->class_loader_data();
2260   if (cld->jmethod_ids() == NULL) return false;
2261   return (cld->jmethod_ids()->contains((Method**)mid));
2262 }
2263 
2264 Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
2265   if (mid == NULL) return NULL;
2266   Method* o = resolve_jmethod_id(mid);
2267   if (o == NULL || o == JNIMethodBlock::_free_method) {
2268     return NULL;
2269   }
2270   // Method should otherwise be valid. Assert for testing.
2271   assert(is_valid_method(o), "should be valid jmethodid");
2272   // If the method's class holder object is unreferenced, but not yet marked as
2273   // unloaded, we need to return NULL here too because after a safepoint, its memory
2274   // will be reclaimed.
2275   return o->method_holder()->is_loader_alive() ? o : NULL;
2276 };
2277 
2278 void Method::set_on_stack(const bool value) {
2279   // Set both the method itself and its constant pool.  The constant pool
2280   // on stack means some method referring to it is also on the stack.
2281   constants()->set_on_stack(value);
2282 
2283   bool already_set = on_stack();
2284   _access_flags.set_on_stack(value);
2285   if (value && !already_set) {
2286     MetadataOnStackMark::record(this);
2287   }
2288 }
2289 
2290 void Method::record_marking_cycle() {
2291   // If any method is on the stack in continuations, none of them can be reclaimed,
2292   // so save the marking cycle to check for the whole class in the cpCache.
2293   // The cpCache is writeable.
2294   constants()->cache()->record_marking_cycle();
2295 }
2296 
2297 // Called when the class loader is unloaded to make all methods weak.
2298 void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
2299   loader_data->jmethod_ids()->clear_all_methods();
2300 }
2301 
2302 bool Method::has_method_vptr(const void* ptr) {
2303   Method m;
2304   // This assumes that the vtbl pointer is the first word of a C++ object.
2305   return dereference_vptr(&m) == dereference_vptr(ptr);
2306 }
2307 
2308 // Check that this pointer is valid by checking that the vtbl pointer matches
2309 bool Method::is_valid_method(const Method* m) {
2310   if (m == NULL) {
2311     return false;
2312   } else if ((intptr_t(m) & (wordSize-1)) != 0) {
2313     // Quick sanity check on pointer.
2314     return false;
2315   } else if (m->is_shared()) {
2316     return CppVtables::is_valid_shared_method(m);
2317   } else if (Metaspace::contains_non_shared(m)) {
2318     return has_method_vptr((const void*)m);
2319   } else {
2320     return false;
2321   }
2322 }
2323 
2324 #ifndef PRODUCT
2325 void Method::print_jmethod_ids_count(const ClassLoaderData* loader_data, outputStream* out) {
2326   out->print("%d", loader_data->jmethod_ids()->count_methods());
2327 }
2328 #endif // PRODUCT
2329 
2330 
2331 // Printing
2332 
2333 #ifndef PRODUCT
2334 
2335 void Method::print_on(outputStream* st) const {
2336   ResourceMark rm;
2337   assert(is_method(), "must be method");
2338   st->print_cr("%s", internal_name());
2339   st->print_cr(" - this oop:          " INTPTR_FORMAT, p2i(this));
2340   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
2341   st->print   (" - constants:         " INTPTR_FORMAT " ", p2i(constants()));
2342   constants()->print_value_on(st); st->cr();
2343   st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
2344   st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
2345   st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
2346   st->print_cr(" - max stack:         %d",   max_stack());
2347   st->print_cr(" - max locals:        %d",   max_locals());
2348   st->print_cr(" - size of params:    %d",   size_of_parameters());
2349   st->print_cr(" - method size:       %d",   method_size());
2350   if (intrinsic_id() != vmIntrinsics::_none)
2351     st->print_cr(" - intrinsic id:      %d %s", vmIntrinsics::as_int(intrinsic_id()), vmIntrinsics::name_at(intrinsic_id()));
2352   if (highest_comp_level() != CompLevel_none)
2353     st->print_cr(" - highest level:     %d", highest_comp_level());
2354   st->print_cr(" - vtable index:      %d",   _vtable_index);
2355   st->print_cr(" - i2i entry:         " INTPTR_FORMAT, p2i(interpreter_entry()));
2356   st->print(   " - adapters:          ");
2357   AdapterHandlerEntry* a = ((Method*)this)->adapter();
2358   if (a == NULL)
2359     st->print_cr(INTPTR_FORMAT, p2i(a));
2360   else
2361     a->print_adapter_on(st);
2362   st->print_cr(" - compiled entry     " INTPTR_FORMAT, p2i(from_compiled_entry()));
2363   st->print_cr(" - code size:         %d",   code_size());
2364   if (code_size() != 0) {
2365     st->print_cr(" - code start:        " INTPTR_FORMAT, p2i(code_base()));
2366     st->print_cr(" - code end (excl):   " INTPTR_FORMAT, p2i(code_base() + code_size()));
2367   }
2368   if (method_data() != NULL) {
2369     st->print_cr(" - method data:       " INTPTR_FORMAT, p2i(method_data()));
2370   }
2371   st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
2372   if (checked_exceptions_length() > 0) {
2373     CheckedExceptionElement* table = checked_exceptions_start();
2374     st->print_cr(" - checked ex start:  " INTPTR_FORMAT, p2i(table));
2375     if (Verbose) {
2376       for (int i = 0; i < checked_exceptions_length(); i++) {
2377         st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
2378       }
2379     }
2380   }
2381   if (has_linenumber_table()) {
2382     u_char* table = compressed_linenumber_table();
2383     st->print_cr(" - linenumber start:  " INTPTR_FORMAT, p2i(table));
2384     if (Verbose) {
2385       CompressedLineNumberReadStream stream(table);
2386       while (stream.read_pair()) {
2387         st->print_cr("   - line %d: %d", stream.line(), stream.bci());
2388       }
2389     }
2390   }
2391   st->print_cr(" - localvar length:   %d",   localvariable_table_length());
2392   if (localvariable_table_length() > 0) {
2393     LocalVariableTableElement* table = localvariable_table_start();
2394     st->print_cr(" - localvar start:    " INTPTR_FORMAT, p2i(table));
2395     if (Verbose) {
2396       for (int i = 0; i < localvariable_table_length(); i++) {
2397         int bci = table[i].start_bci;
2398         int len = table[i].length;
2399         const char* name = constants()->printable_name_at(table[i].name_cp_index);
2400         const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
2401         int slot = table[i].slot;
2402         st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
2403       }
2404     }
2405   }
2406   if (code() != NULL) {
2407     st->print   (" - compiled code: ");
2408     code()->print_value_on(st);
2409   }
2410   if (is_native()) {
2411     st->print_cr(" - native function:   " INTPTR_FORMAT, p2i(native_function()));
2412     st->print_cr(" - signature handler: " INTPTR_FORMAT, p2i(signature_handler()));
2413   }
2414 }
2415 
2416 void Method::print_linkage_flags(outputStream* st) {
2417   access_flags().print_on(st);
2418   if (is_default_method()) {
2419     st->print("default ");
2420   }
2421   if (is_overpass()) {
2422     st->print("overpass ");
2423   }
2424 }
2425 #endif //PRODUCT
2426 
2427 void Method::print_value_on(outputStream* st) const {
2428   assert(is_method(), "must be method");
2429   st->print("%s", internal_name());
2430   print_address_on(st);
2431   st->print(" ");
2432   name()->print_value_on(st);
2433   st->print(" ");
2434   signature()->print_value_on(st);
2435   st->print(" in ");
2436   method_holder()->print_value_on(st);
2437   if (WizardMode) st->print("#%d", _vtable_index);
2438   if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
2439   if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
2440 }
2441 
2442 // LogTouchedMethods and PrintTouchedMethods
2443 
2444 // TouchedMethodRecord -- we can't use a HashtableEntry<Method*> because
2445 // the Method may be garbage collected. Let's roll our own hash table.
2446 class TouchedMethodRecord : CHeapObj<mtTracing> {
2447 public:
2448   // It's OK to store Symbols here because they will NOT be GC'ed if
2449   // LogTouchedMethods is enabled.
2450   TouchedMethodRecord* _next;
2451   Symbol* _class_name;
2452   Symbol* _method_name;
2453   Symbol* _method_signature;
2454 };
2455 
2456 static const int TOUCHED_METHOD_TABLE_SIZE = 20011;
2457 static TouchedMethodRecord** _touched_method_table = NULL;
2458 
2459 void Method::log_touched(Thread* current) {
2460 
2461   const int table_size = TOUCHED_METHOD_TABLE_SIZE;
2462   Symbol* my_class = klass_name();
2463   Symbol* my_name  = name();
2464   Symbol* my_sig   = signature();
2465 
2466   unsigned int hash = my_class->identity_hash() +
2467                       my_name->identity_hash() +
2468                       my_sig->identity_hash();
2469   juint index = juint(hash) % table_size;
2470 
2471   MutexLocker ml(current, TouchedMethodLog_lock);
2472   if (_touched_method_table == NULL) {
2473     _touched_method_table = NEW_C_HEAP_ARRAY2(TouchedMethodRecord*, table_size,
2474                                               mtTracing, CURRENT_PC);
2475     memset(_touched_method_table, 0, sizeof(TouchedMethodRecord*)*table_size);
2476   }
2477 
2478   TouchedMethodRecord* ptr = _touched_method_table[index];
2479   while (ptr) {
2480     if (ptr->_class_name       == my_class &&
2481         ptr->_method_name      == my_name &&
2482         ptr->_method_signature == my_sig) {
2483       return;
2484     }
2485     if (ptr->_next == NULL) break;
2486     ptr = ptr->_next;
2487   }
2488   TouchedMethodRecord* nptr = NEW_C_HEAP_OBJ(TouchedMethodRecord, mtTracing);
2489   my_class->increment_refcount();
2490   my_name->increment_refcount();
2491   my_sig->increment_refcount();
2492   nptr->_class_name         = my_class;
2493   nptr->_method_name        = my_name;
2494   nptr->_method_signature   = my_sig;
2495   nptr->_next               = NULL;
2496 
2497   if (ptr == NULL) {
2498     // first
2499     _touched_method_table[index] = nptr;
2500   } else {
2501     ptr->_next = nptr;
2502   }
2503 }
2504 
2505 void Method::print_touched_methods(outputStream* out) {
2506   MutexLocker ml(Thread::current()->is_VM_thread() ? NULL : TouchedMethodLog_lock);
2507   out->print_cr("# Method::print_touched_methods version 1");
2508   if (_touched_method_table) {
2509     for (int i = 0; i < TOUCHED_METHOD_TABLE_SIZE; i++) {
2510       TouchedMethodRecord* ptr = _touched_method_table[i];
2511       while(ptr) {
2512         ptr->_class_name->print_symbol_on(out);       out->print(".");
2513         ptr->_method_name->print_symbol_on(out);      out->print(":");
2514         ptr->_method_signature->print_symbol_on(out); out->cr();
2515         ptr = ptr->_next;
2516       }
2517     }
2518   }
2519 }
2520 
2521 // Verification
2522 
2523 void Method::verify_on(outputStream* st) {
2524   guarantee(is_method(), "object must be method");
2525   guarantee(constants()->is_constantPool(), "should be constant pool");
2526   MethodData* md = method_data();
2527   guarantee(md == NULL ||
2528       md->is_methodData(), "should be method data");
2529 }
--- EOF ---