method.cpp 69.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25
#include "precompiled.hpp"
26
#include "classfile/metadataOnStackMark.hpp"
27 28 29 30 31 32 33 34 35 36
#include "classfile/systemDictionary.hpp"
#include "code/debugInfoRec.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "interpreter/bytecodeStream.hpp"
#include "interpreter/bytecodeTracer.hpp"
#include "interpreter/bytecodes.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/oopMapCache.hpp"
#include "memory/gcLocker.hpp"
#include "memory/generation.hpp"
37
#include "memory/heapInspection.hpp"
38
#include "memory/metadataFactory.hpp"
39
#include "memory/oopFactory.hpp"
40
#include "oops/constMethod.hpp"
41 42
#include "oops/methodData.hpp"
#include "oops/method.hpp"
43
#include "oops/oop.inline.hpp"
44
#include "oops/symbol.hpp"
45
#include "prims/jvmtiExport.hpp"
46
#include "prims/methodHandles.hpp"
47 48 49 50 51
#include "prims/nativeLookup.hpp"
#include "runtime/arguments.hpp"
#include "runtime/compilationPolicy.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handles.inline.hpp"
52
#include "runtime/orderAccess.inline.hpp"
53 54 55
#include "runtime/relocator.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
56
#include "utilities/quickSort.hpp"
57
#include "utilities/xmlstream.hpp"
D
duke 已提交
58

59
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
D
duke 已提交
60

61 62 63
// Implementation of Method

Method* Method::allocate(ClassLoaderData* loader_data,
64 65
                         int byte_code_size,
                         AccessFlags access_flags,
C
coleenp 已提交
66
                         InlineTableSizes* sizes,
67 68
                         ConstMethod::MethodType method_type,
                         TRAPS) {
69 70 71
  assert(!access_flags.is_native() || byte_code_size == 0,
         "native methods should not contain byte codes");
  ConstMethod* cm = ConstMethod::allocate(loader_data,
72
                                          byte_code_size,
C
coleenp 已提交
73
                                          sizes,
74 75
                                          method_type,
                                          CHECK_NULL);
76 77 78

  int size = Method::size(access_flags.is_native());

79
  return new (loader_data, size, false, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags, size);
80 81
}

82
Method::Method(ConstMethod* xconst, AccessFlags access_flags, int size) {
83 84 85 86 87 88 89 90 91
  No_Safepoint_Verifier no_safepoint;
  set_constMethod(xconst);
  set_access_flags(access_flags);
  set_method_size(size);
#ifdef CC_INTERP
  set_result_index(T_VOID);
#endif
  set_intrinsic_id(vmIntrinsics::_none);
  set_jfr_towrite(false);
92 93 94
  set_force_inline(false);
  set_hidden(false);
  set_dont_inline(false);
95
  set_method_data(NULL);
96
  set_method_counters(NULL);
97 98 99 100 101 102 103 104 105 106 107 108 109 110
  set_vtable_index(Method::garbage_vtable_index);

  // Fix and bury in Method*
  set_interpreter_entry(NULL); // sets i2i entry and from_int
  set_adapter_entry(NULL);
  clear_code(); // from_c/from_i get set to c2i/i2i

  if (access_flags.is_native()) {
    clear_native_function();
    set_signature_handler(NULL);
  }

  NOT_PRODUCT(set_compiled_invocation_count(0);)
}
D
duke 已提交
111

112 113 114 115 116 117 118
// Release Method*.  The nmethod will be gone when we get here because
// we've walked the code cache.
void Method::deallocate_contents(ClassLoaderData* loader_data) {
  MetadataFactory::free_metadata(loader_data, constMethod());
  set_constMethod(NULL);
  MetadataFactory::free_metadata(loader_data, method_data());
  set_method_data(NULL);
119 120
  MetadataFactory::free_metadata(loader_data, method_counters());
  set_method_counters(NULL);
121 122 123 124 125
  // The nmethod will be gone when we get here.
  if (code() != NULL) _code = NULL;
}

address Method::get_i2c_entry() {
D
duke 已提交
126 127 128 129
  assert(_adapter != NULL, "must have");
  return _adapter->get_i2c_entry();
}

130
address Method::get_c2i_entry() {
D
duke 已提交
131 132 133 134
  assert(_adapter != NULL, "must have");
  return _adapter->get_c2i_entry();
}

135
address Method::get_c2i_unverified_entry() {
D
duke 已提交
136 137 138 139
  assert(_adapter != NULL, "must have");
  return _adapter->get_c2i_unverified_entry();
}

140
char* Method::name_and_sig_as_C_string() const {
H
hseigel 已提交
141
  return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
D
duke 已提交
142 143
}

144
char* Method::name_and_sig_as_C_string(char* buf, int size) const {
H
hseigel 已提交
145
  return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
D
duke 已提交
146 147
}

148
char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
D
duke 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161
  const char* klass_name = klass->external_name();
  int klass_name_len  = (int)strlen(klass_name);
  int method_name_len = method_name->utf8_length();
  int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
  char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
  strcpy(dest, klass_name);
  dest[klass_name_len] = '.';
  strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
  strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
  dest[len] = 0;
  return dest;
}

162
char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
163
  Symbol* klass_name = klass->name();
D
duke 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  klass_name->as_klass_external_name(buf, size);
  int len = (int)strlen(buf);

  if (len < size - 1) {
    buf[len++] = '.';

    method_name->as_C_string(&(buf[len]), size - len);
    len = (int)strlen(buf);

    signature->as_C_string(&(buf[len]), size - len);
  }

  return buf;
}

179
int Method::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
D
duke 已提交
180 181
  // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
  // access exception table
182
  ExceptionTable table(mh());
183
  int length = table.length();
D
duke 已提交
184
  // iterate through all entries sequentially
185
  constantPoolHandle pool(THREAD, mh->constants());
186 187
  for (int i = 0; i < length; i ++) {
    //reacquire the table in case a GC happened
188
    ExceptionTable table(mh());
189 190
    int beg_bci = table.start_pc(i);
    int end_bci = table.end_pc(i);
D
duke 已提交
191 192 193
    assert(beg_bci <= end_bci, "inconsistent exception table");
    if (beg_bci <= throw_bci && throw_bci < end_bci) {
      // exception handler bci range covers throw_bci => investigate further
194 195
      int handler_bci = table.handler_pc(i);
      int klass_index = table.catch_type_index(i);
D
duke 已提交
196 197 198 199 200 201 202 203
      if (klass_index == 0) {
        return handler_bci;
      } else if (ex_klass.is_null()) {
        return handler_bci;
      } else {
        // we know the exception class => get the constraint class
        // this may require loading of the constraint class; if verification
        // fails or some other exception occurs, return handler_bci
204
        Klass* k = pool->klass_at(klass_index, CHECK_(handler_bci));
D
duke 已提交
205 206 207 208 209 210 211 212 213 214 215 216
        KlassHandle klass = KlassHandle(THREAD, k);
        assert(klass.not_null(), "klass not loaded");
        if (ex_klass->is_subtype_of(klass())) {
          return handler_bci;
        }
      }
    }
  }

  return -1;
}

217
void Method::mask_for(int bci, InterpreterOopMap* mask) {
D
duke 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231

  Thread* myThread    = Thread::current();
  methodHandle h_this(myThread, this);
#ifdef ASSERT
  bool has_capability = myThread->is_VM_thread() ||
                        myThread->is_ConcurrentGC_thread() ||
                        myThread->is_GC_task_thread();

  if (!has_capability) {
    if (!VerifyStack && !VerifyLastFrame) {
      // verify stack calls this outside VM thread
      warning("oopmap should only be accessed by the "
              "VM, GC task or CMS threads (or during debugging)");
      InterpreterOopMap local_mask;
232
      method_holder()->mask_for(h_this, bci, &local_mask);
D
duke 已提交
233 234 235 236
      local_mask.print();
    }
  }
#endif
237
  method_holder()->mask_for(h_this, bci, mask);
D
duke 已提交
238 239 240 241
  return;
}


242
int Method::bci_from(address bcp) const {
243 244
#ifdef ASSERT
  { ResourceMark rm;
245 246
  assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
         err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
247 248
  }
#endif
D
duke 已提交
249 250 251 252 253 254 255 256
  return bcp - code_base();
}


// Return (int)bcx if it appears to be a valid BCI.
// Return bci_from((address)bcx) if it appears to be a valid BCP.
// Return -1 otherwise.
// Used by profiling code, when invalid data is a possibility.
257 258
// The caller is responsible for validating the Method* itself.
int Method::validate_bci_from_bcx(intptr_t bcx) const {
D
duke 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  // keep bci as -1 if not a valid bci
  int bci = -1;
  if (bcx == 0 || (address)bcx == code_base()) {
    // code_size() may return 0 and we allow 0 here
    // the method may be native
    bci = 0;
  } else if (frame::is_bci(bcx)) {
    if (bcx < code_size()) {
      bci = (int)bcx;
    }
  } else if (contains((address)bcx)) {
    bci = (address)bcx - code_base();
  }
  // Assert that if we have dodged any asserts, bci is negative.
  assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
  return bci;
}

