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