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