277
address Method::bcp_from(int bci) const {
278
  assert((is_native() && bci == 0)  || (!is_native() && 0 <= bci && bci < code_size()), err_msg("illegal bci: %d", bci));
D
duke 已提交
279 280 281 282 283 284
  address bcp = code_base() + bci;
  assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
  return bcp;
}


285
int Method::size(bool is_native) {
D
duke 已提交
286 287 288 289 290 291 292
  // If native, then include pointers for native_function and signature_handler
  int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
  int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
  return align_object_size(header_size() + extra_words);
}


293 294
Symbol* Method::klass_name() const {
  Klass* k = method_holder();
D
duke 已提交
295
  assert(k->is_klass(), "must be klass");
296
  InstanceKlass* ik = (InstanceKlass*) k;
D
duke 已提交
297 298 299 300 301 302 303 304 305
  return ik->name();
}


// Attempt to return method oop to original state.  Clear any pointers
// (to objects outside the shared spaces).  We won't be able to predict
// where they should point in a new JVM.  Further initialize some
// entries now in order allow them to be write protected later.

306
void Method::remove_unshareable_info() {
D
duke 已提交
307 308 309 310
  unlink_method();
}


311 312
bool Method::was_executed_more_than(int n) {
  // Invocation counter is reset when the Method* is compiled.
D
duke 已提交
313 314 315 316 317 318
  // If the method has compiled code we therefore assume it has
  // be excuted more than n times.
  if (is_accessor() || is_empty_method() || (code() != NULL)) {
    // interpreter doesn't bump invocation counter of trivial methods
    // compiler does not bump invocation counter of compiled methods
    return true;
I
iveresov 已提交
319
  }
320 321 322 323
  else if ((method_counters() != NULL &&
            method_counters()->invocation_counter()->carry()) ||
           (method_data() != NULL &&
            method_data()->invocation_counter()->carry())) {
D
duke 已提交
324 325 326 327 328 329 330 331 332 333 334
    // The carry bit is set when the counter overflows and causes
    // a compilation to occur.  We don't know how many times
    // the counter has been reset, so we simply assume it has
    // been executed more than n times.
    return true;
  } else {
    return invocation_count() > n;
  }
}

#ifndef PRODUCT
335
void Method::print_invocation_count() {
D
duke 已提交
336 337 338 339
  if (is_static()) tty->print("static ");
  if (is_final()) tty->print("final ");
  if (is_synchronized()) tty->print("synchronized ");
  if (is_native()) tty->print("native ");
340
  method_holder()->name()->print_symbol_on(tty);
D
duke 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  tty->print(".");
  name()->print_symbol_on(tty);
  signature()->print_symbol_on(tty);

  if (WizardMode) {
    // dump the size of the byte codes
    tty->print(" {%d}", code_size());
  }
  tty->cr();

  tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
  tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
  tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
  if (CountCompiledCalls) {
    tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
  }

}
#endif

361
// Build a MethodData* object to hold information about this method
D
duke 已提交
362
// collected in the interpreter.
363
void Method::build_interpreter_method_data(methodHandle method, TRAPS) {
364 365
  // Do not profile method if current thread holds the pending list lock,
  // which avoids deadlock for acquiring the MethodData_lock.
366
  if (InstanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
367 368 369
    return;
  }

D
duke 已提交
370
  // Grab a lock here to prevent multiple
371
  // MethodData*s from being created.
D
duke 已提交
372 373
  MutexLocker ml(MethodData_lock, THREAD);
  if (method->method_data() == NULL) {
374 375
    ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
    MethodData* method_data = MethodData::allocate(loader_data, method, CHECK);
D
duke 已提交
376 377 378 379 380 381 382 383 384 385 386
    method->set_method_data(method_data);
    if (PrintMethodData && (Verbose || WizardMode)) {
      ResourceMark rm(THREAD);
      tty->print("build_interpreter_method_data for ");
      method->print_name(tty);
      tty->cr();
      // At the end of the run, the MDO, full of data, will be dumped.
    }
  }
}

387 388 389 390 391 392 393 394 395 396 397 398
MethodCounters* Method::build_method_counters(Method* m, TRAPS) {
  methodHandle mh(m);
  ClassLoaderData* loader_data = mh->method_holder()->class_loader_data();
  MethodCounters* counters = MethodCounters::allocate(loader_data, CHECK_NULL);
  if (mh->method_counters() == NULL) {
    mh->set_method_counters(counters);
  } else {
    MetadataFactory::free_metadata(loader_data, counters);
  }
  return mh->method_counters();
}

399
void Method::cleanup_inline_caches() {
D
duke 已提交
400 401 402 403 404
  // The current system doesn't use inline caches in the interpreter
  // => nothing to do (keep this method around for future use)
}


405
int Method::extra_stack_words() {
406
  // not an inline function, to avoid a header dependency on Interpreter
407
  return extra_stack_entries() * Interpreter::stackElementSize;
408 409 410
}


411
void Method::compute_size_of_parameters(Thread *thread) {
412
  ArgumentSizeComputer asc(signature());
D
duke 已提交
413 414 415 416
  set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
}

#ifdef CC_INTERP
417
void Method::set_result_index(BasicType type)          {
D
duke 已提交
418 419 420 421
  _result_index = Interpreter::BasicType_as_index(type);
}
#endif

422
BasicType Method::result_type() const {
D
duke 已提交
423 424 425 426 427
  ResultTypeFinder rtf(signature());
  return rtf.type();
}


428
bool Method::is_empty_method() const {
D
duke 已提交
429 430 431 432 433
  return  code_size() == 1
      && *code_base() == Bytecodes::_return;
}


434
bool Method::is_vanilla_constructor() const {
D
duke 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
  // which only calls the superclass vanilla constructor and possibly does stores of
  // zero constants to local fields:
  //
  //   aload_0
  //   invokespecial
  //   indexbyte1
  //   indexbyte2
  //
  // followed by an (optional) sequence of:
  //
  //   aload_0
  //   aconst_null / iconst_0 / fconst_0 / dconst_0
  //   putfield
  //   indexbyte1
  //   indexbyte2
  //
  // followed by:
  //
  //   return

  assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
  assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
  int size = code_size();
  // Check if size match
  if (size == 0 || size % 5 != 0) return false;
  address cb = code_base();
  int last = size - 1;
  if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
    // Does not call superclass default constructor
    return false;
  }
  // Check optional sequence
  for (int i = 4; i < last; i += 5) {
    if (cb[i] != Bytecodes::_aload_0) return false;
    if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
    if (cb[i+2] != Bytecodes::_putfield) return false;
  }
  return true;
}


477 478
bool Method::compute_has_loops_flag() {
  BytecodeStream bcs(this);
D
duke 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
  Bytecodes::Code bc;

  while ((bc = bcs.next()) >= 0) {
    switch( bc ) {
      case Bytecodes::_ifeq:
      case Bytecodes::_ifnull:
      case Bytecodes::_iflt:
      case Bytecodes::_ifle:
      case Bytecodes::_ifne:
      case Bytecodes::_ifnonnull:
      case Bytecodes::_ifgt:
      case Bytecodes::_ifge:
      case Bytecodes::_if_icmpeq:
      case Bytecodes::_if_icmpne:
      case Bytecodes::_if_icmplt:
      case Bytecodes::_if_icmpgt:
      case Bytecodes::_if_icmple:
      case Bytecodes::_if_icmpge:
      case Bytecodes::_if_acmpeq:
      case Bytecodes::_if_acmpne:
      case Bytecodes::_goto:
      case Bytecodes::_jsr:
        if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
        break;

      case Bytecodes::_goto_w:
      case Bytecodes::_jsr_w:
        if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
        break;
    }
  }
  _access_flags.set_loops_flag_init();
  return _access_flags.has_loops();
}

514 515
bool Method::is_final_method(AccessFlags class_access_flags) const {
  // or "does_not_require_vtable_entry"
516
  // default method or overpass can occur, is not final (reuses vtable entry)
517
  // private methods get vtable entries for backward class compatibility.
518
  if (is_overpass() || is_default_method())  return false;
519 520
  return is_final() || class_access_flags.is_final();
}
D
duke 已提交
521

522
bool Method::is_final_method() const {
523
  return is_final_method(method_holder()->access_flags());
D
duke 已提交
524 525
}

526 527 528 529 530 531 532 533 534 535
bool Method::is_default_method() const {
  if (method_holder() != NULL &&
      method_holder()->is_interface() &&
      !is_abstract()) {
    return true;
  } else {
    return false;
  }
}

536 537 538
bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
  if (is_final_method(class_access_flags))  return true;
#ifdef ASSERT
539
  ResourceMark rm;
