1 /*
   2  * Copyright (c) 1997, 2013, 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/systemDictionary.hpp"
  27 #include "code/debugInfoRec.hpp"
  28 #include "gc_interface/collectedHeap.inline.hpp"
  29 #include "interpreter/bytecodeStream.hpp"
  30 #include "interpreter/bytecodeTracer.hpp"
  31 #include "interpreter/bytecodes.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/oopMapCache.hpp"
  34 #include "memory/gcLocker.hpp"
  35 #include "memory/generation.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "oops/klassOop.hpp"
  38 #include "oops/methodDataOop.hpp"
  39 #include "oops/methodOop.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "oops/symbol.hpp"
  42 #include "prims/jvmtiExport.hpp"
  43 #include "prims/methodHandles.hpp"
  44 #include "prims/nativeLookup.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/compilationPolicy.hpp"
  47 #include "runtime/frame.inline.hpp"
  48 #include "runtime/handles.inline.hpp"
  49 #include "runtime/relocator.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "runtime/signature.hpp"
  52 #include "utilities/quickSort.hpp"
  53 #include "utilities/xmlstream.hpp"
  54 
  55 
  56 // Implementation of methodOopDesc
  57 
  58 address methodOopDesc::get_i2c_entry() {
  59   assert(_adapter != NULL, "must have");
  60   return _adapter->get_i2c_entry();
  61 }
  62 
  63 address methodOopDesc::get_c2i_entry() {
  64   assert(_adapter != NULL, "must have");
  65   return _adapter->get_c2i_entry();
  66 }
  67 
  68 address methodOopDesc::get_c2i_unverified_entry() {
  69   assert(_adapter != NULL, "must have");
  70   return _adapter->get_c2i_unverified_entry();
  71 }
  72 
  73 char* methodOopDesc::name_and_sig_as_C_string() const {
  74   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature());
  75 }
  76 
  77 char* methodOopDesc::name_and_sig_as_C_string(char* buf, int size) const {
  78   return name_and_sig_as_C_string(Klass::cast(constants()->pool_holder()), name(), signature(), buf, size);
  79 }
  80 
  81 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
  82   const char* klass_name = klass->external_name();
  83   int klass_name_len  = (int)strlen(klass_name);
  84   int method_name_len = method_name->utf8_length();
  85   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
  86   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
  87   strcpy(dest, klass_name);
  88   dest[klass_name_len] = '.';
  89   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
  90   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
  91   dest[len] = 0;
  92   return dest;
  93 }
  94 
  95 char* methodOopDesc::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
  96   Symbol* klass_name = klass->name();
  97   klass_name->as_klass_external_name(buf, size);
  98   int len = (int)strlen(buf);
  99 
 100   if (len < size - 1) {
 101     buf[len++] = '.';
 102 
 103     method_name->as_C_string(&(buf[len]), size - len);
 104     len = (int)strlen(buf);
 105 
 106     signature->as_C_string(&(buf[len]), size - len);
 107   }
 108 
 109   return buf;
 110 }
 111 
 112 int  methodOopDesc::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
 113   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 114   // access exception table
 115   ExceptionTable table(mh());
 116   int length = table.length();
 117   // iterate through all entries sequentially
 118   constantPoolHandle pool(THREAD, mh->constants());
 119   for (int i = 0; i < length; i ++) {
 120     //reacquire the table in case a GC happened
 121     ExceptionTable table(mh());
 122     int beg_bci = table.start_pc(i);
 123     int end_bci = table.end_pc(i);
 124     assert(beg_bci <= end_bci, "inconsistent exception table");
 125     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 126       // exception handler bci range covers throw_bci => investigate further
 127       int handler_bci = table.handler_pc(i);
 128       int klass_index = table.catch_type_index(i);
 129       if (klass_index == 0) {
 130         return handler_bci;
 131       } else if (ex_klass.is_null()) {
 132         return handler_bci;
 133       } else {
 134         // we know the exception class => get the constraint class
 135         // this may require loading of the constraint class; if verification
 136         // fails or some other exception occurs, return handler_bci
 137         klassOop k = pool->klass_at(klass_index, CHECK_(handler_bci));
 138         KlassHandle klass = KlassHandle(THREAD, k);
 139         assert(klass.not_null(), "klass not loaded");
 140         if (ex_klass->is_subtype_of(klass())) {
 141           return handler_bci;
 142         }
 143       }
 144     }
 145   }
 146 
 147   return -1;
 148 }
 149 
 150 void methodOopDesc::mask_for(int bci, InterpreterOopMap* mask) {
 151 
 152   Thread* myThread    = Thread::current();
 153   methodHandle h_this(myThread, this);
 154 #ifdef ASSERT
 155   bool has_capability = myThread->is_VM_thread() ||
 156                         myThread->is_ConcurrentGC_thread() ||
 157                         myThread->is_GC_task_thread();
 158 
 159   if (!has_capability) {
 160     if (!VerifyStack && !VerifyLastFrame) {
 161       // verify stack calls this outside VM thread
 162       warning("oopmap should only be accessed by the "
 163               "VM, GC task or CMS threads (or during debugging)");
 164       InterpreterOopMap local_mask;
 165       instanceKlass::cast(method_holder())->mask_for(h_this, bci, &local_mask);
 166       local_mask.print();
 167     }
 168   }
 169 #endif
 170   instanceKlass::cast(method_holder())->mask_for(h_this, bci, mask);
 171   return;
 172 }
 173 
 174 
 175 int methodOopDesc::bci_from(address bcp) const {
 176 #ifdef ASSERT
 177   { ResourceMark rm;
 178   assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
 179          err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
 180   }
 181 #endif
 182   return bcp - code_base();
 183 }
 184 
 185 
 186 // Return (int)bcx if it appears to be a valid BCI.
 187 // Return bci_from((address)bcx) if it appears to be a valid BCP.
 188 // Return -1 otherwise.
 189 // Used by profiling code, when invalid data is a possibility.
 190 // The caller is responsible for validating the methodOop itself.
 191 int methodOopDesc::validate_bci_from_bcx(intptr_t bcx) const {
 192   // keep bci as -1 if not a valid bci
 193   int bci = -1;
 194   if (bcx == 0 || (address)bcx == code_base()) {
 195     // code_size() may return 0 and we allow 0 here
 196     // the method may be native
 197     bci = 0;
 198   } else if (frame::is_bci(bcx)) {
 199     if (bcx < code_size()) {
 200       bci = (int)bcx;
 201     }
 202   } else if (contains((address)bcx)) {
 203     bci = (address)bcx - code_base();
 204   }
 205   // Assert that if we have dodged any asserts, bci is negative.
 206   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 207   return bci;
 208 }
 209 
 210 address methodOopDesc::bcp_from(int bci) const {
 211   assert((is_native() && bci == 0)  || (!is_native() && 0 <= bci && bci < code_size()), "illegal bci");
 212   address bcp = code_base() + bci;
 213   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 214   return bcp;
 215 }
 216 
 217 
 218 int methodOopDesc::object_size(bool is_native) {
 219   // If native, then include pointers for native_function and signature_handler
 220   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 221   int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
 222   return align_object_size(header_size() + extra_words);
 223 }
 224 
 225 
 226 Symbol* methodOopDesc::klass_name() const {
 227   klassOop k = method_holder();
 228   assert(k->is_klass(), "must be klass");
 229   instanceKlass* ik = (instanceKlass*) k->klass_part();
 230   return ik->name();
 231 }
 232 
 233 
 234 void methodOopDesc::set_interpreter_kind() {
 235   int kind = Interpreter::method_kind(methodOop(this));
 236   assert(kind != Interpreter::invalid,
 237          "interpreter entry must be valid");
 238   set_interpreter_kind(kind);
 239 }
 240 
 241 
 242 // Attempt to return method oop to original state.  Clear any pointers
 243 // (to objects outside the shared spaces).  We won't be able to predict
 244 // where they should point in a new JVM.  Further initialize some
 245 // entries now in order allow them to be write protected later.
 246 
 247 void methodOopDesc::remove_unshareable_info() {
 248   unlink_method();
 249   set_interpreter_kind();
 250 }
 251 
 252 
 253 bool methodOopDesc::was_executed_more_than(int n) {
 254   // Invocation counter is reset when the methodOop is compiled.
 255   // If the method has compiled code we therefore assume it has
 256   // be excuted more than n times.
 257   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 258     // interpreter doesn't bump invocation counter of trivial methods
 259     // compiler does not bump invocation counter of compiled methods
 260     return true;
 261   }
 262   else if (_invocation_counter.carry() || (method_data() != NULL && method_data()->invocation_counter()->carry())) {
 263     // The carry bit is set when the counter overflows and causes
 264     // a compilation to occur.  We don't know how many times
 265     // the counter has been reset, so we simply assume it has
 266     // been executed more than n times.
 267     return true;
 268   } else {
 269     return invocation_count() > n;
 270   }
 271 }
 272 
 273 #ifndef PRODUCT
 274 void methodOopDesc::print_invocation_count() {
 275   if (is_static()) tty->print("static ");
 276   if (is_final()) tty->print("final ");
 277   if (is_synchronized()) tty->print("synchronized ");
 278   if (is_native()) tty->print("native ");
 279   method_holder()->klass_part()->name()->print_symbol_on(tty);
 280   tty->print(".");
 281   name()->print_symbol_on(tty);
 282   signature()->print_symbol_on(tty);
 283 
 284   if (WizardMode) {
 285     // dump the size of the byte codes
 286     tty->print(" {%d}", code_size());
 287   }
 288   tty->cr();
 289 
 290   tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
 291   tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
 292   tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
 293   if (CountCompiledCalls) {
 294     tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
 295   }
 296 
 297 }
 298 #endif
 299 
 300 // Build a methodDataOop object to hold information about this method
 301 // collected in the interpreter.
 302 void methodOopDesc::build_interpreter_method_data(methodHandle method, TRAPS) {
 303   // Do not profile method if current thread holds the pending list lock,
 304   // which avoids deadlock for acquiring the MethodData_lock.
 305   if (instanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
 306     return;
 307   }
 308 
 309   // Grab a lock here to prevent multiple
 310   // methodDataOops from being created.
 311   MutexLocker ml(MethodData_lock, THREAD);
 312   if (method->method_data() == NULL) {
 313     methodDataOop method_data = oopFactory::new_methodData(method, CHECK);
 314     method->set_method_data(method_data);
 315     if (PrintMethodData && (Verbose || WizardMode)) {
 316       ResourceMark rm(THREAD);
 317       tty->print("build_interpreter_method_data for ");
 318       method->print_name(tty);
 319       tty->cr();
 320       // At the end of the run, the MDO, full of data, will be dumped.
 321     }
 322   }
 323 }
 324 
 325 void methodOopDesc::cleanup_inline_caches() {
 326   // The current system doesn't use inline caches in the interpreter
 327   // => nothing to do (keep this method around for future use)
 328 }
 329 
 330 
 331 int methodOopDesc::extra_stack_words() {
 332   // not an inline function, to avoid a header dependency on Interpreter
 333   return extra_stack_entries() * Interpreter::stackElementSize;
 334 }
 335 
 336 
 337 void methodOopDesc::compute_size_of_parameters(Thread *thread) {
 338   ArgumentSizeComputer asc(signature());
 339   set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
 340 }
 341 
 342 #ifdef CC_INTERP
 343 void methodOopDesc::set_result_index(BasicType type)          {
 344   _result_index = Interpreter::BasicType_as_index(type);
 345 }
 346 #endif
 347 
 348 BasicType methodOopDesc::result_type() const {
 349   ResultTypeFinder rtf(signature());
 350   return rtf.type();
 351 }
 352 
 353 
 354 bool methodOopDesc::is_empty_method() const {
 355   return  code_size() == 1
 356       && *code_base() == Bytecodes::_return;
 357 }
 358 
 359 
 360 bool methodOopDesc::is_vanilla_constructor() const {
 361   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 362   // which only calls the superclass vanilla constructor and possibly does stores of
 363   // zero constants to local fields:
 364   //
 365   //   aload_0
 366   //   invokespecial
 367   //   indexbyte1
 368   //   indexbyte2
 369   //
 370   // followed by an (optional) sequence of:
 371   //
 372   //   aload_0
 373   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 374   //   putfield
 375   //   indexbyte1
 376   //   indexbyte2
 377   //
 378   // followed by:
 379   //
 380   //   return
 381 
 382   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 383   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 384   int size = code_size();
 385   // Check if size match
 386   if (size == 0 || size % 5 != 0) return false;
 387   address cb = code_base();
 388   int last = size - 1;
 389   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 390     // Does not call superclass default constructor
 391     return false;
 392   }
 393   // Check optional sequence
 394   for (int i = 4; i < last; i += 5) {
 395     if (cb[i] != Bytecodes::_aload_0) return false;
 396     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 397     if (cb[i+2] != Bytecodes::_putfield) return false;
 398   }
 399   return true;
 400 }
 401 
 402 
 403 bool methodOopDesc::compute_has_loops_flag() {
 404   BytecodeStream bcs(methodOop(this));
 405   Bytecodes::Code bc;
 406 
 407   while ((bc = bcs.next()) >= 0) {
 408     switch( bc ) {
 409       case Bytecodes::_ifeq:
 410       case Bytecodes::_ifnull:
 411       case Bytecodes::_iflt:
 412       case Bytecodes::_ifle:
 413       case Bytecodes::_ifne:
 414       case Bytecodes::_ifnonnull:
 415       case Bytecodes::_ifgt:
 416       case Bytecodes::_ifge:
 417       case Bytecodes::_if_icmpeq:
 418       case Bytecodes::_if_icmpne:
 419       case Bytecodes::_if_icmplt:
 420       case Bytecodes::_if_icmpgt:
 421       case Bytecodes::_if_icmple:
 422       case Bytecodes::_if_icmpge:
 423       case Bytecodes::_if_acmpeq:
 424       case Bytecodes::_if_acmpne:
 425       case Bytecodes::_goto:
 426       case Bytecodes::_jsr:
 427         if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
 428         break;
 429 
 430       case Bytecodes::_goto_w:
 431       case Bytecodes::_jsr_w:
 432         if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
 433         break;
 434     }
 435   }
 436   _access_flags.set_loops_flag_init();
 437   return _access_flags.has_loops();
 438 }
 439 
 440 
 441 bool methodOopDesc::is_final_method() const {
 442   // %%% Should return true for private methods also,
 443   // since there is no way to override them.
 444   return is_final() || Klass::cast(method_holder())->is_final();
 445 }
 446 
 447 
 448 bool methodOopDesc::is_strict_method() const {
 449   return is_strict();
 450 }
 451 
 452 
 453 bool methodOopDesc::can_be_statically_bound() const {
 454   if (is_final_method())  return true;
 455   return vtable_index() == nonvirtual_vtable_index;
 456 }
 457 
 458 
 459 bool methodOopDesc::is_accessor() const {
 460   if (code_size() != 5) return false;
 461   if (size_of_parameters() != 1) return false;
 462   if (java_code_at(0) != Bytecodes::_aload_0 ) return false;
 463   if (java_code_at(1) != Bytecodes::_getfield) return false;
 464   if (java_code_at(4) != Bytecodes::_areturn &&
 465       java_code_at(4) != Bytecodes::_ireturn ) return false;
 466   return true;
 467 }
 468 
 469 
 470 bool methodOopDesc::is_initializer() const {
 471   return name() == vmSymbols::object_initializer_name() || is_static_initializer();
 472 }
 473 
 474 bool methodOopDesc::has_valid_initializer_flags() const {
 475   return (is_static() ||
 476           instanceKlass::cast(method_holder())->major_version() < 51);
 477 }
 478 
 479 bool methodOopDesc::is_static_initializer() const {
 480   // For classfiles version 51 or greater, ensure that the clinit method is
 481   // static.  Non-static methods with the name "<clinit>" are not static
 482   // initializers. (older classfiles exempted for backward compatibility)
 483   return name() == vmSymbols::class_initializer_name() &&
 484          has_valid_initializer_flags();
 485 }
 486 
 487 
 488 objArrayHandle methodOopDesc::resolved_checked_exceptions_impl(methodOop this_oop, TRAPS) {
 489   int length = this_oop->checked_exceptions_length();
 490   if (length == 0) {  // common case
 491     return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
 492   } else {
 493     methodHandle h_this(THREAD, this_oop);
 494     objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
 495     objArrayHandle mirrors (THREAD, m_oop);
 496     for (int i = 0; i < length; i++) {
 497       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 498       klassOop k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 499       assert(Klass::cast(k)->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
 500       mirrors->obj_at_put(i, Klass::cast(k)->java_mirror());
 501     }
 502     return mirrors;
 503   }
 504 };
 505 
 506 
 507 int methodOopDesc::line_number_from_bci(int bci) const {
 508   if (bci == SynchronizationEntryBCI) bci = 0;
 509   assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
 510   int best_bci  =  0;
 511   int best_line = -1;
 512 
 513   if (has_linenumber_table()) {
 514     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 515     // Not necessarily sorted and not necessarily one-to-one.
 516     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 517     while (stream.read_pair()) {
 518       if (stream.bci() == bci) {
 519         // perfect match
 520         return stream.line();
 521       } else {
 522         // update best_bci/line
 523         if (stream.bci() < bci && stream.bci() >= best_bci) {
 524           best_bci  = stream.bci();
 525           best_line = stream.line();
 526         }
 527       }
 528     }
 529   }
 530   return best_line;
 531 }
 532 
 533 
 534 bool methodOopDesc::is_klass_loaded_by_klass_index(int klass_index) const {
 535   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 536     Thread *thread = Thread::current();
 537     Symbol* klass_name = constants()->klass_name_at(klass_index);
 538     Handle loader(thread, instanceKlass::cast(method_holder())->class_loader());
 539     Handle prot  (thread, Klass::cast(method_holder())->protection_domain());
 540     return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
 541   } else {
 542     return true;
 543   }
 544 }
 545 
 546 
 547 bool methodOopDesc::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 548   int klass_index = constants()->klass_ref_index_at(refinfo_index);
 549   if (must_be_resolved) {
 550     // Make sure klass is resolved in constantpool.
 551     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 552   }
 553   return is_klass_loaded_by_klass_index(klass_index);
 554 }
 555 
 556 
 557 void methodOopDesc::set_native_function(address function, bool post_event_flag) {
 558   assert(function != NULL, "use clear_native_function to unregister natives");
 559   assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
 560   address* native_function = native_function_addr();
 561 
 562   // We can see racers trying to place the same native function into place. Once
 563   // is plenty.
 564   address current = *native_function;
 565   if (current == function) return;
 566   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 567       function != NULL) {
 568     // native_method_throw_unsatisfied_link_error_entry() should only
 569     // be passed when post_event_flag is false.
 570     assert(function !=
 571       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 572       "post_event_flag mis-match");
 573 
 574     // post the bind event, and possible change the bind function
 575     JvmtiExport::post_native_method_bind(this, &function);
 576   }
 577   *native_function = function;
 578   // This function can be called more than once. We must make sure that we always
 579   // use the latest registered method -> check if a stub already has been generated.
 580   // If so, we have to make it not_entrant.
 581   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 582   if (nm != NULL) {
 583     nm->make_not_entrant();
 584   }
 585 }
 586 
 587 
 588 bool methodOopDesc::has_native_function() const {
 589   if (is_method_handle_intrinsic())
 590     return false;  // special-cased in SharedRuntime::generate_native_wrapper
 591   address func = native_function();
 592   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 593 }
 594 
 595 
 596 void methodOopDesc::clear_native_function() {
 597   // Note: is_method_handle_intrinsic() is allowed here.
 598   set_native_function(
 599     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 600     !native_bind_event_is_interesting);
 601   clear_code();
 602 }
 603 
 604 address methodOopDesc::critical_native_function() {
 605   methodHandle mh(this);
 606   return NativeLookup::lookup_critical_entry(mh);
 607 }
 608 
 609 
 610 void methodOopDesc::set_signature_handler(address handler) {
 611   address* signature_handler =  signature_handler_addr();
 612   *signature_handler = handler;
 613 }
 614 
 615 
 616 void methodOopDesc::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
 617   if (PrintCompilation && report) {
 618     ttyLocker ttyl;
 619     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
 620     if (comp_level == CompLevel_all) {
 621       tty->print("all levels ");
 622     } else {
 623       tty->print("levels ");
 624       for (int i = (int)CompLevel_none; i <= comp_level; i++) {
 625         tty->print("%d ", i);
 626       }
 627     }
 628     this->print_short_name(tty);
 629     int size = this->code_size();
 630     if (size > 0) {
 631       tty->print(" (%d bytes)", size);
 632     }
 633     if (reason != NULL) {
 634       tty->print("   %s", reason);
 635     }
 636     tty->cr();
 637   }
 638   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
 639     ttyLocker ttyl;
 640     xtty->begin_elem("make_not_%scompilable thread='" UINTX_FORMAT "'",
 641                      is_osr ? "osr_" : "", os::current_thread_id());
 642     if (reason != NULL) {
 643       xtty->print(" reason=\'%s\'", reason);
 644     }
 645     xtty->method(methodOop(this));
 646     xtty->stamp();
 647     xtty->end_elem();
 648   }
 649 }
 650 
 651 bool methodOopDesc::is_not_compilable(int comp_level) const {
 652   if (number_of_breakpoints() > 0)
 653     return true;
 654   if (is_method_handle_intrinsic())
 655     return !is_synthetic();  // the generated adapters must be compiled
 656   if (comp_level == CompLevel_any)
 657     return is_not_c1_compilable() || is_not_c2_compilable();
 658   if (is_c1_compile(comp_level))
 659     return is_not_c1_compilable();
 660   if (is_c2_compile(comp_level))
 661     return is_not_c2_compilable();
 662   return false;
 663 }
 664 
 665 // call this when compiler finds that this method is not compilable
 666 void methodOopDesc::set_not_compilable(int comp_level, bool report, const char* reason) {
 667   print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
 668   if (comp_level == CompLevel_all) {
 669     set_not_c1_compilable();
 670     set_not_c2_compilable();
 671   } else {
 672     if (is_c1_compile(comp_level))
 673       set_not_c1_compilable();
 674     if (is_c2_compile(comp_level))
 675       set_not_c2_compilable();
 676   }
 677   CompilationPolicy::policy()->disable_compilation(this);
 678 }
 679 
 680 bool methodOopDesc::is_not_osr_compilable(int comp_level) const {
 681   if (is_not_compilable(comp_level))
 682     return true;
 683   if (comp_level == CompLevel_any)
 684     return is_not_c1_osr_compilable() || is_not_c2_osr_compilable();
 685   if (is_c1_compile(comp_level))
 686     return is_not_c1_osr_compilable();
 687   if (is_c2_compile(comp_level))
 688     return is_not_c2_osr_compilable();
 689   return false;
 690 }
 691 
 692 void methodOopDesc::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
 693   print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
 694   if (comp_level == CompLevel_all) {
 695     set_not_c1_osr_compilable();
 696     set_not_c2_osr_compilable();
 697   } else {
 698     if (is_c1_compile(comp_level))
 699       set_not_c1_osr_compilable();
 700     if (is_c2_compile(comp_level))
 701       set_not_c2_osr_compilable();
 702   }
 703   CompilationPolicy::policy()->disable_compilation(this);
 704 }
 705 
 706 // Revert to using the interpreter and clear out the nmethod
 707 void methodOopDesc::clear_code() {
 708 
 709   // this may be NULL if c2i adapters have not been made yet
 710   // Only should happen at allocate time.
 711   if (_adapter == NULL) {
 712     _from_compiled_entry    = NULL;
 713   } else {
 714     _from_compiled_entry    = _adapter->get_c2i_entry();
 715   }
 716   OrderAccess::storestore();
 717   _from_interpreted_entry = _i2i_entry;
 718   OrderAccess::storestore();
 719   _code = NULL;
 720 }
 721 
 722 // Called by class data sharing to remove any entry points (which are not shared)
 723 void methodOopDesc::unlink_method() {
 724   _code = NULL;
 725   _i2i_entry = NULL;
 726   _from_interpreted_entry = NULL;
 727   if (is_native()) {
 728     *native_function_addr() = NULL;
 729     set_signature_handler(NULL);
 730   }
 731   NOT_PRODUCT(set_compiled_invocation_count(0);)
 732   invocation_counter()->reset();
 733   backedge_counter()->reset();
 734   _adapter = NULL;
 735   _from_compiled_entry = NULL;
 736   assert(_method_data == NULL, "unexpected method data?");
 737   set_method_data(NULL);
 738   set_interpreter_throwout_count(0);
 739   set_interpreter_invocation_count(0);
 740 }
 741 
 742 // Called when the method_holder is getting linked. Setup entrypoints so the method
 743 // is ready to be called from interpreter, compiler, and vtables.
 744 void methodOopDesc::link_method(methodHandle h_method, TRAPS) {
 745   // If the code cache is full, we may reenter this function for the
 746   // leftover methods that weren't linked.
 747   if (_i2i_entry != NULL) return;
 748 
 749   assert(_adapter == NULL, "init'd to NULL" );
 750   assert( _code == NULL, "nothing compiled yet" );
 751 
 752   // Setup interpreter entrypoint
 753   assert(this == h_method(), "wrong h_method()" );
 754   address entry = Interpreter::entry_for_method(h_method);
 755   assert(entry != NULL, "interpreter entry must be non-null");
 756   // Sets both _i2i_entry and _from_interpreted_entry
 757   set_interpreter_entry(entry);
 758 
 759   // Don't overwrite already registered native entries.
 760   if (is_native() && !has_native_function()) {
 761     set_native_function(
 762       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 763       !native_bind_event_is_interesting);
 764   }
 765 
 766   // Setup compiler entrypoint.  This is made eagerly, so we do not need
 767   // special handling of vtables.  An alternative is to make adapters more
 768   // lazily by calling make_adapter() from from_compiled_entry() for the
 769   // normal calls.  For vtable calls life gets more complicated.  When a
 770   // call-site goes mega-morphic we need adapters in all methods which can be
 771   // called from the vtable.  We need adapters on such methods that get loaded
 772   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
 773   // problem we'll make these lazily later.
 774   (void) make_adapters(h_method, CHECK);
 775 
 776   // ONLY USE the h_method now as make_adapter may have blocked
 777 
 778 }
 779 
 780 address methodOopDesc::make_adapters(methodHandle mh, TRAPS) {
 781   // Adapters for compiled code are made eagerly here.  They are fairly
 782   // small (generally < 100 bytes) and quick to make (and cached and shared)
 783   // so making them eagerly shouldn't be too expensive.
 784   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
 785   if (adapter == NULL ) {
 786     THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
 787   }
 788 
 789   mh->set_adapter_entry(adapter);
 790   mh->_from_compiled_entry = adapter->get_c2i_entry();
 791   return adapter->get_c2i_entry();
 792 }
 793 
 794 // The verified_code_entry() must be called when a invoke is resolved
 795 // on this method.
 796 
 797 // It returns the compiled code entry point, after asserting not null.
 798 // This function is called after potential safepoints so that nmethod
 799 // or adapter that it points to is still live and valid.
 800 // This function must not hit a safepoint!
 801 address methodOopDesc::verified_code_entry() {
 802   debug_only(No_Safepoint_Verifier nsv;)
 803   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 804   if (code == NULL && UseCodeCacheFlushing) {
 805     nmethod *saved_code = CodeCache::find_and_remove_saved_code(this);
 806     if (saved_code != NULL) {
 807       methodHandle method(this);
 808       assert( ! saved_code->is_osr_method(), "should not get here for osr" );
 809       set_code( method, saved_code );
 810     }
 811   }
 812 
 813   assert(_from_compiled_entry != NULL, "must be set");
 814   return _from_compiled_entry;
 815 }
 816 
 817 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
 818 // (could be racing a deopt).
 819 // Not inline to avoid circular ref.
 820 bool methodOopDesc::check_code() const {
 821   // cached in a register or local.  There's a race on the value of the field.
 822   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 823   return code == NULL || (code->method() == NULL) || (code->method() == (methodOop)this && !code->is_osr_method());
 824 }
 825 
 826 // Install compiled code.  Instantly it can execute.
 827 void methodOopDesc::set_code(methodHandle mh, nmethod *code) {
 828   assert( code, "use clear_code to remove code" );
 829   assert( mh->check_code(), "" );
 830 
 831   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
 832 
 833   // These writes must happen in this order, because the interpreter will
 834   // directly jump to from_interpreted_entry which jumps to an i2c adapter
 835   // which jumps to _from_compiled_entry.
 836   mh->_code = code;             // Assign before allowing compiled code to exec
 837 
 838   int comp_level = code->comp_level();
 839   // In theory there could be a race here. In practice it is unlikely
 840   // and not worth worrying about.
 841   if (comp_level > mh->highest_comp_level()) {
 842     mh->set_highest_comp_level(comp_level);
 843   }
 844 
 845   OrderAccess::storestore();
 846 #ifdef SHARK
 847   mh->_from_interpreted_entry = code->insts_begin();
 848 #else //!SHARK
 849   mh->_from_compiled_entry = code->verified_entry_point();
 850   OrderAccess::storestore();
 851   // Instantly compiled code can execute.
 852   if (!mh->is_method_handle_intrinsic())
 853     mh->_from_interpreted_entry = mh->get_i2c_entry();
 854 #endif //!SHARK
 855 }
 856 
 857 
 858 bool methodOopDesc::is_overridden_in(klassOop k) const {
 859   instanceKlass* ik = instanceKlass::cast(k);
 860 
 861   if (ik->is_interface()) return false;
 862 
 863   // If method is an interface, we skip it - except if it
 864   // is a miranda method
 865   if (instanceKlass::cast(method_holder())->is_interface()) {
 866     // Check that method is not a miranda method
 867     if (ik->lookup_method(name(), signature()) == NULL) {
 868       // No implementation exist - so miranda method
 869       return false;
 870     }
 871     return true;
 872   }
 873 
 874   assert(ik->is_subclass_of(method_holder()), "should be subklass");
 875   assert(ik->vtable() != NULL, "vtable should exist");
 876   if (vtable_index() == nonvirtual_vtable_index) {
 877     return false;
 878   } else {
 879     methodOop vt_m = ik->method_at_vtable(vtable_index());
 880     return vt_m != methodOop(this);
 881   }
 882 }
 883 
 884 
 885 // give advice about whether this methodOop should be cached or not
 886 bool methodOopDesc::should_not_be_cached() const {
 887   if (is_old()) {
 888     // This method has been redefined. It is either EMCP or obsolete
 889     // and we don't want to cache it because that would pin the method
 890     // down and prevent it from being collectible if and when it
 891     // finishes executing.
 892     return true;
 893   }
 894 
 895   if (mark()->should_not_be_cached()) {
 896     // It is either not safe or not a good idea to cache this
 897     // method at this time because of the state of the embedded
 898     // markOop. See markOop.cpp for the gory details.
 899     return true;
 900   }
 901 
 902   // caching this method should be just fine
 903   return false;
 904 }
 905 
 906 // Constant pool structure for invoke methods:
 907 enum {
 908   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
 909   _imcp_invoke_signature,       // utf8: (variable Symbol*)
 910   _imcp_limit
 911 };
 912 
 913 // Test if this method is an MH adapter frame generated by Java code.
 914 // Cf. java/lang/invoke/InvokerBytecodeGenerator
 915 bool methodOopDesc::is_compiled_lambda_form() const {
 916   return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
 917 }
 918 
 919 // Test if this method is an internal MH primitive method.
 920 bool methodOopDesc::is_method_handle_intrinsic() const {
 921   vmIntrinsics::ID iid = intrinsic_id();
 922   return (MethodHandles::is_signature_polymorphic(iid) &&
 923           MethodHandles::is_signature_polymorphic_intrinsic(iid));
 924 }
 925 
 926 bool methodOopDesc::has_member_arg() const {
 927   vmIntrinsics::ID iid = intrinsic_id();
 928   return (MethodHandles::is_signature_polymorphic(iid) &&
 929           MethodHandles::has_member_arg(iid));
 930 }
 931 
 932 // Make an instance of a signature-polymorphic internal MH primitive.
 933 methodHandle methodOopDesc::make_method_handle_intrinsic(vmIntrinsics::ID iid,
 934                                                          Symbol* signature,
 935                                                          TRAPS) {
 936   ResourceMark rm;
 937   methodHandle empty;
 938 
 939   KlassHandle holder = SystemDictionary::MethodHandle_klass();
 940   Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
 941   assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
 942   if (TraceMethodHandles) {
 943     tty->print_cr("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
 944   }
 945 
 946   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
 947   name->increment_refcount();
 948   signature->increment_refcount();
 949 
 950   int cp_length = _imcp_limit;
 951   constantPoolHandle cp;
 952   {
 953     constantPoolOop cp_oop = oopFactory::new_constantPool(cp_length, IsSafeConc, CHECK_(empty));
 954     cp = constantPoolHandle(THREAD, cp_oop);
 955   }
 956   cp->symbol_at_put(_imcp_invoke_name,       name);
 957   cp->symbol_at_put(_imcp_invoke_signature,  signature);
 958   cp->set_preresolution();
 959   cp->set_pool_holder(holder());
 960 
 961   // decide on access bits:  public or not?
 962   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
 963   bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
 964   if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
 965   assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
 966 
 967   methodHandle m;
 968   {
 969     methodOop m_oop = oopFactory::new_method(0, accessFlags_from(flags_bits),
 970                                              0, 0, 0, 0, IsSafeConc, CHECK_(empty));
 971     m = methodHandle(THREAD, m_oop);
 972   }
 973   m->set_constants(cp());
 974   m->set_name_index(_imcp_invoke_name);
 975   m->set_signature_index(_imcp_invoke_signature);
 976   assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
 977   assert(m->signature() == signature, "");
 978 #ifdef CC_INTERP
 979   ResultTypeFinder rtf(signature);
 980   m->set_result_index(rtf.type());
 981 #endif
 982   m->compute_size_of_parameters(THREAD);
 983   m->init_intrinsic_id();
 984   assert(m->is_method_handle_intrinsic(), "");
 985 #ifdef ASSERT
 986   if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
 987   assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
 988   assert(m->intrinsic_id() == iid, "correctly predicted iid");
 989 #endif //ASSERT
 990 
 991   // Finally, set up its entry points.
 992   assert(m->can_be_statically_bound(), "");
 993   m->set_vtable_index(methodOopDesc::nonvirtual_vtable_index);
 994   m->link_method(m, CHECK_(empty));
 995 
 996   if (TraceMethodHandles && (Verbose || WizardMode))
 997     m->print_on(tty);
 998 
 999   return m;
1000 }
1001 
1002 klassOop methodOopDesc::check_non_bcp_klass(klassOop klass) {
1003   if (klass != NULL && Klass::cast(klass)->class_loader() != NULL) {
1004     if (Klass::cast(klass)->oop_is_objArray())
1005       klass = objArrayKlass::cast(klass)->bottom_klass();
1006     return klass;
1007   }
1008   return NULL;
1009 }
1010 
1011 
1012 methodHandle methodOopDesc::clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
1013                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1014   // Code below does not work for native methods - they should never get rewritten anyway
1015   assert(!m->is_native(), "cannot rewrite native methods");
1016   // Allocate new methodOop
1017   AccessFlags flags = m->access_flags();
1018   int checked_exceptions_len = m->checked_exceptions_length();
1019   int localvariable_len = m->localvariable_table_length();
1020   int exception_table_len = m->exception_table_length();
1021   // Allocate newm_oop with the is_conc_safe parameter set
1022   // to IsUnsafeConc to indicate that newm_oop is not yet
1023   // safe for concurrent processing by a GC.
1024   methodOop newm_oop = oopFactory::new_method(new_code_length,
1025                                               flags,
1026                                               new_compressed_linenumber_size,
1027                                               localvariable_len,
1028                                               exception_table_len,
1029                                               checked_exceptions_len,
1030                                               IsUnsafeConc,
1031                                               CHECK_(methodHandle()));
1032   methodHandle newm (THREAD, newm_oop);
1033   NOT_PRODUCT(int nmsz = newm->is_parsable() ? newm->size() : -1;)
1034   int new_method_size = newm->method_size();
1035   // Create a shallow copy of methodOopDesc part, but be careful to preserve the new constMethodOop
1036   constMethodOop newcm = newm->constMethod();
1037   NOT_PRODUCT(int ncmsz = newcm->is_parsable() ? newcm->size() : -1;)
1038   int new_const_method_size = newm->constMethod()->object_size();
1039 
1040   memcpy(newm(), m(), sizeof(methodOopDesc));
1041   // Create shallow copy of constMethodOopDesc, but be careful to preserve the methodOop
1042   // is_conc_safe is set to false because that is the value of
1043   // is_conc_safe initialzied into newcm and the copy should
1044   // not overwrite that value.  During the window during which it is
1045   // tagged as unsafe, some extra work could be needed during precleaning
1046   // or concurrent marking but those phases will be correct.  Setting and
1047   // resetting is done in preference to a careful copying into newcm to
1048   // avoid having to know the precise layout of a constMethodOop.
1049   m->constMethod()->set_is_conc_safe(oopDesc::IsUnsafeConc);
1050   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1051 
1052   // NOTE: this is a reachable object that transiently signals "conc_unsafe"
1053   // However, no allocations are done during this window
1054   // during which it is tagged conc_unsafe, so we are assured that any concurrent
1055   // thread will not wait forever for the object to revert to "conc_safe".
1056   // Further, any such conc_unsafe object will indicate a stable size
1057   // through the transition.
1058   memcpy(newcm, m->constMethod(), sizeof(constMethodOopDesc));
1059   m->constMethod()->set_is_conc_safe(oopDesc::IsSafeConc);
1060   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1061 
1062   // Reset correct method/const method, method size, and parameter info
1063   newm->set_constMethod(newcm);
1064   newm->constMethod()->set_code_size(new_code_length);
1065   newm->constMethod()->set_constMethod_size(new_const_method_size);
1066   newm->set_method_size(new_method_size);
1067   assert(newm->code_size() == new_code_length, "check");
1068   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1069   assert(newm->exception_table_length() == exception_table_len, "check");
1070   assert(newm->localvariable_table_length() == localvariable_len, "check");
1071   // Copy new byte codes
1072   memcpy(newm->code_base(), new_code, new_code_length);
1073   // Copy line number table
1074   if (new_compressed_linenumber_size > 0) {
1075     memcpy(newm->compressed_linenumber_table(),
1076            new_compressed_linenumber_table,
1077            new_compressed_linenumber_size);
1078   }
1079   // Copy checked_exceptions
1080   if (checked_exceptions_len > 0) {
1081     memcpy(newm->checked_exceptions_start(),
1082            m->checked_exceptions_start(),
1083            checked_exceptions_len * sizeof(CheckedExceptionElement));
1084   }
1085   // Copy exception table
1086   if (exception_table_len > 0) {
1087     memcpy(newm->exception_table_start(),
1088            m->exception_table_start(),
1089            exception_table_len * sizeof(ExceptionTableElement));
1090   }
1091   // Copy local variable number table
1092   if (localvariable_len > 0) {
1093     memcpy(newm->localvariable_table_start(),
1094            m->localvariable_table_start(),
1095            localvariable_len * sizeof(LocalVariableTableElement));
1096   }
1097 
1098   // Only set is_conc_safe to true when changes to newcm are
1099   // complete.
1100   assert(!newm->is_parsable()  || nmsz  < 0 || newm->size()  == nmsz,  "newm->size()  inconsistency");
1101   assert(!newcm->is_parsable() || ncmsz < 0 || newcm->size() == ncmsz, "newcm->size() inconsistency");
1102   newcm->set_is_conc_safe(true);
1103   return newm;
1104 }
1105 
1106 vmSymbols::SID methodOopDesc::klass_id_for_intrinsics(klassOop holder) {
1107   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1108   // because we are not loading from core libraries
1109   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1110   // which does not use the class default class loader so we check for its loader here
1111   if ((instanceKlass::cast(holder)->class_loader() != NULL) &&
1112        instanceKlass::cast(holder)->class_loader()->klass()->klass_part()->name() != vmSymbols::sun_misc_Launcher_ExtClassLoader()) {
1113     return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1114   }
1115 
1116   // see if the klass name is well-known:
1117   Symbol* klass_name = instanceKlass::cast(holder)->name();
1118   return vmSymbols::find_sid(klass_name);
1119 }
1120 
1121 void methodOopDesc::init_intrinsic_id() {
1122   assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
1123   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1124   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1125   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1126 
1127   // the klass name is well-known:
1128   vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
1129   assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
1130 
1131   // ditto for method and signature:
1132   vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1133   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1134       && name_id == vmSymbols::NO_SID)
1135     return;
1136   vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1137   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1138       && sig_id == vmSymbols::NO_SID)  return;
1139   jshort flags = access_flags().as_short();
1140 
1141   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1142   if (id != vmIntrinsics::_none) {
1143     set_intrinsic_id(id);
1144     return;
1145   }
1146 
1147   // A few slightly irregular cases:
1148   switch (klass_id) {
1149   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
1150     // Second chance: check in regular Math.
1151     switch (name_id) {
1152     case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
1153     case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
1154     case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
1155       // pretend it is the corresponding method in the non-strict class:
1156       klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1157       id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1158       break;
1159     }
1160     break;
1161 
1162   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1163   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1164     if (!is_native())  break;
1165     id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1166     if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1167       id = vmIntrinsics::_none;
1168     break;
1169   }
1170 
1171   if (id != vmIntrinsics::_none) {
1172     // Set up its iid.  It is an alias method.
1173     set_intrinsic_id(id);
1174     return;
1175   }
1176 }
1177 
1178 // These two methods are static since a GC may move the methodOopDesc
1179 bool methodOopDesc::load_signature_classes(methodHandle m, TRAPS) {
1180   if (THREAD->is_Compiler_thread()) {
1181     // There is nothing useful this routine can do from within the Compile thread.
1182     // Hopefully, the signature contains only well-known classes.
1183     // We could scan for this and return true/false, but the caller won't care.
1184     return false;
1185   }
1186   bool sig_is_loaded = true;
1187   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1188   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1189   ResourceMark rm(THREAD);
1190   Symbol*  signature = m->signature();
1191   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1192     if (ss.is_object()) {
1193       Symbol* sym = ss.as_symbol(CHECK_(false));
1194       Symbol*  name  = sym;
1195       klassOop klass = SystemDictionary::resolve_or_null(name, class_loader,
1196                                              protection_domain, THREAD);
1197       // We are loading classes eagerly. If a ClassNotFoundException or
1198       // a LinkageError was generated, be sure to ignore it.
1199       if (HAS_PENDING_EXCEPTION) {
1200         if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
1201             PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
1202           CLEAR_PENDING_EXCEPTION;
1203         } else {
1204           return false;
1205         }
1206       }
1207       if( klass == NULL) { sig_is_loaded = false; }
1208     }
1209   }
1210   return sig_is_loaded;
1211 }
1212 
1213 bool methodOopDesc::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1214   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1215   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1216   ResourceMark rm(THREAD);
1217   Symbol*  signature = m->signature();
1218   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1219     if (ss.type() == T_OBJECT) {
1220       Symbol* name = ss.as_symbol_or_null();
1221       if (name == NULL) return true;
1222       klassOop klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1223       if (klass == NULL) return true;
1224     }
1225   }
1226   return false;
1227 }
1228 
1229 // Exposed so field engineers can debug VM
1230 void methodOopDesc::print_short_name(outputStream* st) {
1231   ResourceMark rm;
1232 #ifdef PRODUCT
1233   st->print(" %s::", method_holder()->klass_part()->external_name());
1234 #else
1235   st->print(" %s::", method_holder()->klass_part()->internal_name());
1236 #endif
1237   name()->print_symbol_on(st);
1238   if (WizardMode) signature()->print_symbol_on(st);
1239   else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1240     MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
1241 }
1242 
1243 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1244 static void reorder_based_on_method_index(objArrayOop methods,
1245                                           objArrayOop annotations,
1246                                           GrowableArray<oop>* temp_array) {
1247   if (annotations == NULL) {
1248     return;
1249   }
1250 
1251   int length = methods->length();
1252   int i;
1253   // Copy to temp array
1254   temp_array->clear();
1255   for (i = 0; i < length; i++) {
1256     temp_array->append(annotations->obj_at(i));
1257   }
1258 
1259   // Copy back using old method indices
1260   for (i = 0; i < length; i++) {
1261     methodOop m = (methodOop) methods->obj_at(i);
1262     annotations->obj_at_put(i, temp_array->at(m->method_idnum()));
1263   }
1264 }
1265 
1266 // Comparer for sorting an object array containing
1267 // methodOops.
1268 // Used non-template method_comparator methods since
1269 // Visual Studio 2003 compiler generates incorrect
1270 // optimized code for it.
1271 static int method_comparator_narrowOop(narrowOop a, narrowOop b) {
1272   methodOop m = (methodOop)oopDesc::decode_heap_oop_not_null(a);
1273   methodOop n = (methodOop)oopDesc::decode_heap_oop_not_null(b);
1274   return m->name()->fast_compare(n->name());
1275 }
1276 static int method_comparator_oop(oop a, oop b) {
1277   methodOop m = (methodOop)a;
1278   methodOop n = (methodOop)b;
1279   return m->name()->fast_compare(n->name());
1280 }
1281 
1282 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1283 void methodOopDesc::sort_methods(objArrayOop methods,
1284                                  objArrayOop methods_annotations,
1285                                  objArrayOop methods_parameter_annotations,
1286                                  objArrayOop methods_default_annotations,
1287                                  bool idempotent) {
1288   int length = methods->length();
1289   if (length > 1) {
1290     bool do_annotations = false;
1291     if (methods_annotations != NULL ||
1292         methods_parameter_annotations != NULL ||
1293         methods_default_annotations != NULL) {
1294       do_annotations = true;
1295     }
1296     if (do_annotations) {
1297       // Remember current method ordering so we can reorder annotations
1298       for (int i = 0; i < length; i++) {
1299         methodOop m = (methodOop) methods->obj_at(i);
1300         m->set_method_idnum(i);
1301       }
1302     }
1303     {
1304       No_Safepoint_Verifier nsv;
1305       if (UseCompressedOops) {
1306         QuickSort::sort<narrowOop>((narrowOop*)(methods->base()), length, method_comparator_narrowOop, idempotent);
1307       } else {
1308         QuickSort::sort<oop>((oop*)(methods->base()), length, method_comparator_oop, idempotent);
1309       }
1310       if (UseConcMarkSweepGC) {
1311         // For CMS we need to dirty the cards for the array
1312         BarrierSet* bs = Universe::heap()->barrier_set();
1313         assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1314         bs->write_ref_array(methods->base(), length);
1315       }
1316     }
1317 
1318     // Sort annotations if necessary
1319     assert(methods_annotations == NULL           || methods_annotations->length() == methods->length(), "");
1320     assert(methods_parameter_annotations == NULL || methods_parameter_annotations->length() == methods->length(), "");
1321     assert(methods_default_annotations == NULL   || methods_default_annotations->length() == methods->length(), "");
1322     if (do_annotations) {
1323       ResourceMark rm;
1324       // Allocate temporary storage
1325       GrowableArray<oop>* temp_array = new GrowableArray<oop>(length);
1326       reorder_based_on_method_index(methods, methods_annotations, temp_array);
1327       reorder_based_on_method_index(methods, methods_parameter_annotations, temp_array);
1328       reorder_based_on_method_index(methods, methods_default_annotations, temp_array);
1329     }
1330 
1331     // Reset method ordering
1332     for (int i = 0; i < length; i++) {
1333       methodOop m = (methodOop) methods->obj_at(i);
1334       m->set_method_idnum(i);
1335     }
1336   }
1337 }
1338 
1339 
1340 class SignatureTypePrinter : public SignatureTypeNames {
1341  private:
1342   outputStream* _st;
1343   bool _use_separator;
1344 
1345   void type_name(const char* name) {
1346     if (_use_separator) _st->print(", ");
1347     _st->print(name);
1348     _use_separator = true;
1349   }
1350 
1351  public:
1352   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1353     _st = st;
1354     _use_separator = false;
1355   }
1356 
1357   void print_parameters()              { _use_separator = false; iterate_parameters(); }
1358   void print_returntype()              { _use_separator = false; iterate_returntype(); }
1359 };
1360 
1361 
1362 void methodOopDesc::print_name(outputStream* st) {
1363   Thread *thread = Thread::current();
1364   ResourceMark rm(thread);
1365   SignatureTypePrinter sig(signature(), st);
1366   st->print("%s ", is_static() ? "static" : "virtual");
1367   sig.print_returntype();
1368   st->print(" %s.", method_holder()->klass_part()->internal_name());
1369   name()->print_symbol_on(st);
1370   st->print("(");
1371   sig.print_parameters();
1372   st->print(")");
1373 }
1374 
1375 
1376 //-----------------------------------------------------------------------------------
1377 // Non-product code
1378 
1379 #ifndef PRODUCT
1380 void methodOopDesc::print_codes_on(outputStream* st) const {
1381   print_codes_on(0, code_size(), st);
1382 }
1383 
1384 void methodOopDesc::print_codes_on(int from, int to, outputStream* st) const {
1385   Thread *thread = Thread::current();
1386   ResourceMark rm(thread);
1387   methodHandle mh (thread, (methodOop)this);
1388   BytecodeStream s(mh);
1389   s.set_interval(from, to);
1390   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1391   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1392 }
1393 #endif // not PRODUCT
1394 
1395 
1396 // Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1397 // between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1398 // we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1399 // as end-of-stream terminator.
1400 
1401 void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1402   // bci and line number does not compress into single byte.
1403   // Write out escape character and use regular compression for bci and line number.
1404   write_byte((jubyte)0xFF);
1405   write_signed_int(bci_delta);
1406   write_signed_int(line_delta);
1407 }
1408 
1409 // See comment in methodOop.hpp which explains why this exists.
1410 #if defined(_M_AMD64) && _MSC_VER >= 1400
1411 #pragma optimize("", off)
1412 void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1413   write_pair_inline(bci, line);
1414 }
1415 #pragma optimize("", on)
1416 #endif
1417 
1418 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1419   _bci = 0;
1420   _line = 0;
1421 };
1422 
1423 
1424 bool CompressedLineNumberReadStream::read_pair() {
1425   jubyte next = read_byte();
1426   // Check for terminator
1427   if (next == 0) return false;
1428   if (next == 0xFF) {
1429     // Escape character, regular compression used
1430     _bci  += read_signed_int();
1431     _line += read_signed_int();
1432   } else {
1433     // Single byte compression used
1434     _bci  += next >> 3;
1435     _line += next & 0x7;
1436   }
1437   return true;
1438 }
1439 
1440 
1441 Bytecodes::Code methodOopDesc::orig_bytecode_at(int bci) const {
1442   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1443   for (; bp != NULL; bp = bp->next()) {
1444     if (bp->match(this, bci)) {
1445       return bp->orig_bytecode();
1446     }
1447   }
1448   ShouldNotReachHere();
1449   return Bytecodes::_shouldnotreachhere;
1450 }
1451 
1452 void methodOopDesc::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1453   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1454   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1455   for (; bp != NULL; bp = bp->next()) {
1456     if (bp->match(this, bci)) {
1457       bp->set_orig_bytecode(code);
1458       // and continue, in case there is more than one
1459     }
1460   }
1461 }
1462 
1463 void methodOopDesc::set_breakpoint(int bci) {
1464   instanceKlass* ik = instanceKlass::cast(method_holder());
1465   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1466   bp->set_next(ik->breakpoints());
1467   ik->set_breakpoints(bp);
1468   // do this last:
1469   bp->set(this);
1470 }
1471 
1472 static void clear_matches(methodOop m, int bci) {
1473   instanceKlass* ik = instanceKlass::cast(m->method_holder());
1474   BreakpointInfo* prev_bp = NULL;
1475   BreakpointInfo* next_bp;
1476   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1477     next_bp = bp->next();
1478     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1479     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1480       // do this first:
1481       bp->clear(m);
1482       // unhook it
1483       if (prev_bp != NULL)
1484         prev_bp->set_next(next_bp);
1485       else
1486         ik->set_breakpoints(next_bp);
1487       delete bp;
1488       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1489       // at same location. So we have multiple matching (method_index and bci)
1490       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1491       // breakpoint for clear_breakpoint request and keep all other method versions
1492       // BreakpointInfo for future clear_breakpoint request.
1493       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1494       // which is being called when class is unloaded. We delete all the Breakpoint
1495       // information for all versions of method. We may not correctly restore the original
1496       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1497       // so these methods won't be used anymore.
1498       if (bci >= 0) {
1499         break;
1500       }
1501     } else {
1502       // This one is a keeper.
1503       prev_bp = bp;
1504     }
1505   }
1506 }
1507 
1508 void methodOopDesc::clear_breakpoint(int bci) {
1509   assert(bci >= 0, "");
1510   clear_matches(this, bci);
1511 }
1512 
1513 void methodOopDesc::clear_all_breakpoints() {
1514   clear_matches(this, -1);
1515 }
1516 
1517 
1518 int methodOopDesc::invocation_count() {
1519   if (TieredCompilation) {
1520     const methodDataOop mdo = method_data();
1521     if (invocation_counter()->carry() || ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1522       return InvocationCounter::count_limit;
1523     } else {
1524       return invocation_counter()->count() + ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1525     }
1526   } else {
1527     return invocation_counter()->count();
1528   }
1529 }
1530 
1531 int methodOopDesc::backedge_count() {
1532   if (TieredCompilation) {
1533     const methodDataOop mdo = method_data();
1534     if (backedge_counter()->carry() || ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1535       return InvocationCounter::count_limit;
1536     } else {
1537       return backedge_counter()->count() + ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1538     }
1539   } else {
1540     return backedge_counter()->count();
1541   }
1542 }
1543 
1544 int methodOopDesc::highest_comp_level() const {
1545   methodDataOop mdo = method_data();
1546   if (mdo != NULL) {
1547     return mdo->highest_comp_level();
1548   } else {
1549     return CompLevel_none;
1550   }
1551 }
1552 
1553 int methodOopDesc::highest_osr_comp_level() const {
1554   methodDataOop mdo = method_data();
1555   if (mdo != NULL) {
1556     return mdo->highest_osr_comp_level();
1557   } else {
1558     return CompLevel_none;
1559   }
1560 }
1561 
1562 void methodOopDesc::set_highest_comp_level(int level) {
1563   methodDataOop mdo = method_data();
1564   if (mdo != NULL) {
1565     mdo->set_highest_comp_level(level);
1566   }
1567 }
1568 
1569 void methodOopDesc::set_highest_osr_comp_level(int level) {
1570   methodDataOop mdo = method_data();
1571   if (mdo != NULL) {
1572     mdo->set_highest_osr_comp_level(level);
1573   }
1574 }
1575 
1576 BreakpointInfo::BreakpointInfo(methodOop m, int bci) {
1577   _bci = bci;
1578   _name_index = m->name_index();
1579   _signature_index = m->signature_index();
1580   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1581   if (_orig_bytecode == Bytecodes::_breakpoint)
1582     _orig_bytecode = m->orig_bytecode_at(_bci);
1583   _next = NULL;
1584 }
1585 
1586 void BreakpointInfo::set(methodOop method) {
1587 #ifdef ASSERT
1588   {
1589     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1590     if (code == Bytecodes::_breakpoint)
1591       code = method->orig_bytecode_at(_bci);
1592     assert(orig_bytecode() == code, "original bytecode must be the same");
1593   }
1594 #endif
1595   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1596   method->incr_number_of_breakpoints();
1597   SystemDictionary::notice_modification();
1598   {
1599     // Deoptimize all dependents on this method
1600     Thread *thread = Thread::current();
1601     HandleMark hm(thread);
1602     methodHandle mh(thread, method);
1603     Universe::flush_dependents_on_method(mh);
1604   }
1605 }
1606 
1607 void BreakpointInfo::clear(methodOop method) {
1608   *method->bcp_from(_bci) = orig_bytecode();
1609   assert(method->number_of_breakpoints() > 0, "must not go negative");
1610   method->decr_number_of_breakpoints();
1611 }