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