540
  bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
541 542 543
  if (class_access_flags.is_interface()) {
      assert(is_nonv == is_static(), err_msg("is_nonv=%s", name_and_sig_as_C_string()));
  }
544 545 546
#endif
  assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
  return vtable_index() == nonvirtual_vtable_index;
D
duke 已提交
547 548
}

549
bool Method::can_be_statically_bound() const {
550
  return can_be_statically_bound(method_holder()->access_flags());
D
duke 已提交
551 552
}

553
bool Method::is_accessor() const {
D
duke 已提交
554 555
  if (code_size() != 5) return false;
  if (size_of_parameters() != 1) return false;
556 557 558 559
  if (java_code_at(0) != Bytecodes::_aload_0 ) return false;
  if (java_code_at(1) != Bytecodes::_getfield) return false;
  if (java_code_at(4) != Bytecodes::_areturn &&
      java_code_at(4) != Bytecodes::_ireturn ) return false;
D
duke 已提交
560 561 562 563
  return true;
}


564
bool Method::is_initializer() const {
565 566 567
  return name() == vmSymbols::object_initializer_name() || is_static_initializer();
}

568
bool Method::has_valid_initializer_flags() const {
569
  return (is_static() ||
570
          method_holder()->major_version() < 51);
571 572
}

573
bool Method::is_static_initializer() const {
574 575 576 577 578
  // For classfiles version 51 or greater, ensure that the clinit method is
  // static.  Non-static methods with the name "<clinit>" are not static
  // initializers. (older classfiles exempted for backward compatibility)
  return name() == vmSymbols::class_initializer_name() &&
         has_valid_initializer_flags();
D
duke 已提交
579 580 581
}


582
objArrayHandle Method::resolved_checked_exceptions_impl(Method* this_oop, TRAPS) {
D
duke 已提交
583 584 585 586 587
  int length = this_oop->checked_exceptions_length();
  if (length == 0) {  // common case
    return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
  } else {
    methodHandle h_this(THREAD, this_oop);
588
    objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
D
duke 已提交
589 590 591
    objArrayHandle mirrors (THREAD, m_oop);
    for (int i = 0; i < length; i++) {
      CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
592
      Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
H
hseigel 已提交
593 594
      assert(k->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
      mirrors->obj_at_put(i, k->java_mirror());
D
duke 已提交
595 596 597 598 599 600
    }
    return mirrors;
  }
};


601
int Method::line_number_from_bci(int bci) const {
D
duke 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
  if (bci == SynchronizationEntryBCI) bci = 0;
  assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
  int best_bci  =  0;
  int best_line = -1;

  if (has_linenumber_table()) {
    // The line numbers are a short array of 2-tuples [start_pc, line_number].
    // Not necessarily sorted and not necessarily one-to-one.
    CompressedLineNumberReadStream stream(compressed_linenumber_table());
    while (stream.read_pair()) {
      if (stream.bci() == bci) {
        // perfect match
        return stream.line();
      } else {
        // update best_bci/line
        if (stream.bci() < bci && stream.bci() >= best_bci) {
          best_bci  = stream.bci();
          best_line = stream.line();
        }
      }
    }
  }
  return best_line;
}


628
bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
629
  if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
D
duke 已提交
630
    Thread *thread = Thread::current();
631
    Symbol* klass_name = constants()->klass_name_at(klass_index);
632
    Handle loader(thread, method_holder()->class_loader());
H
hseigel 已提交
633
    Handle prot  (thread, method_holder()->protection_domain());
D
duke 已提交
634 635 636 637 638 639 640
    return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
  } else {
    return true;
  }
}


641
bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
642
  int klass_index = constants()->klass_ref_index_at(refinfo_index);
D
duke 已提交
643 644 645 646 647 648 649 650
  if (must_be_resolved) {
    // Make sure klass is resolved in constantpool.
    if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
  }
  return is_klass_loaded_by_klass_index(klass_index);
}


651
void Method::set_native_function(address function, bool post_event_flag) {
D
duke 已提交
652
  assert(function != NULL, "use clear_native_function to unregister natives");
653
  assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
D
duke 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  address* native_function = native_function_addr();

  // We can see racers trying to place the same native function into place. Once
  // is plenty.
  address current = *native_function;
  if (current == function) return;
  if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
      function != NULL) {
    // native_method_throw_unsatisfied_link_error_entry() should only
    // be passed when post_event_flag is false.
    assert(function !=
      SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
      "post_event_flag mis-match");

    // post the bind event, and possible change the bind function
    JvmtiExport::post_native_method_bind(this, &function);
  }
  *native_function = function;
  // This function can be called more than once. We must make sure that we always
  // use the latest registered method -> check if a stub already has been generated.
  // If so, we have to make it not_entrant.
  nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
  if (nm != NULL) {
    nm->make_not_entrant();
  }
}


682
bool Method::has_native_function() const {
683 684
  if (is_method_handle_intrinsic())
    return false;  // special-cased in SharedRuntime::generate_native_wrapper
D
duke 已提交
685 686 687 688 689
  address func = native_function();
  return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
}


690
void Method::clear_native_function() {
691
  // Note: is_method_handle_intrinsic() is allowed here.
D
duke 已提交
692 693 694 695 696 697
  set_native_function(
    SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
    !native_bind_event_is_interesting);
  clear_code();
}

698
address Method::critical_native_function() {
699 700 701 702
  methodHandle mh(this);
  return NativeLookup::lookup_critical_entry(mh);
}

D
duke 已提交
703

704
void Method::set_signature_handler(address handler) {
D
duke 已提交
705 706 707 708 709
  address* signature_handler =  signature_handler_addr();
  *signature_handler = handler;
}


710
void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
711
  if (PrintCompilation && report) {
712
    ttyLocker ttyl;
713 714 715 716 717 718 719 720 721
    tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
    if (comp_level == CompLevel_all) {
      tty->print("all levels ");
    } else {
      tty->print("levels ");
      for (int i = (int)CompLevel_none; i <= comp_level; i++) {
        tty->print("%d ", i);
      }
    }
722 723
    this->print_short_name(tty);
    int size = this->code_size();
724
    if (size > 0) {
725
      tty->print(" (%d bytes)", size);
726 727 728 729
    }
    if (reason != NULL) {
      tty->print("   %s", reason);
    }
730 731
    tty->cr();
  }
D
duke 已提交
732 733
  if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
    ttyLocker ttyl;
V
vlivanov 已提交
734 735
    xtty->begin_elem("make_not_%scompilable thread='" UINTX_FORMAT "'",
                     is_osr ? "osr_" : "", os::current_thread_id());
736 737 738
    if (reason != NULL) {
      xtty->print(" reason=\'%s\'", reason);
    }
739
    xtty->method(this);
D
duke 已提交
740 741 742
    xtty->stamp();
    xtty->end_elem();
  }
743 744
}

745 746 747 748 749 750 751 752 753 754 755
bool Method::is_always_compilable() const {
  // Generated adapters must be compiled
  if (is_method_handle_intrinsic() && is_synthetic()) {
    assert(!is_not_c1_compilable(), "sanity check");
    assert(!is_not_c2_compilable(), "sanity check");
    return true;
  }

  return false;
}

756 757 758
bool Method::is_not_compilable(int comp_level) const {
  if (number_of_breakpoints() > 0)
    return true;
759 760
  if (is_always_compilable())
    return false;
761 762 763 764 765 766 767 768 769 770
  if (comp_level == CompLevel_any)
    return is_not_c1_compilable() || is_not_c2_compilable();
  if (is_c1_compile(comp_level))
    return is_not_c1_compilable();
  if (is_c2_compile(comp_level))
    return is_not_c2_compilable();
  return false;
}

// call this when compiler finds that this method is not compilable
771
void Method::set_not_compilable(int comp_level, bool report, const char* reason) {
772 773 774 775
  if (is_always_compilable()) {
    // Don't mark a method which should be always compilable
    return;
  }
776
  print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
I
iveresov 已提交
777 778 779 780
  if (comp_level == CompLevel_all) {
    set_not_c1_compilable();
    set_not_c2_compilable();
  } else {
781
    if (is_c1_compile(comp_level))
I
iveresov 已提交
782
      set_not_c1_compilable();
783 784 785 786
    if (is_c2_compile(comp_level))
      set_not_c2_compilable();
  }
  CompilationPolicy::policy()->disable_compilation(this);
787
  assert(!CompilationPolicy::can_be_compiled(this, comp_level), "sanity check");
788 789 790 791 792 793 794 795 796 797 798 799 800 801
}

bool Method::is_not_osr_compilable(int comp_level) const {
  if (is_not_compilable(comp_level))
    return true;
  if (comp_level == CompLevel_any)
    return is_not_c1_osr_compilable() || is_not_c2_osr_compilable();
  if (is_c1_compile(comp_level))
    return is_not_c1_osr_compilable();
  if (is_c2_compile(comp_level))
    return is_not_c2_osr_compilable();
  return false;
}

