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