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