802 803
void Method::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
  print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
804 805 806 807 808 809 810 811
  if (comp_level == CompLevel_all) {
    set_not_c1_osr_compilable();
    set_not_c2_osr_compilable();
  } else {
    if (is_c1_compile(comp_level))
      set_not_c1_osr_compilable();
    if (is_c2_compile(comp_level))
      set_not_c2_osr_compilable();
D
duke 已提交
812
  }
I
iveresov 已提交
813
  CompilationPolicy::policy()->disable_compilation(this);
814
  assert(!CompilationPolicy::can_be_osr_compiled(this, comp_level), "sanity check");
D
duke 已提交
815 816 817
}

// Revert to using the interpreter and clear out the nmethod
818
void Method::clear_code() {
D
duke 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

  // this may be NULL if c2i adapters have not been made yet
  // Only should happen at allocate time.
  if (_adapter == NULL) {
    _from_compiled_entry    = NULL;
  } else {
    _from_compiled_entry    = _adapter->get_c2i_entry();
  }
  OrderAccess::storestore();
  _from_interpreted_entry = _i2i_entry;
  OrderAccess::storestore();
  _code = NULL;
}

// Called by class data sharing to remove any entry points (which are not shared)
834
void Method::unlink_method() {
D
duke 已提交
835 836 837 838 839 840 841 842 843 844
  _code = NULL;
  _i2i_entry = NULL;
  _from_interpreted_entry = NULL;
  if (is_native()) {
    *native_function_addr() = NULL;
    set_signature_handler(NULL);
  }
  NOT_PRODUCT(set_compiled_invocation_count(0);)
  _adapter = NULL;
  _from_compiled_entry = NULL;
845 846 847 848 849 850 851 852 853

  // In case of DumpSharedSpaces, _method_data should always be NULL.
  //
  // During runtime (!DumpSharedSpaces), when we are cleaning a
  // shared class that failed to load, this->link_method() may
  // have already been called (before an exception happened), so
  // this->_method_data may not be NULL.
  assert(!DumpSharedSpaces || _method_data == NULL, "unexpected method data?");

D
duke 已提交
854
  set_method_data(NULL);
855
  set_method_counters(NULL);
D
duke 已提交
856 857 858 859
}

// Called when the method_holder is getting linked. Setup entrypoints so the method
// is ready to be called from interpreter, compiler, and vtables.
860
void Method::link_method(methodHandle h_method, TRAPS) {
861 862 863 864
  // If the code cache is full, we may reenter this function for the
  // leftover methods that weren't linked.
  if (_i2i_entry != NULL) return;

D
duke 已提交
865 866 867 868 869 870 871 872 873
  assert(_adapter == NULL, "init'd to NULL" );
  assert( _code == NULL, "nothing compiled yet" );

  // Setup interpreter entrypoint
  assert(this == h_method(), "wrong h_method()" );
  address entry = Interpreter::entry_for_method(h_method);
  assert(entry != NULL, "interpreter entry must be non-null");
  // Sets both _i2i_entry and _from_interpreted_entry
  set_interpreter_entry(entry);
874 875 876

  // Don't overwrite already registered native entries.
  if (is_native() && !has_native_function()) {
D
duke 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889
    set_native_function(
      SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
      !native_bind_event_is_interesting);
  }

  // Setup compiler entrypoint.  This is made eagerly, so we do not need
  // special handling of vtables.  An alternative is to make adapters more
  // lazily by calling make_adapter() from from_compiled_entry() for the
  // normal calls.  For vtable calls life gets more complicated.  When a
  // call-site goes mega-morphic we need adapters in all methods which can be
  // called from the vtable.  We need adapters on such methods that get loaded
  // later.  Ditto for mega-morphic itable calls.  If this proves to be a
  // problem we'll make these lazily later.
890
  (void) make_adapters(h_method, CHECK);
D
duke 已提交
891 892 893 894 895

  // ONLY USE the h_method now as make_adapter may have blocked

}

896
address Method::make_adapters(methodHandle mh, TRAPS) {
D
duke 已提交
897 898 899 900 901
  // Adapters for compiled code are made eagerly here.  They are fairly
  // small (generally < 100 bytes) and quick to make (and cached and shared)
  // so making them eagerly shouldn't be too expensive.
  AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
  if (adapter == NULL ) {
902
    THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
D
duke 已提交
903 904 905 906 907 908 909
  }

  mh->set_adapter_entry(adapter);
  mh->_from_compiled_entry = adapter->get_c2i_entry();
  return adapter->get_c2i_entry();
}

910 911 912 913 914 915 916 917 918 919 920 921 922
void Method::restore_unshareable_info(TRAPS) {
  // Since restore_unshareable_info can be called more than once for a method, don't
  // redo any work.   If this field is restored, there is nothing to do.
  if (_from_compiled_entry == NULL) {
    // restore method's vtable by calling a virtual function
    restore_vtable();

    methodHandle mh(THREAD, this);
    link_method(mh, CHECK);
  }
}


D
duke 已提交
923 924 925 926 927 928 929
// The verified_code_entry() must be called when a invoke is resolved
// on this method.

// It returns the compiled code entry point, after asserting not null.
// This function is called after potential safepoints so that nmethod
// or adapter that it points to is still live and valid.
// This function must not hit a safepoint!
930
address Method::verified_code_entry() {
D
duke 已提交
931 932 933 934 935 936 937 938
  debug_only(No_Safepoint_Verifier nsv;)
  assert(_from_compiled_entry != NULL, "must be set");
  return _from_compiled_entry;
}

// Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
// (could be racing a deopt).
// Not inline to avoid circular ref.
939
bool Method::check_code() const {
D
duke 已提交
940 941
  // cached in a register or local.  There's a race on the value of the field.
  nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
942
  return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
D
duke 已提交
943 944 945
}

// Install compiled code.  Instantly it can execute.
946
void Method::set_code(methodHandle mh, nmethod *code) {
D
duke 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959
  assert( code, "use clear_code to remove code" );
  assert( mh->check_code(), "" );

  guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");

  // These writes must happen in this order, because the interpreter will
  // directly jump to from_interpreted_entry which jumps to an i2c adapter
  // which jumps to _from_compiled_entry.
  mh->_code = code;             // Assign before allowing compiled code to exec

  int comp_level = code->comp_level();
  // In theory there could be a race here. In practice it is unlikely
  // and not worth worrying about.
I
iveresov 已提交
960 961
  if (comp_level > mh->highest_comp_level()) {
    mh->set_highest_comp_level(comp_level);
D
duke 已提交
962 963 964
  }

  OrderAccess::storestore();
965
#ifdef SHARK
966
  mh->_from_interpreted_entry = code->insts_begin();
967
#else //!SHARK
D
duke 已提交
968 969 970
  mh->_from_compiled_entry = code->verified_entry_point();
  OrderAccess::storestore();
  // Instantly compiled code can execute.
971 972 973
  if (!mh->is_method_handle_intrinsic())
    mh->_from_interpreted_entry = mh->get_i2c_entry();
#endif //!SHARK
D
duke 已提交
974 975 976
}


977 978
bool Method::is_overridden_in(Klass* k) const {
  InstanceKlass* ik = InstanceKlass::cast(k);
D
duke 已提交
979 980 981 982 983

  if (ik->is_interface()) return false;

  // If method is an interface, we skip it - except if it
  // is a miranda method
984
  if (method_holder()->is_interface()) {
D
duke 已提交
985 986 987 988 989 990 991 992 993 994
    // Check that method is not a miranda method
    if (ik->lookup_method(name(), signature()) == NULL) {
      // No implementation exist - so miranda method
      return false;
    }
    return true;
  }

  assert(ik->is_subclass_of(method_holder()), "should be subklass");
  assert(ik->vtable() != NULL, "vtable should exist");
995
  if (!has_vtable_index()) {
D
duke 已提交
996 997
    return false;
  } else {
998 999
    Method* vt_m = ik->method_at_vtable(vtable_index());
    return vt_m != this;
D
duke 已提交
1000 1001 1002 1003
  }
}


1004 1005
// give advice about whether this Method* should be cached or not
bool Method::should_not_be_cached() const {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
  if (is_old()) {
    // This method has been redefined. It is either EMCP or obsolete
    // and we don't want to cache it because that would pin the method
    // down and prevent it from being collectible if and when it
    // finishes executing.
    return true;
  }

  // caching this method should be just fine
  return false;
}

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

/**
 *  Returns true if this is one of the specially treated methods for
 *  security related stack walks (like Reflection.getCallerClass).
 */
bool Method::is_ignored_by_security_stack_walk() const {
  const bool use_new_reflection = JDK_Version::is_gte_jdk14x_version() && UseNewReflection;

  if (intrinsic_id() == vmIntrinsics::_invoke) {
    // This is Method.invoke() -- ignore it
    return true;
  }
  if (use_new_reflection &&
      method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
    // This is an auxilary frame -- ignore it
    return true;
  }
  if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
    // This is an internal adapter frame for method handles -- ignore it
    return true;
  }
  return false;
}


