1 /*
   2  * Copyright (c) 1997, 2012, 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/methodHandleWalk.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(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   const int beg_bci_offset     = 0;
 115   const int end_bci_offset     = 1;
 116   const int handler_bci_offset = 2;
 117   const int klass_index_offset = 3;
 118   const int entry_size         = 4;
 119   // access exception table
 120   typeArrayHandle table (THREAD, constMethod()->exception_table());
 121   int length = table->length();
 122   assert(length % entry_size == 0, "exception table format has changed");
 123   // iterate through all entries sequentially
 124   constantPoolHandle pool(THREAD, constants());
 125   for (int i = 0; i < length; i += entry_size) {
 126     int beg_bci = table->int_at(i + beg_bci_offset);
 127     int end_bci = table->int_at(i + end_bci_offset);
 128     assert(beg_bci <= end_bci, "inconsistent exception table");
 129     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 130       // exception handler bci range covers throw_bci => investigate further
 131       int handler_bci = table->int_at(i + handler_bci_offset);
 132       int klass_index = table->int_at(i + klass_index_offset);
 133       if (klass_index == 0) {
 134         return handler_bci;
 135       } else if (ex_klass.is_null()) {
 136         return handler_bci;
 137       } else {
 138         // we know the exception class => get the constraint class
 139         // this may require loading of the constraint class; if verification
 140         // fails or some other exception occurs, return handler_bci
 141         klassOop k = pool->klass_at(klass_index, CHECK_(handler_bci));
 142         KlassHandle klass = KlassHandle(THREAD, k);
 143         assert(klass.not_null(), "klass not loaded");
 144         if (ex_klass->is_subtype_of(klass())) {
 145           return handler_bci;
 146         }
 147       }
 148     }
 149   }
 150 
 151   return -1;
 152 }
 153 
 154 void methodOopDesc::mask_for(int bci, InterpreterOopMap* mask) {
 155 
 156   Thread* myThread    = Thread::current();
 157   methodHandle h_this(myThread, this);
 158 #ifdef ASSERT
 159   bool has_capability = myThread->is_VM_thread() ||
 160                         myThread->is_ConcurrentGC_thread() ||
 161                         myThread->is_GC_task_thread();
 162 
 163   if (!has_capability) {
 164     if (!VerifyStack && !VerifyLastFrame) {
 165       // verify stack calls this outside VM thread
 166       warning("oopmap should only be accessed by the "
 167               "VM, GC task or CMS threads (or during debugging)");
 168       InterpreterOopMap local_mask;
 169       instanceKlass::cast(method_holder())->mask_for(h_this, bci, &local_mask);
 170       local_mask.print();
 171     }
 172   }
 173 #endif
 174   instanceKlass::cast(method_holder())->mask_for(h_this, bci, mask);
 175   return;
 176 }
 177 
 178 
 179 int methodOopDesc::bci_from(address bcp) const {
 180   assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
 181          err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
 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   address* native_function = native_function_addr();
 560 
 561   // We can see racers trying to place the same native function into place. Once
 562   // is plenty.
 563   address current = *native_function;
 564   if (current == function) return;
 565   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 566       function != NULL) {
 567     // native_method_throw_unsatisfied_link_error_entry() should only
 568     // be passed when post_event_flag is false.
 569     assert(function !=
 570       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 571       "post_event_flag mis-match");
 572 
 573     // post the bind event, and possible change the bind function
 574     JvmtiExport::post_native_method_bind(this, &function);
 575   }
 576   *native_function = function;
 577   // This function can be called more than once. We must make sure that we always
 578   // use the latest registered method -> check if a stub already has been generated.
 579   // If so, we have to make it not_entrant.
 580   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 581   if (nm != NULL) {
 582     nm->make_not_entrant();
 583   }
 584 }
 585 
 586 
 587 bool methodOopDesc::has_native_function() const {
 588   address func = native_function();
 589   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 590 }
 591 
 592 
 593 void methodOopDesc::clear_native_function() {
 594   set_native_function(
 595     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 596     !native_bind_event_is_interesting);
 597   clear_code();
 598 }
 599 
 600 address methodOopDesc::critical_native_function() {
 601   methodHandle mh(this);
 602   return NativeLookup::lookup_critical_entry(mh);
 603 }
 604 
 605 
 606 void methodOopDesc::set_signature_handler(address handler) {
 607   address* signature_handler =  signature_handler_addr();
 608   *signature_handler = handler;
 609 }
 610 
 611 
 612 bool methodOopDesc::is_not_compilable(int comp_level) const {
 613   if (is_method_handle_invoke()) {
 614     // compilers must recognize this method specially, or not at all
 615     return true;
 616   }
 617   if (number_of_breakpoints() > 0) {
 618     return true;
 619   }
 620   if (comp_level == CompLevel_any) {
 621     return is_not_c1_compilable() || is_not_c2_compilable();
 622   }
 623   if (is_c1_compile(comp_level)) {
 624     return is_not_c1_compilable();
 625   }
 626   if (is_c2_compile(comp_level)) {
 627     return is_not_c2_compilable();
 628   }
 629   return false;
 630 }
 631 
 632 // call this when compiler finds that this method is not compilable
 633 void methodOopDesc::set_not_compilable(int comp_level, bool report) {
 634   if (PrintCompilation && report) {
 635     ttyLocker ttyl;
 636     tty->print("made not compilable ");
 637     this->print_short_name(tty);
 638     int size = this->code_size();
 639     if (size > 0)
 640       tty->print(" (%d bytes)", size);
 641     tty->cr();
 642   }
 643   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
 644     ttyLocker ttyl;
 645     xtty->begin_elem("make_not_compilable thread='%d'", (int) os::current_thread_id());
 646     xtty->method(methodOop(this));
 647     xtty->stamp();
 648     xtty->end_elem();
 649   }
 650   if (comp_level == CompLevel_all) {
 651     set_not_c1_compilable();
 652     set_not_c2_compilable();
 653   } else {
 654     if (is_c1_compile(comp_level)) {
 655       set_not_c1_compilable();
 656     } else
 657       if (is_c2_compile(comp_level)) {
 658         set_not_c2_compilable();
 659       }
 660   }
 661   CompilationPolicy::policy()->disable_compilation(this);
 662 }
 663 
 664 // Revert to using the interpreter and clear out the nmethod
 665 void methodOopDesc::clear_code() {
 666 
 667   // this may be NULL if c2i adapters have not been made yet
 668   // Only should happen at allocate time.
 669   if (_adapter == NULL) {
 670     _from_compiled_entry    = NULL;
 671   } else {
 672     _from_compiled_entry    = _adapter->get_c2i_entry();
 673   }
 674   OrderAccess::storestore();
 675   _from_interpreted_entry = _i2i_entry;
 676   OrderAccess::storestore();
 677   _code = NULL;
 678 }
 679 
 680 // Called by class data sharing to remove any entry points (which are not shared)
 681 void methodOopDesc::unlink_method() {
 682   _code = NULL;
 683   _i2i_entry = NULL;
 684   _from_interpreted_entry = NULL;
 685   if (is_native()) {
 686     *native_function_addr() = NULL;
 687     set_signature_handler(NULL);
 688   }
 689   NOT_PRODUCT(set_compiled_invocation_count(0);)
 690   invocation_counter()->reset();
 691   backedge_counter()->reset();
 692   _adapter = NULL;
 693   _from_compiled_entry = NULL;
 694   assert(_method_data == NULL, "unexpected method data?");
 695   set_method_data(NULL);
 696   set_interpreter_throwout_count(0);
 697   set_interpreter_invocation_count(0);
 698 }
 699 
 700 // Called when the method_holder is getting linked. Setup entrypoints so the method
 701 // is ready to be called from interpreter, compiler, and vtables.
 702 void methodOopDesc::link_method(methodHandle h_method, TRAPS) {
 703   // If the code cache is full, we may reenter this function for the
 704   // leftover methods that weren't linked.
 705   if (_i2i_entry != NULL) return;
 706 
 707   assert(_adapter == NULL, "init'd to NULL" );
 708   assert( _code == NULL, "nothing compiled yet" );
 709 
 710   // Setup interpreter entrypoint
 711   assert(this == h_method(), "wrong h_method()" );
 712   address entry = Interpreter::entry_for_method(h_method);
 713   assert(entry != NULL, "interpreter entry must be non-null");
 714   // Sets both _i2i_entry and _from_interpreted_entry
 715   set_interpreter_entry(entry);
 716   if (is_native() && !is_method_handle_invoke()) {
 717     set_native_function(
 718       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 719       !native_bind_event_is_interesting);
 720   }
 721 
 722   // Setup compiler entrypoint.  This is made eagerly, so we do not need
 723   // special handling of vtables.  An alternative is to make adapters more
 724   // lazily by calling make_adapter() from from_compiled_entry() for the
 725   // normal calls.  For vtable calls life gets more complicated.  When a
 726   // call-site goes mega-morphic we need adapters in all methods which can be
 727   // called from the vtable.  We need adapters on such methods that get loaded
 728   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
 729   // problem we'll make these lazily later.
 730   (void) make_adapters(h_method, CHECK);
 731 
 732   // ONLY USE the h_method now as make_adapter may have blocked
 733 
 734 }
 735 
 736 address methodOopDesc::make_adapters(methodHandle mh, TRAPS) {
 737   // Adapters for compiled code are made eagerly here.  They are fairly
 738   // small (generally < 100 bytes) and quick to make (and cached and shared)
 739   // so making them eagerly shouldn't be too expensive.
 740   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
 741   if (adapter == NULL ) {
 742     THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
 743   }
 744 
 745   mh->set_adapter_entry(adapter);
 746   mh->_from_compiled_entry = adapter->get_c2i_entry();
 747   return adapter->get_c2i_entry();
 748 }
 749 
 750 // The verified_code_entry() must be called when a invoke is resolved
 751 // on this method.
 752 
 753 // It returns the compiled code entry point, after asserting not null.
 754 // This function is called after potential safepoints so that nmethod
 755 // or adapter that it points to is still live and valid.
 756 // This function must not hit a safepoint!
 757 address methodOopDesc::verified_code_entry() {
 758   debug_only(No_Safepoint_Verifier nsv;)
 759   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 760   if (code == NULL && UseCodeCacheFlushing) {
 761     nmethod *saved_code = CodeCache::find_and_remove_saved_code(this);
 762     if (saved_code != NULL) {
 763       methodHandle method(this);
 764       assert( ! saved_code->is_osr_method(), "should not get here for osr" );
 765       set_code( method, saved_code );
 766     }
 767   }
 768 
 769   assert(_from_compiled_entry != NULL, "must be set");
 770   return _from_compiled_entry;
 771 }
 772 
 773 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
 774 // (could be racing a deopt).
 775 // Not inline to avoid circular ref.
 776 bool methodOopDesc::check_code() const {
 777   // cached in a register or local.  There's a race on the value of the field.
 778   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 779   return code == NULL || (code->method() == NULL) || (code->method() == (methodOop)this && !code->is_osr_method());
 780 }
 781 
 782 // Install compiled code.  Instantly it can execute.
 783 void methodOopDesc::set_code(methodHandle mh, nmethod *code) {
 784   assert( code, "use clear_code to remove code" );
 785   assert( mh->check_code(), "" );
 786 
 787   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
 788 
 789   // These writes must happen in this order, because the interpreter will
 790   // directly jump to from_interpreted_entry which jumps to an i2c adapter
 791   // which jumps to _from_compiled_entry.
 792   mh->_code = code;             // Assign before allowing compiled code to exec
 793 
 794   int comp_level = code->comp_level();
 795   // In theory there could be a race here. In practice it is unlikely
 796   // and not worth worrying about.
 797   if (comp_level > mh->highest_comp_level()) {
 798     mh->set_highest_comp_level(comp_level);
 799   }
 800 
 801   OrderAccess::storestore();
 802 #ifdef SHARK
 803   mh->_from_interpreted_entry = code->insts_begin();
 804 #else
 805   mh->_from_compiled_entry = code->verified_entry_point();
 806   OrderAccess::storestore();
 807   // Instantly compiled code can execute.
 808   mh->_from_interpreted_entry = mh->get_i2c_entry();
 809 #endif // SHARK
 810 
 811 }
 812 
 813 
 814 bool methodOopDesc::is_overridden_in(klassOop k) const {
 815   instanceKlass* ik = instanceKlass::cast(k);
 816 
 817   if (ik->is_interface()) return false;
 818 
 819   // If method is an interface, we skip it - except if it
 820   // is a miranda method
 821   if (instanceKlass::cast(method_holder())->is_interface()) {
 822     // Check that method is not a miranda method
 823     if (ik->lookup_method(name(), signature()) == NULL) {
 824       // No implementation exist - so miranda method
 825       return false;
 826     }
 827     return true;
 828   }
 829 
 830   assert(ik->is_subclass_of(method_holder()), "should be subklass");
 831   assert(ik->vtable() != NULL, "vtable should exist");
 832   if (vtable_index() == nonvirtual_vtable_index) {
 833     return false;
 834   } else {
 835     methodOop vt_m = ik->method_at_vtable(vtable_index());
 836     return vt_m != methodOop(this);
 837   }
 838 }
 839 
 840 
 841 // give advice about whether this methodOop should be cached or not
 842 bool methodOopDesc::should_not_be_cached() const {
 843   if (is_old()) {
 844     // This method has been redefined. It is either EMCP or obsolete
 845     // and we don't want to cache it because that would pin the method
 846     // down and prevent it from being collectible if and when it
 847     // finishes executing.
 848     return true;
 849   }
 850 
 851   if (mark()->should_not_be_cached()) {
 852     // It is either not safe or not a good idea to cache this
 853     // method at this time because of the state of the embedded
 854     // markOop. See markOop.cpp for the gory details.
 855     return true;
 856   }
 857 
 858   // caching this method should be just fine
 859   return false;
 860 }
 861 
 862 bool methodOopDesc::is_method_handle_invoke_name(vmSymbols::SID name_sid) {
 863   switch (name_sid) {
 864   case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeExact_name):
 865   case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):
 866     return true;
 867   }
 868   if (AllowInvokeGeneric
 869       && name_sid == vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name))
 870     return true;
 871   return false;
 872 }
 873 
 874 // Constant pool structure for invoke methods:
 875 enum {
 876   _imcp_invoke_name = 1,        // utf8: 'invokeExact' or 'invokeGeneric'
 877   _imcp_invoke_signature,       // utf8: (variable Symbol*)
 878   _imcp_method_type_value,      // string: (variable java/lang/invoke/MethodType, sic)
 879   _imcp_limit
 880 };
 881 
 882 oop methodOopDesc::method_handle_type() const {
 883   if (!is_method_handle_invoke()) { assert(false, "caller resp."); return NULL; }
 884   oop mt = constants()->resolved_string_at(_imcp_method_type_value);
 885   assert(mt->klass() == SystemDictionary::MethodType_klass(), "");
 886   return mt;
 887 }
 888 
 889 jint* methodOopDesc::method_type_offsets_chain() {
 890   static jint pchase[] = { -1, -1, -1 };
 891   if (pchase[0] == -1) {
 892     jint step0 = in_bytes(constants_offset());
 893     jint step1 = (constantPoolOopDesc::header_size() + _imcp_method_type_value) * HeapWordSize;
 894     // do this in reverse to avoid races:
 895     OrderAccess::release_store(&pchase[1], step1);
 896     OrderAccess::release_store(&pchase[0], step0);
 897   }
 898   return pchase;
 899 }
 900 
 901 //------------------------------------------------------------------------------
 902 // methodOopDesc::is_method_handle_adapter
 903 //
 904 // Tests if this method is an internal adapter frame from the
 905 // MethodHandleCompiler.
 906 // Must be consistent with MethodHandleCompiler::get_method_oop().
 907 bool methodOopDesc::is_method_handle_adapter() const {
 908   if (is_synthetic() &&
 909       !is_native() &&   // has code from MethodHandleCompiler
 910       is_method_handle_invoke_name(name()) &&
 911       MethodHandleCompiler::klass_is_method_handle_adapter_holder(method_holder())) {
 912     assert(!is_method_handle_invoke(), "disjoint");
 913     return true;
 914   } else {
 915     return false;
 916   }
 917 }
 918 
 919 methodHandle methodOopDesc::make_invoke_method(KlassHandle holder,
 920                                                Symbol* name,
 921                                                Symbol* signature,
 922                                                Handle method_type, TRAPS) {
 923   ResourceMark rm;
 924   methodHandle empty;
 925 
 926   assert(holder() == SystemDictionary::MethodHandle_klass(),
 927          "must be a JSR 292 magic type");
 928 
 929   if (TraceMethodHandles) {
 930     tty->print("Creating invoke method for ");
 931     signature->print_value();
 932     tty->cr();
 933   }
 934 
 935   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
 936   name->increment_refcount();
 937   signature->increment_refcount();
 938 
 939   // record non-BCP method types in the constant pool
 940   GrowableArray<KlassHandle>* extra_klasses = NULL;
 941   for (int i = -1, len = java_lang_invoke_MethodType::ptype_count(method_type()); i < len; i++) {
 942     oop ptype = (i == -1
 943                  ? java_lang_invoke_MethodType::rtype(method_type())
 944                  : java_lang_invoke_MethodType::ptype(method_type(), i));
 945     klassOop klass = check_non_bcp_klass(java_lang_Class::as_klassOop(ptype));
 946     if (klass != NULL) {
 947       if (extra_klasses == NULL)
 948         extra_klasses = new GrowableArray<KlassHandle>(len+1);
 949       bool dup = false;
 950       for (int j = 0; j < extra_klasses->length(); j++) {
 951         if (extra_klasses->at(j) == klass) { dup = true; break; }
 952       }
 953       if (!dup)
 954         extra_klasses->append(KlassHandle(THREAD, klass));
 955     }
 956   }
 957 
 958   int extra_klass_count = (extra_klasses == NULL ? 0 : extra_klasses->length());
 959   int cp_length = _imcp_limit + extra_klass_count;
 960   constantPoolHandle cp;
 961   {
 962     constantPoolOop cp_oop = oopFactory::new_constantPool(cp_length, IsSafeConc, CHECK_(empty));
 963     cp = constantPoolHandle(THREAD, cp_oop);
 964   }
 965   cp->symbol_at_put(_imcp_invoke_name,       name);
 966   cp->symbol_at_put(_imcp_invoke_signature,  signature);
 967   cp->string_at_put(_imcp_method_type_value, Universe::the_null_string());
 968   for (int j = 0; j < extra_klass_count; j++) {
 969     KlassHandle klass = extra_klasses->at(j);
 970     cp->klass_at_put(_imcp_limit + j, klass());
 971   }
 972   cp->set_preresolution();
 973   cp->set_pool_holder(holder());
 974 
 975   // set up the fancy stuff:
 976   cp->pseudo_string_at_put(_imcp_method_type_value, method_type());
 977   methodHandle m;
 978   {
 979     int flags_bits = (JVM_MH_INVOKE_BITS | JVM_ACC_PUBLIC | JVM_ACC_FINAL);
 980     methodOop m_oop = oopFactory::new_method(0, accessFlags_from(flags_bits),
 981                                              0, 0, 0, IsSafeConc, CHECK_(empty));
 982     m = methodHandle(THREAD, m_oop);
 983   }
 984   m->set_constants(cp());
 985   m->set_name_index(_imcp_invoke_name);
 986   m->set_signature_index(_imcp_invoke_signature);
 987   assert(is_method_handle_invoke_name(m->name()), "");
 988   assert(m->signature() == signature, "");
 989   assert(m->is_method_handle_invoke(), "");
 990 #ifdef CC_INTERP
 991   ResultTypeFinder rtf(signature);
 992   m->set_result_index(rtf.type());
 993 #endif
 994   m->compute_size_of_parameters(THREAD);
 995   m->set_exception_table(Universe::the_empty_int_array());
 996   m->init_intrinsic_id();
 997   assert(m->intrinsic_id() == vmIntrinsics::_invokeExact ||
 998          m->intrinsic_id() == vmIntrinsics::_invokeGeneric, "must be an invoker");
 999 
1000   // Finally, set up its entry points.
1001   assert(m->method_handle_type() == method_type(), "");
1002   assert(m->can_be_statically_bound(), "");
1003   m->set_vtable_index(methodOopDesc::nonvirtual_vtable_index);
1004   m->link_method(m, CHECK_(empty));
1005 
1006 #ifdef ASSERT
1007   // Make sure the pointer chase works.
1008   address p = (address) m();
1009   for (jint* pchase = method_type_offsets_chain(); (*pchase) != -1; pchase++) {
1010     p = *(address*)(p + (*pchase));
1011   }
1012   assert((oop)p == method_type(), "pointer chase is correct");
1013 #endif
1014 
1015   if (TraceMethodHandles && (Verbose || WizardMode))
1016     m->print_on(tty);
1017 
1018   return m;
1019 }
1020 
1021 klassOop methodOopDesc::check_non_bcp_klass(klassOop klass) {
1022   if (klass != NULL && Klass::cast(klass)->class_loader() != NULL) {
1023     if (Klass::cast(klass)->oop_is_objArray())
1024       klass = objArrayKlass::cast(klass)->bottom_klass();
1025     return klass;
1026   }
1027   return NULL;
1028 }
1029 
1030 
1031 methodHandle methodOopDesc:: clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
1032                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1033   // Code below does not work for native methods - they should never get rewritten anyway
1034   assert(!m->is_native(), "cannot rewrite native methods");
1035   // Allocate new methodOop
1036   AccessFlags flags = m->access_flags();
1037   int checked_exceptions_len = m->checked_exceptions_length();
1038   int localvariable_len = m->localvariable_table_length();
1039   // Allocate newm_oop with the is_conc_safe parameter set
1040   // to IsUnsafeConc to indicate that newm_oop is not yet
1041   // safe for concurrent processing by a GC.
1042   methodOop newm_oop = oopFactory::new_method(new_code_length,
1043                                               flags,
1044                                               new_compressed_linenumber_size,
1045                                               localvariable_len,
1046                                               checked_exceptions_len,
1047                                               IsUnsafeConc,
1048                                               CHECK_(methodHandle()));
1049   methodHandle newm (THREAD, newm_oop);
1050   NOT_PRODUCT(int nmsz = newm->is_parsable() ? newm->size() : -1;)
1051   int new_method_size = newm->method_size();
1052   // Create a shallow copy of methodOopDesc part, but be careful to preserve the new constMethodOop
1053   constMethodOop newcm = newm->constMethod();
1054   NOT_PRODUCT(int ncmsz = newcm->is_parsable() ? newcm->size() : -1;)
1055   int new_const_method_size = newm->constMethod()->object_size();
1056 
1057   memcpy(newm(), m(), sizeof(methodOopDesc));
1058   // Create shallow copy of constMethodOopDesc, but be careful to preserve the methodOop
1059   // is_conc_safe is set to false because that is the value of
1060   // is_conc_safe initialzied into newcm and the copy should
1061   // not overwrite that value.  During the window during which it is
1062   // tagged as unsafe, some extra work could be needed during precleaning
1063   // or concurrent marking but those phases will be correct.  Setting and
1064   // resetting is done in preference to a careful copying into newcm to
1065   // avoid having to know the precise layout of a constMethodOop.
1066   m->constMethod()->set_is_conc_safe(oopDesc::IsUnsafeConc);
1067   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1068 
1069   // NOTE: this is a reachable object that transiently signals "conc_unsafe"
1070   // However, no allocations are done during this window
1071   // during which it is tagged conc_unsafe, so we are assured that any concurrent
1072   // thread will not wait forever for the object to revert to "conc_safe".
1073   // Further, any such conc_unsafe object will indicate a stable size
1074   // through the transition.
1075   memcpy(newcm, m->constMethod(), sizeof(constMethodOopDesc));
1076   m->constMethod()->set_is_conc_safe(oopDesc::IsSafeConc);
1077   assert(m->constMethod()->is_parsable(), "Should remain parsable");
1078 
1079   // Reset correct method/const method, method size, and parameter info
1080   newcm->set_method(newm());
1081   newm->set_constMethod(newcm);
1082   assert(newcm->method() == newm(), "check");
1083   newm->constMethod()->set_code_size(new_code_length);
1084   newm->constMethod()->set_constMethod_size(new_const_method_size);
1085   newm->set_method_size(new_method_size);
1086   assert(newm->code_size() == new_code_length, "check");
1087   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1088   assert(newm->localvariable_table_length() == localvariable_len, "check");
1089   // Copy new byte codes
1090   memcpy(newm->code_base(), new_code, new_code_length);
1091   // Copy line number table
1092   if (new_compressed_linenumber_size > 0) {
1093     memcpy(newm->compressed_linenumber_table(),
1094            new_compressed_linenumber_table,
1095            new_compressed_linenumber_size);
1096   }
1097   // Copy checked_exceptions
1098   if (checked_exceptions_len > 0) {
1099     memcpy(newm->checked_exceptions_start(),
1100            m->checked_exceptions_start(),
1101            checked_exceptions_len * sizeof(CheckedExceptionElement));
1102   }
1103   // Copy local variable number table
1104   if (localvariable_len > 0) {
1105     memcpy(newm->localvariable_table_start(),
1106            m->localvariable_table_start(),
1107            localvariable_len * sizeof(LocalVariableTableElement));
1108   }
1109 
1110   // Only set is_conc_safe to true when changes to newcm are
1111   // complete.
1112   assert(!newm->is_parsable()  || nmsz  < 0 || newm->size()  == nmsz,  "newm->size()  inconsistency");
1113   assert(!newcm->is_parsable() || ncmsz < 0 || newcm->size() == ncmsz, "newcm->size() inconsistency");
1114   newcm->set_is_conc_safe(true);
1115   return newm;
1116 }
1117 
1118 vmSymbols::SID methodOopDesc::klass_id_for_intrinsics(klassOop holder) {
1119   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1120   // because we are not loading from core libraries
1121   if (instanceKlass::cast(holder)->class_loader() != NULL)
1122     return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1123 
1124   // see if the klass name is well-known:
1125   Symbol* klass_name = instanceKlass::cast(holder)->name();
1126   return vmSymbols::find_sid(klass_name);
1127 }
1128 
1129 void methodOopDesc::init_intrinsic_id() {
1130   assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
1131   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1132   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1133   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1134 
1135   // the klass name is well-known:
1136   vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
1137   assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
1138 
1139   // ditto for method and signature:
1140   vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1141   if (name_id == vmSymbols::NO_SID)  return;
1142   vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1143   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1144       && sig_id == vmSymbols::NO_SID)  return;
1145   jshort flags = access_flags().as_short();
1146 
1147   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1148   if (id != vmIntrinsics::_none) {
1149     set_intrinsic_id(id);
1150     return;
1151   }
1152 
1153   // A few slightly irregular cases:
1154   switch (klass_id) {
1155   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
1156     // Second chance: check in regular Math.
1157     switch (name_id) {
1158     case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
1159     case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
1160     case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
1161       // pretend it is the corresponding method in the non-strict class:
1162       klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1163       id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1164       break;
1165     }
1166     break;
1167 
1168   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1169   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1170     if (is_static() || !is_native())  break;
1171     switch (name_id) {
1172     case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name):
1173       if (!AllowInvokeGeneric)  break;
1174     case vmSymbols::VM_SYMBOL_ENUM_NAME(invoke_name):
1175       id = vmIntrinsics::_invokeGeneric;
1176       break;
1177     case vmSymbols::VM_SYMBOL_ENUM_NAME(invokeExact_name):
1178       id = vmIntrinsics::_invokeExact;
1179       break;
1180     }
1181     break;
1182   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InvokeDynamic):
1183     if (!is_static() || !is_native())  break;
1184     id = vmIntrinsics::_invokeDynamic;
1185     break;
1186   }
1187 
1188   if (id != vmIntrinsics::_none) {
1189     // Set up its iid.  It is an alias method.
1190     set_intrinsic_id(id);
1191     return;
1192   }
1193 }
1194 
1195 // These two methods are static since a GC may move the methodOopDesc
1196 bool methodOopDesc::load_signature_classes(methodHandle m, TRAPS) {
1197   bool sig_is_loaded = true;
1198   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1199   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1200   ResourceMark rm(THREAD);
1201   Symbol*  signature = m->signature();
1202   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1203     if (ss.is_object()) {
1204       Symbol* sym = ss.as_symbol(CHECK_(false));
1205       Symbol*  name  = sym;
1206       klassOop klass = SystemDictionary::resolve_or_null(name, class_loader,
1207                                              protection_domain, THREAD);
1208       // We are loading classes eagerly. If a ClassNotFoundException or
1209       // a LinkageError was generated, be sure to ignore it.
1210       if (HAS_PENDING_EXCEPTION) {
1211         if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
1212             PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
1213           CLEAR_PENDING_EXCEPTION;
1214         } else {
1215           return false;
1216         }
1217       }
1218       if( klass == NULL) { sig_is_loaded = false; }
1219     }
1220   }
1221   return sig_is_loaded;
1222 }
1223 
1224 bool methodOopDesc::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1225   Handle class_loader(THREAD, instanceKlass::cast(m->method_holder())->class_loader());
1226   Handle protection_domain(THREAD, Klass::cast(m->method_holder())->protection_domain());
1227   ResourceMark rm(THREAD);
1228   Symbol*  signature = m->signature();
1229   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1230     if (ss.type() == T_OBJECT) {
1231       Symbol* name = ss.as_symbol_or_null();
1232       if (name == NULL) return true;
1233       klassOop klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1234       if (klass == NULL) return true;
1235     }
1236   }
1237   return false;
1238 }
1239 
1240 // Exposed so field engineers can debug VM
1241 void methodOopDesc::print_short_name(outputStream* st) {
1242   ResourceMark rm;
1243 #ifdef PRODUCT
1244   st->print(" %s::", method_holder()->klass_part()->external_name());
1245 #else
1246   st->print(" %s::", method_holder()->klass_part()->internal_name());
1247 #endif
1248   name()->print_symbol_on(st);
1249   if (WizardMode) signature()->print_symbol_on(st);
1250 }
1251 
1252 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1253 static void reorder_based_on_method_index(objArrayOop methods,
1254                                           objArrayOop annotations,
1255                                           GrowableArray<oop>* temp_array) {
1256   if (annotations == NULL) {
1257     return;
1258   }
1259 
1260   int length = methods->length();
1261   int i;
1262   // Copy to temp array
1263   temp_array->clear();
1264   for (i = 0; i < length; i++) {
1265     temp_array->append(annotations->obj_at(i));
1266   }
1267 
1268   // Copy back using old method indices
1269   for (i = 0; i < length; i++) {
1270     methodOop m = (methodOop) methods->obj_at(i);
1271     annotations->obj_at_put(i, temp_array->at(m->method_idnum()));
1272   }
1273 }
1274 
1275 // Comparer for sorting an object array containing
1276 // methodOops.
1277 // Used non-template method_comparator methods since
1278 // Visual Studio 2003 compiler generates incorrect
1279 // optimized code for it.
1280 static int method_comparator_narrowOop(narrowOop a, narrowOop b) {
1281   methodOop m = (methodOop)oopDesc::decode_heap_oop_not_null(a);
1282   methodOop n = (methodOop)oopDesc::decode_heap_oop_not_null(b);
1283   return m->name()->fast_compare(n->name());
1284 }
1285 static int method_comparator_oop(oop a, oop b) {
1286   methodOop m = (methodOop)a;
1287   methodOop n = (methodOop)b;
1288   return m->name()->fast_compare(n->name());
1289 }
1290 
1291 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1292 void methodOopDesc::sort_methods(objArrayOop methods,
1293                                  objArrayOop methods_annotations,
1294                                  objArrayOop methods_parameter_annotations,
1295                                  objArrayOop methods_default_annotations,
1296                                  bool idempotent) {
1297   int length = methods->length();
1298   if (length > 1) {
1299     bool do_annotations = false;
1300     if (methods_annotations != NULL ||
1301         methods_parameter_annotations != NULL ||
1302         methods_default_annotations != NULL) {
1303       do_annotations = true;
1304     }
1305     if (do_annotations) {
1306       // Remember current method ordering so we can reorder annotations
1307       for (int i = 0; i < length; i++) {
1308         methodOop m = (methodOop) methods->obj_at(i);
1309         m->set_method_idnum(i);
1310       }
1311     }
1312     {
1313       No_Safepoint_Verifier nsv;
1314       if (UseCompressedOops) {
1315         QuickSort::sort<narrowOop>((narrowOop*)(methods->base()), length, method_comparator_narrowOop, idempotent);
1316       } else {
1317         QuickSort::sort<oop>((oop*)(methods->base()), length, method_comparator_oop, idempotent);
1318       }
1319       if (UseConcMarkSweepGC) {
1320         // For CMS we need to dirty the cards for the array
1321         BarrierSet* bs = Universe::heap()->barrier_set();
1322         assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1323         bs->write_ref_array(methods->base(), length);
1324       }
1325     }
1326 
1327     // Sort annotations if necessary
1328     assert(methods_annotations == NULL           || methods_annotations->length() == methods->length(), "");
1329     assert(methods_parameter_annotations == NULL || methods_parameter_annotations->length() == methods->length(), "");
1330     assert(methods_default_annotations == NULL   || methods_default_annotations->length() == methods->length(), "");
1331     if (do_annotations) {
1332       ResourceMark rm;
1333       // Allocate temporary storage
1334       GrowableArray<oop>* temp_array = new GrowableArray<oop>(length);
1335       reorder_based_on_method_index(methods, methods_annotations, temp_array);
1336       reorder_based_on_method_index(methods, methods_parameter_annotations, temp_array);
1337       reorder_based_on_method_index(methods, methods_default_annotations, temp_array);
1338     }
1339 
1340     // Reset method ordering
1341     for (int i = 0; i < length; i++) {
1342       methodOop m = (methodOop) methods->obj_at(i);
1343       m->set_method_idnum(i);
1344     }
1345   }
1346 }
1347 
1348 
1349 //-----------------------------------------------------------------------------------
1350 // Non-product code
1351 
1352 #ifndef PRODUCT
1353 class SignatureTypePrinter : public SignatureTypeNames {
1354  private:
1355   outputStream* _st;
1356   bool _use_separator;
1357 
1358   void type_name(const char* name) {
1359     if (_use_separator) _st->print(", ");
1360     _st->print(name);
1361     _use_separator = true;
1362   }
1363 
1364  public:
1365   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1366     _st = st;
1367     _use_separator = false;
1368   }
1369 
1370   void print_parameters()              { _use_separator = false; iterate_parameters(); }
1371   void print_returntype()              { _use_separator = false; iterate_returntype(); }
1372 };
1373 
1374 
1375 void methodOopDesc::print_name(outputStream* st) {
1376   Thread *thread = Thread::current();
1377   ResourceMark rm(thread);
1378   SignatureTypePrinter sig(signature(), st);
1379   st->print("%s ", is_static() ? "static" : "virtual");
1380   sig.print_returntype();
1381   st->print(" %s.", method_holder()->klass_part()->internal_name());
1382   name()->print_symbol_on(st);
1383   st->print("(");
1384   sig.print_parameters();
1385   st->print(")");
1386 }
1387 
1388 
1389 void methodOopDesc::print_codes_on(outputStream* st) const {
1390   print_codes_on(0, code_size(), st);
1391 }
1392 
1393 void methodOopDesc::print_codes_on(int from, int to, outputStream* st) const {
1394   Thread *thread = Thread::current();
1395   ResourceMark rm(thread);
1396   methodHandle mh (thread, (methodOop)this);
1397   BytecodeStream s(mh);
1398   s.set_interval(from, to);
1399   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1400   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1401 }
1402 #endif // not PRODUCT
1403 
1404 
1405 // Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1406 // between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1407 // we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1408 // as end-of-stream terminator.
1409 
1410 void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1411   // bci and line number does not compress into single byte.
1412   // Write out escape character and use regular compression for bci and line number.
1413   write_byte((jubyte)0xFF);
1414   write_signed_int(bci_delta);
1415   write_signed_int(line_delta);
1416 }
1417 
1418 // See comment in methodOop.hpp which explains why this exists.
1419 #if defined(_M_AMD64) && _MSC_VER >= 1400
1420 #pragma optimize("", off)
1421 void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1422   write_pair_inline(bci, line);
1423 }
1424 #pragma optimize("", on)
1425 #endif
1426 
1427 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1428   _bci = 0;
1429   _line = 0;
1430 };
1431 
1432 
1433 bool CompressedLineNumberReadStream::read_pair() {
1434   jubyte next = read_byte();
1435   // Check for terminator
1436   if (next == 0) return false;
1437   if (next == 0xFF) {
1438     // Escape character, regular compression used
1439     _bci  += read_signed_int();
1440     _line += read_signed_int();
1441   } else {
1442     // Single byte compression used
1443     _bci  += next >> 3;
1444     _line += next & 0x7;
1445   }
1446   return true;
1447 }
1448 
1449 
1450 Bytecodes::Code methodOopDesc::orig_bytecode_at(int bci) const {
1451   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1452   for (; bp != NULL; bp = bp->next()) {
1453     if (bp->match(this, bci)) {
1454       return bp->orig_bytecode();
1455     }
1456   }
1457   ShouldNotReachHere();
1458   return Bytecodes::_shouldnotreachhere;
1459 }
1460 
1461 void methodOopDesc::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1462   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1463   BreakpointInfo* bp = instanceKlass::cast(method_holder())->breakpoints();
1464   for (; bp != NULL; bp = bp->next()) {
1465     if (bp->match(this, bci)) {
1466       bp->set_orig_bytecode(code);
1467       // and continue, in case there is more than one
1468     }
1469   }
1470 }
1471 
1472 void methodOopDesc::set_breakpoint(int bci) {
1473   instanceKlass* ik = instanceKlass::cast(method_holder());
1474   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1475   bp->set_next(ik->breakpoints());
1476   ik->set_breakpoints(bp);
1477   // do this last:
1478   bp->set(this);
1479 }
1480 
1481 static void clear_matches(methodOop m, int bci) {
1482   instanceKlass* ik = instanceKlass::cast(m->method_holder());
1483   BreakpointInfo* prev_bp = NULL;
1484   BreakpointInfo* next_bp;
1485   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1486     next_bp = bp->next();
1487     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1488     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1489       // do this first:
1490       bp->clear(m);
1491       // unhook it
1492       if (prev_bp != NULL)
1493         prev_bp->set_next(next_bp);
1494       else
1495         ik->set_breakpoints(next_bp);
1496       delete bp;
1497       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1498       // at same location. So we have multiple matching (method_index and bci)
1499       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1500       // breakpoint for clear_breakpoint request and keep all other method versions
1501       // BreakpointInfo for future clear_breakpoint request.
1502       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1503       // which is being called when class is unloaded. We delete all the Breakpoint
1504       // information for all versions of method. We may not correctly restore the original
1505       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1506       // so these methods won't be used anymore.
1507       if (bci >= 0) {
1508         break;
1509       }
1510     } else {
1511       // This one is a keeper.
1512       prev_bp = bp;
1513     }
1514   }
1515 }
1516 
1517 void methodOopDesc::clear_breakpoint(int bci) {
1518   assert(bci >= 0, "");
1519   clear_matches(this, bci);
1520 }
1521 
1522 void methodOopDesc::clear_all_breakpoints() {
1523   clear_matches(this, -1);
1524 }
1525 
1526 
1527 int methodOopDesc::invocation_count() {
1528   if (TieredCompilation) {
1529     const methodDataOop mdo = method_data();
1530     if (invocation_counter()->carry() || ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1531       return InvocationCounter::count_limit;
1532     } else {
1533       return invocation_counter()->count() + ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1534     }
1535   } else {
1536     return invocation_counter()->count();
1537   }
1538 }
1539 
1540 int methodOopDesc::backedge_count() {
1541   if (TieredCompilation) {
1542     const methodDataOop mdo = method_data();
1543     if (backedge_counter()->carry() || ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1544       return InvocationCounter::count_limit;
1545     } else {
1546       return backedge_counter()->count() + ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1547     }
1548   } else {
1549     return backedge_counter()->count();
1550   }
1551 }
1552 
1553 int methodOopDesc::highest_comp_level() const {
1554   methodDataOop mdo = method_data();
1555   if (mdo != NULL) {
1556     return mdo->highest_comp_level();
1557   } else {
1558     return CompLevel_none;
1559   }
1560 }
1561 
1562 int methodOopDesc::highest_osr_comp_level() const {
1563   methodDataOop mdo = method_data();
1564   if (mdo != NULL) {
1565     return mdo->highest_osr_comp_level();
1566   } else {
1567     return CompLevel_none;
1568   }
1569 }
1570 
1571 void methodOopDesc::set_highest_comp_level(int level) {
1572   methodDataOop mdo = method_data();
1573   if (mdo != NULL) {
1574     mdo->set_highest_comp_level(level);
1575   }
1576 }
1577 
1578 void methodOopDesc::set_highest_osr_comp_level(int level) {
1579   methodDataOop mdo = method_data();
1580   if (mdo != NULL) {
1581     mdo->set_highest_osr_comp_level(level);
1582   }
1583 }
1584 
1585 BreakpointInfo::BreakpointInfo(methodOop m, int bci) {
1586   _bci = bci;
1587   _name_index = m->name_index();
1588   _signature_index = m->signature_index();
1589   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1590   if (_orig_bytecode == Bytecodes::_breakpoint)
1591     _orig_bytecode = m->orig_bytecode_at(_bci);
1592   _next = NULL;
1593 }
1594 
1595 void BreakpointInfo::set(methodOop method) {
1596 #ifdef ASSERT
1597   {
1598     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1599     if (code == Bytecodes::_breakpoint)
1600       code = method->orig_bytecode_at(_bci);
1601     assert(orig_bytecode() == code, "original bytecode must be the same");
1602   }
1603 #endif
1604   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1605   method->incr_number_of_breakpoints();
1606   SystemDictionary::notice_modification();
1607   {
1608     // Deoptimize all dependents on this method
1609     Thread *thread = Thread::current();
1610     HandleMark hm(thread);
1611     methodHandle mh(thread, method);
1612     Universe::flush_dependents_on_method(mh);
1613   }
1614 }
1615 
1616 void BreakpointInfo::clear(methodOop method) {
1617   *method->bcp_from(_bci) = orig_bytecode();
1618   assert(method->number_of_breakpoints() > 0, "must not go negative");
1619   method->decr_number_of_breakpoints();
1620 }