1043 1044
// Constant pool structure for invoke methods:
enum {
1045
  _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1046
  _imcp_invoke_signature,       // utf8: (variable Symbol*)
1047 1048 1049
  _imcp_limit
};

1050 1051
// Test if this method is an MH adapter frame generated by Java code.
// Cf. java/lang/invoke/InvokerBytecodeGenerator
1052
bool Method::is_compiled_lambda_form() const {
1053 1054 1055 1056
  return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
}

// Test if this method is an internal MH primitive method.
1057
bool Method::is_method_handle_intrinsic() const {
1058 1059 1060 1061 1062
  vmIntrinsics::ID iid = intrinsic_id();
  return (MethodHandles::is_signature_polymorphic(iid) &&
          MethodHandles::is_signature_polymorphic_intrinsic(iid));
}

1063
bool Method::has_member_arg() const {
1064 1065 1066
  vmIntrinsics::ID iid = intrinsic_id();
  return (MethodHandles::is_signature_polymorphic(iid) &&
          MethodHandles::has_member_arg(iid));
1067 1068
}

1069
// Make an instance of a signature-polymorphic internal MH primitive.
1070
methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1071 1072
                                                         Symbol* signature,
                                                         TRAPS) {
1073
  ResourceMark rm;
1074 1075
  methodHandle empty;

1076 1077 1078
  KlassHandle holder = SystemDictionary::MethodHandle_klass();
  Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
  assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1079
  if (TraceMethodHandles) {
1080
    tty->print_cr("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1081 1082
  }

1083 1084 1085 1086
  // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
  name->increment_refcount();
  signature->increment_refcount();

1087
  int cp_length = _imcp_limit;
1088
  ClassLoaderData* loader_data = holder->class_loader_data();
1089 1090
  constantPoolHandle cp;
  {
1091
    ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1092 1093
    cp = constantPoolHandle(THREAD, cp_oop);
  }
1094
  cp->set_pool_holder(InstanceKlass::cast(holder()));
1095 1096
  cp->symbol_at_put(_imcp_invoke_name,       name);
  cp->symbol_at_put(_imcp_invoke_signature,  signature);
1097
  cp->set_has_preresolution();
1098

1099 1100 1101 1102 1103 1104
  // decide on access bits:  public or not?
  int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
  bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
  if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
  assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");

1105 1106
  methodHandle m;
  {
C
coleenp 已提交
1107
    InlineTableSizes sizes;
1108
    Method* m_oop = Method::allocate(loader_data, 0,
C
coleenp 已提交
1109
                                     accessFlags_from(flags_bits), &sizes,
1110
                                     ConstMethod::NORMAL, CHECK_(empty));
1111 1112 1113 1114 1115
    m = methodHandle(THREAD, m_oop);
  }
  m->set_constants(cp());
  m->set_name_index(_imcp_invoke_name);
  m->set_signature_index(_imcp_invoke_signature);
1116
  assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1117
  assert(m->signature() == signature, "");
1118
#ifdef CC_INTERP
1119
  ResultTypeFinder rtf(signature);
1120 1121 1122
  m->set_result_index(rtf.type());
#endif
  m->compute_size_of_parameters(THREAD);
1123
  m->init_intrinsic_id();
1124 1125 1126 1127 1128 1129
  assert(m->is_method_handle_intrinsic(), "");
#ifdef ASSERT
  if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
  assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
  assert(m->intrinsic_id() == iid, "correctly predicted iid");
#endif //ASSERT
1130 1131 1132

  // Finally, set up its entry points.
  assert(m->can_be_statically_bound(), "");
1133
  m->set_vtable_index(Method::nonvirtual_vtable_index);
1134 1135
  m->link_method(m, CHECK_(empty));

1136
  if (TraceMethodHandles && (Verbose || WizardMode))
1137 1138 1139 1140 1141
    m->print_on(tty);

  return m;
}

1142
Klass* Method::check_non_bcp_klass(Klass* klass) {
H
hseigel 已提交
1143 1144
  if (klass != NULL && klass->class_loader() != NULL) {
    if (klass->oop_is_objArray())
1145
      klass = ObjArrayKlass::cast(klass)->bottom_klass();
1146 1147 1148 1149
    return klass;
  }
  return NULL;
}
1150

1151

1152
methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
D
duke 已提交
1153 1154 1155
                                                u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
  // Code below does not work for native methods - they should never get rewritten anyway
  assert(!m->is_native(), "cannot rewrite native methods");
1156
  // Allocate new Method*
D
duke 已提交
1157
  AccessFlags flags = m->access_flags();
C
coleenp 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

  ConstMethod* cm = m->constMethod();
  int checked_exceptions_len = cm->checked_exceptions_length();
  int localvariable_len = cm->localvariable_table_length();
  int exception_table_len = cm->exception_table_length();
  int method_parameters_len = cm->method_parameters_length();
  int method_annotations_len = cm->method_annotations_length();
  int parameter_annotations_len = cm->parameter_annotations_length();
  int type_annotations_len = cm->type_annotations_length();
  int default_annotations_len = cm->default_annotations_length();

  InlineTableSizes sizes(
      localvariable_len,
      new_compressed_linenumber_size,
      exception_table_len,
      checked_exceptions_len,
      method_parameters_len,
      cm->generic_signature_index(),
      method_annotations_len,
      parameter_annotations_len,
      type_annotations_len,
      default_annotations_len,
      0);
1181

1182
  ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1183
  Method* newm_oop = Method::allocate(loader_data,
1184 1185
                                      new_code_length,
                                      flags,
C
coleenp 已提交
1186
                                      &sizes,
1187 1188
                                      m->method_type(),
                                      CHECK_(methodHandle()));
D
duke 已提交
1189 1190
  methodHandle newm (THREAD, newm_oop);
  int new_method_size = newm->method_size();
1191 1192 1193 1194 1195 1196 1197 1198 1199

  // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
  ConstMethod* newcm = newm->constMethod();
  int new_const_method_size = newm->constMethod()->size();

  memcpy(newm(), m(), sizeof(Method));

  // Create shallow copy of ConstMethod.
  memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1200

D
duke 已提交
1201 1202 1203 1204 1205 1206
  // Reset correct method/const method, method size, and parameter info
  newm->set_constMethod(newcm);
  newm->constMethod()->set_code_size(new_code_length);
  newm->constMethod()->set_constMethod_size(new_const_method_size);
  newm->set_method_size(new_method_size);
  assert(newm->code_size() == new_code_length, "check");
1207
  assert(newm->method_parameters_length() == method_parameters_len, "check");
D
duke 已提交
1208
  assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1209
  assert(newm->exception_table_length() == exception_table_len, "check");
D
duke 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218
  assert(newm->localvariable_table_length() == localvariable_len, "check");
  // Copy new byte codes
  memcpy(newm->code_base(), new_code, new_code_length);
  // Copy line number table
  if (new_compressed_linenumber_size > 0) {
    memcpy(newm->compressed_linenumber_table(),
           new_compressed_linenumber_table,
           new_compressed_linenumber_size);
  }
1219 1220 1221 1222 1223 1224
  // Copy method_parameters
  if (method_parameters_len > 0) {
    memcpy(newm->method_parameters_start(),
           m->method_parameters_start(),
           method_parameters_len * sizeof(MethodParametersElement));
  }
D
duke 已提交
1225 1226 1227 1228 1229 1230
  // Copy checked_exceptions
  if (checked_exceptions_len > 0) {
    memcpy(newm->checked_exceptions_start(),
           m->checked_exceptions_start(),
           checked_exceptions_len * sizeof(CheckedExceptionElement));
  }
1231 1232 1233 1234 1235 1236
  // Copy exception table
  if (exception_table_len > 0) {
    memcpy(newm->exception_table_start(),
           m->exception_table_start(),
           exception_table_len * sizeof(ExceptionTableElement));
  }
D
duke 已提交
1237 1238 1239 1240 1241 1242
  // Copy local variable number table
  if (localvariable_len > 0) {
    memcpy(newm->localvariable_table_start(),
           m->localvariable_table_start(),
           localvariable_len * sizeof(LocalVariableTableElement));
  }
1243 1244 1245 1246 1247 1248 1249 1250 1251
  // Copy stackmap table
  if (m->has_stackmap_table()) {
    int code_attribute_length = m->stackmap_data()->length();
    Array<u1>* stackmap_data =
      MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_NULL);
    memcpy((void*)stackmap_data->adr_at(0),
           (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
    newm->set_stackmap_data(stackmap_data);
  }
1252

1253 1254
  // copy annotations over to new method
  newcm->copy_annotations_from(cm);
D
duke 已提交
1255 1256 1257
  return newm;
}

1258
vmSymbols::SID Method::klass_id_for_intrinsics(Klass* holder) {
D
duke 已提交
1259 1260
  // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
  // because we are not loading from core libraries
1261 1262
  // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
  // which does not use the class default class loader so we check for its loader here
1263 1264
  InstanceKlass* ik = InstanceKlass::cast(holder);
  if ((ik->class_loader() != NULL) && !SystemDictionary::is_ext_class_loader(ik->class_loader())) {
1265
    return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1266
  }
D
duke 已提交
1267 1268

  // see if the klass name is well-known:
1269
  Symbol* klass_name = ik->name();
1270 1271 1272
  return vmSymbols::find_sid(klass_name);
}

1273
void Method::init_intrinsic_id() {
1274 1275 1276
  assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
  const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
  assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1277
  assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1278 1279 1280 1281

  // the klass name is well-known:
  vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
  assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
D
duke 已提交
1282 1283 1284

  // ditto for method and signature:
  vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1285 1286 1287
  if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
      && name_id == vmSymbols::NO_SID)
    return;
D
duke 已提交
1288
  vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1289
  if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1290
      && sig_id == vmSymbols::NO_SID)  return;
D
duke 已提交
1291 1292
  jshort flags = access_flags().as_short();

1293 1294 1295 1296 1297 1298
  vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
  if (id != vmIntrinsics::_none) {
    set_intrinsic_id(id);
    return;
  }

D
duke 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  // A few slightly irregular cases:
  switch (klass_id) {
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
    // Second chance: check in regular Math.
    switch (name_id) {
    case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
    case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
    case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
      // pretend it is the corresponding method in the non-strict class:
      klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1309
      id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
D
duke 已提交
1310 1311
      break;
    }
1312 1313 1314
    break;

  // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1315
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1316 1317 1318 1319
    if (!is_native())  break;
    id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
    if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
      id = vmIntrinsics::_none;
1320
    break;
D
duke 已提交
1321 1322
  }

1323 1324 1325 1326 1327
  if (id != vmIntrinsics::_none) {
    // Set up its iid.  It is an alias method.
    set_intrinsic_id(id);
    return;
  }
D
duke 已提交
1328 1329
}

1330 1331
// These two methods are static since a GC may move the Method
bool Method::load_signature_classes(methodHandle m, TRAPS) {
1332 1333 1334 1335 1336 1337
  if (THREAD->is_Compiler_thread()) {
    // There is nothing useful this routine can do from within the Compile thread.
    // Hopefully, the signature contains only well-known classes.
    // We could scan for this and return true/false, but the caller won't care.
    return false;
  }
D
duke 已提交
1338
  bool sig_is_loaded = true;
1339 1340
  Handle class_loader(THREAD, m->method_holder()->class_loader());
  Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1341 1342
  ResourceMark rm(THREAD);
  Symbol*  signature = m->signature();
D
duke 已提交
1343 1344
  for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
    if (ss.is_object()) {
1345 1346
      Symbol* sym = ss.as_symbol(CHECK_(false));
      Symbol*  name  = sym;
1347
      Klass* klass = SystemDictionary::resolve_or_null(name, class_loader,
D
duke 已提交
1348
                                             protection_domain, THREAD);
1349 1350
      // We are loading classes eagerly. If a ClassNotFoundException or
      // a LinkageError was generated, be sure to ignore it.
D
duke 已提交
1351
      if (HAS_PENDING_EXCEPTION) {
1352 1353
        if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
            PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
D
duke 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
          CLEAR_PENDING_EXCEPTION;
        } else {
          return false;
        }
      }
      if( klass == NULL) { sig_is_loaded = false; }
    }
  }
  return sig_is_loaded;
}

1365
bool Method::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1366 1367
  Handle class_loader(THREAD, m->method_holder()->class_loader());
  Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1368 1369
  ResourceMark rm(THREAD);
  Symbol*  signature = m->signature();
D
duke 已提交
1370 1371
  for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
    if (ss.type() == T_OBJECT) {
1372 1373
      Symbol* name = ss.as_symbol_or_null();
      if (name == NULL) return true;
1374
      Klass* klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
D
duke 已提交
1375 1376 1377 1378 1379 1380 1381
      if (klass == NULL) return true;
    }
  }
  return false;
}

// Exposed so field engineers can debug VM
1382
void Method::print_short_name(outputStream* st) {
D
duke 已提交
1383 1384
  ResourceMark rm;
#ifdef PRODUCT
1385
  st->print(" %s::", method_holder()->external_name());
D
duke 已提交
1386
#else
1387
  st->print(" %s::", method_holder()->internal_name());
D
duke 已提交
1388 1389 1390
#endif
  name()->print_symbol_on(st);
  if (WizardMode) signature()->print_symbol_on(st);
1391 1392
  else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
    MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
D
duke 已提交
1393 1394
}

1395
// Comparer for sorting an object array containing
1396 1397 1398
// Method*s.
static int method_comparator(Method* a, Method* b) {
  return a->name()->fast_compare(b->name());
1399
}
D
duke 已提交
1400 1401

// This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1402 1403
// default_methods also uses this without the ordering for fast find_method
void Method::sort_methods(Array<Method*>* methods, bool idempotent, bool set_idnums) {
D
duke 已提交
1404 1405
  int length = methods->length();
  if (length > 1) {
1406 1407
    {
      No_Safepoint_Verifier nsv;
1408
      QuickSort::sort<Method*>(methods->data(), length, method_comparator, idempotent);
D
duke 已提交
1409 1410
    }
    // Reset method ordering
1411 1412 1413 1414 1415
    if (set_idnums) {
      for (int i = 0; i < length; i++) {
        Method* m = methods->at(i);
        m->set_method_idnum(i);
      }
D
duke 已提交
1416 1417 1418 1419 1420
    }
  }
}

//-----------------------------------------------------------------------------------
1421
// Non-product code unless JVM/TI needs it
D
duke 已提交
1422

1423
#if !defined(PRODUCT) || INCLUDE_JVMTI
D
duke 已提交
1424 1425 1426 1427 1428 1429 1430
class SignatureTypePrinter : public SignatureTypeNames {
 private:
  outputStream* _st;
  bool _use_separator;

  void type_name(const char* name) {
    if (_use_separator) _st->print(", ");
1431
    _st->print("%s", name);
D
duke 已提交
1432 1433 1434 1435
    _use_separator = true;
  }

 public:
1436
  SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
D
duke 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445
    _st = st;
    _use_separator = false;
  }

  void print_parameters()              { _use_separator = false; iterate_parameters(); }
  void print_returntype()              { _use_separator = false; iterate_returntype(); }
};


1446
void Method::print_name(outputStream* st) {
D
duke 已提交
1447 1448 1449 1450 1451
  Thread *thread = Thread::current();
  ResourceMark rm(thread);
  SignatureTypePrinter sig(signature(), st);
  st->print("%s ", is_static() ? "static" : "virtual");
  sig.print_returntype();
1452
  st->print(" %s.", method_holder()->internal_name());
D
duke 已提交
1453 1454 1455 1456 1457
  name()->print_symbol_on(st);
  st->print("(");
  sig.print_parameters();
  st->print(")");
}
1458 1459
#endif // !PRODUCT || INCLUDE_JVMTI

D
duke 已提交
1460

1461 1462
//-----------------------------------------------------------------------------------
// Non-product code
D
duke 已提交
1463

1464
#ifndef PRODUCT
1465
void Method::print_codes_on(outputStream* st) const {
D
duke 已提交
1466 1467 1468
  print_codes_on(0, code_size(), st);
}

1469
void Method::print_codes_on(int from, int to, outputStream* st) const {
D
duke 已提交
1470 1471
  Thread *thread = Thread::current();
  ResourceMark rm(thread);
1472
  methodHandle mh (thread, (Method*)this);
D
duke 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
  BytecodeStream s(mh);
  s.set_interval(from, to);
  BytecodeTracer::set_closure(BytecodeTracer::std_closure());
  while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
}
#endif // not PRODUCT


// Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
// between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
// we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
// as end-of-stream terminator.

void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
  // bci and line number does not compress into single byte.
  // Write out escape character and use regular compression for bci and line number.
  write_byte((jubyte)0xFF);
  write_signed_int(bci_delta);
  write_signed_int(line_delta);
}

1494
// See comment in method.hpp which explains why this exists.
1495
#if defined(_M_AMD64) && _MSC_VER >= 1400
D
duke 已提交
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
#pragma optimize("", off)
void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
  write_pair_inline(bci, line);
}
#pragma optimize("", on)
#endif

CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
  _bci = 0;
  _line = 0;
};


bool CompressedLineNumberReadStream::read_pair() {
  jubyte next = read_byte();
  // Check for terminator
  if (next == 0) return false;
  if (next == 0xFF) {
    // Escape character, regular compression used
    _bci  += read_signed_int();
    _line += read_signed_int();
  } else {
    // Single byte compression used
    _bci  += next >> 3;
    _line += next & 0x7;
  }
  return true;
}


1526
Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1527
  BreakpointInfo* bp = method_holder()->breakpoints();
D
duke 已提交
1528 1529 1530 1531 1532
  for (; bp != NULL; bp = bp->next()) {
    if (bp->match(this, bci)) {
      return bp->orig_bytecode();
    }
  }
1533 1534 1535 1536
  {
    ResourceMark rm;
    fatal(err_msg("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci));
  }
D
duke 已提交
1537 1538 1539
  return Bytecodes::_shouldnotreachhere;
}

1540
void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
D
duke 已提交
1541
  assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1542
  BreakpointInfo* bp = method_holder()->breakpoints();
D
duke 已提交
1543 1544 1545 1546 1547 1548 1549 1550
  for (; bp != NULL; bp = bp->next()) {
    if (bp->match(this, bci)) {
      bp->set_orig_bytecode(code);
      // and continue, in case there is more than one
    }
  }
}

1551
void Method::set_breakpoint(int bci) {
1552
  InstanceKlass* ik = method_holder();
D
duke 已提交
1553 1554 1555 1556 1557 1558 1559
  BreakpointInfo *bp = new BreakpointInfo(this, bci);
  bp->set_next(ik->breakpoints());
  ik->set_breakpoints(bp);
  // do this last:
  bp->set(this);
}

1560
static void clear_matches(Method* m, int bci) {
1561
  InstanceKlass* ik = m->method_holder();
D
duke 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
  BreakpointInfo* prev_bp = NULL;
  BreakpointInfo* next_bp;
  for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
    next_bp = bp->next();
    // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
    if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
      // do this first:
      bp->clear(m);
      // unhook it
      if (prev_bp != NULL)
        prev_bp->set_next(next_bp);
      else
        ik->set_breakpoints(next_bp);
      delete bp;
      // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
      // at same location. So we have multiple matching (method_index and bci)
      // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
      // breakpoint for clear_breakpoint request and keep all other method versions
      // BreakpointInfo for future clear_breakpoint request.
      // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
      // which is being called when class is unloaded. We delete all the Breakpoint
      // information for all versions of method. We may not correctly restore the original
      // bytecode in all method versions, but that is ok. Because the class is being unloaded
      // so these methods won't be used anymore.
      if (bci >= 0) {
        break;
      }
    } else {
      // This one is a keeper.
      prev_bp = bp;
    }
  }
}

1596
void Method::clear_breakpoint(int bci) {
D
duke 已提交
1597 1598 1599 1600
  assert(bci >= 0, "");
  clear_matches(this, bci);
}

1601
void Method::clear_all_breakpoints() {
D
duke 已提交
1602 1603 1604 1605
  clear_matches(this, -1);
}


1606
int Method::invocation_count() {
1607
  MethodCounters *mcs = method_counters();
I
iveresov 已提交
1608
  if (TieredCompilation) {
1609
    MethodData* const mdo = method_data();
1610 1611
    if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
        ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
I
iveresov 已提交
1612 1613
      return InvocationCounter::count_limit;
    } else {
1614 1615
      return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
             ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
I
iveresov 已提交
1616 1617
    }
  } else {
1618
    return (mcs == NULL) ? 0 : mcs->invocation_counter()->count();
I
iveresov 已提交
1619 1620 1621
  }
}

1622
int Method::backedge_count() {
1623
  MethodCounters *mcs = method_counters();
I
iveresov 已提交
1624
  if (TieredCompilation) {
1625
    MethodData* const mdo = method_data();
1626 1627
    if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
        ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
I
iveresov 已提交
1628 1629
      return InvocationCounter::count_limit;
    } else {
1630 1631
      return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
             ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
I
iveresov 已提交
1632 1633
    }
  } else {
1634
    return (mcs == NULL) ? 0 : mcs->backedge_counter()->count();
I
iveresov 已提交
1635 1636 1637
  }
}

1638
int Method::highest_comp_level() const {
1639 1640 1641
  const MethodCounters* mcs = method_counters();
  if (mcs != NULL) {
    return mcs->highest_comp_level();
I
iveresov 已提交
1642 1643 1644 1645 1646
  } else {
    return CompLevel_none;
  }
}

1647
int Method::highest_osr_comp_level() const {
1648 1649 1650
  const MethodCounters* mcs = method_counters();
  if (mcs != NULL) {
    return mcs->highest_osr_comp_level();
I
iveresov 已提交
1651 1652 1653 1654 1655
  } else {
    return CompLevel_none;
  }
}

1656
void Method::set_highest_comp_level(int level) {
1657 1658 1659
  MethodCounters* mcs = method_counters();
  if (mcs != NULL) {
    mcs->set_highest_comp_level(level);
I
iveresov 已提交
1660 1661 1662
  }
}

1663
void Method::set_highest_osr_comp_level(int level) {
1664 1665 1666
  MethodCounters* mcs = method_counters();
  if (mcs != NULL) {
    mcs->set_highest_osr_comp_level(level);
I
iveresov 已提交
1667 1668 1669
  }
}

1670
BreakpointInfo::BreakpointInfo(Method* m, int bci) {
D
duke 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679
  _bci = bci;
  _name_index = m->name_index();
  _signature_index = m->signature_index();
  _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
  if (_orig_bytecode == Bytecodes::_breakpoint)
    _orig_bytecode = m->orig_bytecode_at(_bci);
  _next = NULL;
}

1680
void BreakpointInfo::set(Method* method) {
D
duke 已提交
1681 1682 1683 1684 1685 1686 1687 1688
#ifdef ASSERT
  {
    Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
    if (code == Bytecodes::_breakpoint)
      code = method->orig_bytecode_at(_bci);
    assert(orig_bytecode() == code, "original bytecode must be the same");
  }
#endif
1689
  Thread *thread = Thread::current();
D
duke 已提交
1690
  *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1691
  method->incr_number_of_breakpoints(thread);
D
duke 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700
  SystemDictionary::notice_modification();
  {
    // Deoptimize all dependents on this method
    HandleMark hm(thread);
    methodHandle mh(thread, method);
    Universe::flush_dependents_on_method(mh);
  }
}

1701
void BreakpointInfo::clear(Method* method) {
D
duke 已提交
1702 1703
  *method->bcp_from(_bci) = orig_bytecode();
  assert(method->number_of_breakpoints() > 0, "must not go negative");
1704
  method->decr_number_of_breakpoints(Thread::current());
D
duke 已提交
1705
}
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849

// jmethodID handling

// This is a block allocating object, sort of like JNIHandleBlock, only a
// lot simpler.  There aren't many of these, they aren't long, they are rarely
// deleted and so we can do some suboptimal things.
// It's allocated on the CHeap because once we allocate a jmethodID, we can
// never get rid of it.
// It would be nice to be able to parameterize the number of methods for
// the null_class_loader but then we'd have to turn this and ClassLoaderData
// into templates.

// I feel like this brain dead class should exist somewhere in the STL

class JNIMethodBlock : public CHeapObj<mtClass> {
  enum { number_of_methods = 8 };

  Method*         _methods[number_of_methods];
  int             _top;
  JNIMethodBlock* _next;
 public:
  static Method* const _free_method;

  JNIMethodBlock() : _next(NULL), _top(0) {
    for (int i = 0; i< number_of_methods; i++) _methods[i] = _free_method;
  }

  Method** add_method(Method* m) {
    if (_top < number_of_methods) {
      // top points to the next free entry.
      int i = _top;
      _methods[i] = m;
      _top++;
      return &_methods[i];
    } else if (_top == number_of_methods) {
      // if the next free entry ran off the block see if there's a free entry
      for (int i = 0; i< number_of_methods; i++) {
        if (_methods[i] == _free_method) {
          _methods[i] = m;
          return &_methods[i];
        }
      }
      // Only check each block once for frees.  They're very unlikely.
      // Increment top past the end of the block.
      _top++;
    }
    // need to allocate a next block.
    if (_next == NULL) {
      _next = new JNIMethodBlock();
    }
    return _next->add_method(m);
  }

  bool contains(Method** m) {
    for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
      for (int i = 0; i< number_of_methods; i++) {
        if (&(b->_methods[i]) == m) {
          return true;
        }
      }
    }
    return false;  // not found
  }

  // Doesn't really destroy it, just marks it as free so it can be reused.
  void destroy_method(Method** m) {
#ifdef ASSERT
    assert(contains(m), "should be a methodID");
#endif // ASSERT
    *m = _free_method;
  }

  // During class unloading the methods are cleared, which is different
  // than freed.
  void clear_all_methods() {
    for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
      for (int i = 0; i< number_of_methods; i++) {
        _methods[i] = NULL;
      }
    }
  }
#ifndef PRODUCT
  int count_methods() {
    // count all allocated methods
    int count = 0;
    for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
      for (int i = 0; i< number_of_methods; i++) {
        if (_methods[i] != _free_method) count++;
      }
    }
    return count;
  }
#endif // PRODUCT
};

// Something that can't be mistaken for an address or a markOop
Method* const JNIMethodBlock::_free_method = (Method*)55;

// Add a method id to the jmethod_ids
jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
  ClassLoaderData* cld = loader_data;

  if (!SafepointSynchronize::is_at_safepoint()) {
    // Have to add jmethod_ids() to class loader data thread-safely.
    // Also have to add the method to the list safely, which the cld lock
    // protects as well.
    MutexLockerEx ml(cld->metaspace_lock(),  Mutex::_no_safepoint_check_flag);
    if (cld->jmethod_ids() == NULL) {
      cld->set_jmethod_ids(new JNIMethodBlock());
    }
    // jmethodID is a pointer to Method*
    return (jmethodID)cld->jmethod_ids()->add_method(m);
  } else {
    // At safepoint, we are single threaded and can set this.
    if (cld->jmethod_ids() == NULL) {
      cld->set_jmethod_ids(new JNIMethodBlock());
    }
    // jmethodID is a pointer to Method*
    return (jmethodID)cld->jmethod_ids()->add_method(m);
  }
}

// Mark a jmethodID as free.  This is called when there is a data race in
// InstanceKlass while creating the jmethodID cache.
void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
  ClassLoaderData* cld = loader_data;
  Method** ptr = (Method**)m;
  assert(cld->jmethod_ids() != NULL, "should have method handles");
  cld->jmethod_ids()->destroy_method(ptr);
}

void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
  // Can't assert the method_holder is the same because the new method has the
  // scratch method holder.
  assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
           == new_method->method_holder()->class_loader(),
         "changing to a different class loader");
  // Just change the method in place, jmethodID pointer doesn't change.
  *((Method**)jmid) = new_method;
}

bool Method::is_method_id(jmethodID mid) {
  Method* m = resolve_jmethod_id(mid);
  assert(m != NULL, "should be called with non-null method");
1850
  InstanceKlass* ik = m->method_holder();
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
  ClassLoaderData* cld = ik->class_loader_data();
  if (cld->jmethod_ids() == NULL) return false;
  return (cld->jmethod_ids()->contains((Method**)mid));
}

Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
  if (mid == NULL) return NULL;
  Method* o = resolve_jmethod_id(mid);
  if (o == NULL || o == JNIMethodBlock::_free_method || !((Metadata*)o)->is_method()) {
    return NULL;
  }
  return o;
};

void Method::set_on_stack(const bool value) {
  // Set both the method itself and its constant pool.  The constant pool
  // on stack means some method referring to it is also on the stack.
  _access_flags.set_on_stack(value);
  constants()->set_on_stack(value);
  if (value) MetadataOnStackMark::record(this);
}

// Called when the class loader is unloaded to make all methods weak.
void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
  loader_data->jmethod_ids()->clear_all_methods();
}

1878 1879 1880 1881 1882 1883 1884 1885
bool Method::has_method_vptr(const void* ptr) {
  Method m;
  // This assumes that the vtbl pointer is the first word of a C++ object.
  // This assumption is also in universe.cpp patch_klass_vtble
  void* vtbl2 = dereference_vptr((const void*)&m);
  void* this_vtbl = dereference_vptr(ptr);
  return vtbl2 == this_vtbl;
}
1886 1887 1888 1889 1890 1891 1892 1893

// Check that this pointer is valid by checking that the vtbl pointer matches
bool Method::is_valid_method() const {
  if (this == NULL) {
    return false;
  } else if (!is_metaspace_object()) {
    return false;
  } else {
1894
    return has_method_vptr((const void*)this);
1895 1896 1897
  }
}

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
#ifndef PRODUCT
void Method::print_jmethod_ids(ClassLoaderData* loader_data, outputStream* out) {
  out->print_cr("jni_method_id count = %d", loader_data->jmethod_ids()->count_methods());
}
#endif // PRODUCT


// Printing

#ifndef PRODUCT

void Method::print_on(outputStream* st) const {
  ResourceMark rm;
  assert(is_method(), "must be method");
1912
  st->print_cr("%s", internal_name());
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
  // get the effect of PrintOopAddress, always, for methods:
  st->print_cr(" - this oop:          "INTPTR_FORMAT, (intptr_t)this);
  st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
  st->print   (" - constants:         "INTPTR_FORMAT" ", (address)constants());
  constants()->print_value_on(st); st->cr();
  st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
  st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
  st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
  st->print_cr(" - max stack:         %d",   max_stack());
  st->print_cr(" - max locals:        %d",   max_locals());
  st->print_cr(" - size of params:    %d",   size_of_parameters());
  st->print_cr(" - method size:       %d",   method_size());
  if (intrinsic_id() != vmIntrinsics::_none)
    st->print_cr(" - intrinsic id:      %d %s", intrinsic_id(), vmIntrinsics::name_at(intrinsic_id()));
  if (highest_comp_level() != CompLevel_none)
    st->print_cr(" - highest level:     %d", highest_comp_level());
  st->print_cr(" - vtable index:      %d",   _vtable_index);
  st->print_cr(" - i2i entry:         " INTPTR_FORMAT, interpreter_entry());
  st->print(   " - adapters:          ");
  AdapterHandlerEntry* a = ((Method*)this)->adapter();
  if (a == NULL)
    st->print_cr(INTPTR_FORMAT, a);
  else
    a->print_adapter_on(st);
  st->print_cr(" - compiled entry     " INTPTR_FORMAT, from_compiled_entry());
  st->print_cr(" - code size:         %d",   code_size());
  if (code_size() != 0) {
    st->print_cr(" - code start:        " INTPTR_FORMAT, code_base());
    st->print_cr(" - code end (excl):   " INTPTR_FORMAT, code_base() + code_size());
  }
  if (method_data() != NULL) {
    st->print_cr(" - method data:       " INTPTR_FORMAT, (address)method_data());
  }
  st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
  if (checked_exceptions_length() > 0) {
    CheckedExceptionElement* table = checked_exceptions_start();
    st->print_cr(" - checked ex start:  " INTPTR_FORMAT, table);
    if (Verbose) {
      for (int i = 0; i < checked_exceptions_length(); i++) {
        st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
      }
    }
  }
  if (has_linenumber_table()) {
    u_char* table = compressed_linenumber_table();
    st->print_cr(" - linenumber start:  " INTPTR_FORMAT, table);
    if (Verbose) {
      CompressedLineNumberReadStream stream(table);
      while (stream.read_pair()) {
        st->print_cr("   - line %d: %d", stream.line(), stream.bci());
      }
    }
  }
  st->print_cr(" - localvar length:   %d",   localvariable_table_length());
  if (localvariable_table_length() > 0) {
    LocalVariableTableElement* table = localvariable_table_start();
    st->print_cr(" - localvar start:    " INTPTR_FORMAT, table);
    if (Verbose) {
      for (int i = 0; i < localvariable_table_length(); i++) {
        int bci = table[i].start_bci;
        int len = table[i].length;
        const char* name = constants()->printable_name_at(table[i].name_cp_index);
        const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
        int slot = table[i].slot;
        st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
      }
    }
  }
  if (code() != NULL) {
    st->print   (" - compiled code: ");
    code()->print_value_on(st);
  }
  if (is_native()) {
    st->print_cr(" - native function:   " INTPTR_FORMAT, native_function());
    st->print_cr(" - signature handler: " INTPTR_FORMAT, signature_handler());
  }
}

#endif //PRODUCT

void Method::print_value_on(outputStream* st) const {
  assert(is_method(), "must be method");
1995
  st->print("%s", internal_name());
1996 1997 1998 1999 2000 2001 2002
  print_address_on(st);
  st->print(" ");
  name()->print_value_on(st);
  st->print(" ");
  signature()->print_value_on(st);
  st->print(" in ");
  method_holder()->print_value_on(st);
2003
  if (WizardMode) st->print("#%d", _vtable_index);
2004 2005 2006 2007
  if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
  if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
}

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
#if INCLUDE_SERVICES
// Size Statistics
void Method::collect_statistics(KlassSizeStats *sz) const {
  int mysize = sz->count(this);
  sz->_method_bytes += mysize;
  sz->_method_all_bytes += mysize;
  sz->_rw_bytes += mysize;

  if (constMethod()) {
    constMethod()->collect_statistics(sz);
  }
  if (method_data()) {
    method_data()->collect_statistics(sz);
  }
}
#endif // INCLUDE_SERVICES
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034

// Verification

void Method::verify_on(outputStream* st) {
  guarantee(is_method(), "object must be method");
  guarantee(constants()->is_constantPool(), "should be constant pool");
  guarantee(constMethod()->is_constMethod(), "should be ConstMethod*");
  MethodData* md = method_data();
  guarantee(md == NULL ||
      md->is_methodData(), "should be method data");
}