klassVtable.cpp 66.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2017, 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 26 27 28 29
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "gc_implementation/shared/markSweep.inline.hpp"
#include "memory/gcLocker.hpp"
J
jiangli 已提交
30
#include "memory/metaspaceShared.hpp"
31 32 33 34
#include "memory/resourceArea.hpp"
#include "memory/universe.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/klassVtable.hpp"
35
#include "oops/method.hpp"
36 37 38 39 40 41
#include "oops/objArrayOop.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvmtiRedefineClassesTrace.hpp"
#include "runtime/arguments.hpp"
#include "runtime/handles.inline.hpp"
#include "utilities/copy.hpp"
D
duke 已提交
42

43 44
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

45 46 47 48
inline InstanceKlass* klassVtable::ik() const {
  Klass* k = _klass();
  assert(k->oop_is_instance(), "not an InstanceKlass");
  return (InstanceKlass*)k;
D
duke 已提交
49 50
}

J
jiangli 已提交
51 52 53 54
bool klassVtable::is_preinitialized_vtable() {
  return _klass->is_shared() && !MetaspaceShared::remapped_readwrite();
}

D
duke 已提交
55 56

// this function computes the vtable size (including the size needed for miranda
57
// methods) and the number of miranda methods in this class.
D
duke 已提交
58
// Note on Miranda methods: Let's say there is a class C that implements
59 60 61 62
// interface I, and none of C's superclasses implements I.
// Let's say there is an abstract method m in I that neither C
// nor any of its super classes implement (i.e there is no method of any access,
// with the same name and signature as m), then m is a Miranda method which is
D
duke 已提交
63 64
// entered as a public abstract method in C's vtable.  From then on it should
// treated as any other public method in C for method over-ride purposes.
65 66 67 68 69 70
void klassVtable::compute_vtable_size_and_num_mirandas(
    int* vtable_length_ret, int* num_new_mirandas,
    GrowableArray<Method*>* all_mirandas, Klass* super,
    Array<Method*>* methods, AccessFlags class_flags,
    Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces,
    TRAPS) {
D
duke 已提交
71 72 73
  No_Safepoint_Verifier nsv;

  // set up default result values
74
  int vtable_length = 0;
D
duke 已提交
75 76

  // start off with super's vtable length
77
  InstanceKlass* sk = (InstanceKlass*)super;
D
duke 已提交
78 79 80 81 82
  vtable_length = super == NULL ? 0 : sk->vtable_length();

  // go thru each method in the methods table to see if it needs a new entry
  int len = methods->length();
  for (int i = 0; i < len; i++) {
83 84
    assert(methods->at(i)->is_method(), "must be a Method*");
    methodHandle mh(THREAD, methods->at(i));
D
duke 已提交
85

86
    if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
D
duke 已提交
87 88 89 90
      vtable_length += vtableEntry::size(); // we need a new entry
    }
  }

91
  GrowableArray<Method*> new_mirandas(20);
D
duke 已提交
92
  // compute the number of mirandas methods that must be added to the end
93
  get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces);
94 95
  *num_new_mirandas = new_mirandas.length();

96 97 98 99 100
  // Interfaces do not need interface methods in their vtables
  // This includes miranda methods and during later processing, default methods
  if (!class_flags.is_interface()) {
    vtable_length += *num_new_mirandas * vtableEntry::size();
  }
D
duke 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

  if (Universe::is_bootstrapping() && vtable_length == 0) {
    // array classes don't have their superclass set correctly during
    // bootstrapping
    vtable_length = Universe::base_vtable_size();
  }

  if (super == NULL && !Universe::is_bootstrapping() &&
      vtable_length != Universe::base_vtable_size()) {
    // Someone is attempting to redefine java.lang.Object incorrectly.  The
    // only way this should happen is from
    // SystemDictionary::resolve_from_stream(), which will detect this later
    // and throw a security exception.  So don't assert here to let
    // the exception occur.
    vtable_length = Universe::base_vtable_size();
  }
  assert(super != NULL || vtable_length == Universe::base_vtable_size(),
         "bad vtable size for class Object");
  assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
  assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
121 122

  *vtable_length_ret = vtable_length;
D
duke 已提交
123 124
}

125
int klassVtable::index_of(Method* m, int len) const {
126
  assert(m->has_vtable_index(), "do not ask this of non-vtable methods");
D
duke 已提交
127 128 129
  return m->vtable_index();
}

130 131 132
// Copy super class's vtable to the first part (prefix) of this class's vtable,
// and return the number of entries copied.  Expects that 'super' is the Java
// super class (arrays can have "array" super classes that must be skipped).
D
duke 已提交
133 134 135
int klassVtable::initialize_from_super(KlassHandle super) {
  if (super.is_null()) {
    return 0;
J
jiangli 已提交
136 137 138 139 140 141
  } else if (is_preinitialized_vtable()) {
    // A shared class' vtable is preinitialized at dump time. No need to copy
    // methods from super class for shared class, as that was already done
    // during archiving time. However, if Jvmti has redefined a class,
    // copy super class's vtable in case the super class has changed.
    return super->vtable()->length();
D
duke 已提交
142 143
  } else {
    // copy methods from superKlass
144
    // can't inherit from array class, so must be InstanceKlass
D
duke 已提交
145
    assert(super->oop_is_instance(), "must be instance klass");
146
    InstanceKlass* sk = (InstanceKlass*)super();
D
duke 已提交
147 148 149 150 151 152 153 154
    klassVtable* superVtable = sk->vtable();
    assert(superVtable->length() <= _length, "vtable too short");
#ifdef ASSERT
    superVtable->verify(tty, true);
#endif
    superVtable->copy_vtable_to(table());
#ifndef PRODUCT
    if (PrintVtables && Verbose) {
155
      ResourceMark rm;
D
duke 已提交
156 157 158 159 160 161 162
      tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
    }
#endif
    return superVtable->length();
  }
}

163 164
//
// Revised lookup semantics   introduced 1.3 (Kestrel beta)
D
duke 已提交
165 166 167 168 169 170
void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {

  // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
  KlassHandle super (THREAD, klass()->java_super());
  int nofNewEntries = 0;

J
jiangli 已提交
171 172
  bool is_shared = _klass->is_shared();

D
duke 已提交
173 174 175 176 177 178 179 180 181 182 183 184
  if (PrintVtables && !klass()->oop_is_array()) {
    ResourceMark rm(THREAD);
    tty->print_cr("Initializing: %s", _klass->name()->as_C_string());
  }

#ifdef ASSERT
  oop* end_of_obj = (oop*)_klass() + _klass()->size();
  oop* end_of_vtable = (oop*)&table()[_length];
  assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
#endif

  if (Universe::is_bootstrapping()) {
J
jiangli 已提交
185
    assert(!is_shared, "sanity");
D
duke 已提交
186 187 188 189 190 191 192 193 194
    // just clear everything
    for (int i = 0; i < _length; i++) table()[i].clear();
    return;
  }

  int super_vtable_len = initialize_from_super(super);
  if (klass()->oop_is_array()) {
    assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
  } else {
195
    assert(_klass->oop_is_instance(), "must be InstanceKlass");
D
duke 已提交
196

197 198
    Array<Method*>* methods = ik()->methods();
    int len = methods->length();
D
duke 已提交
199 200
    int initialized = super_vtable_len;

201 202
    // Check each of this class's methods against super;
    // if override, replace in copy of super vtable, otherwise append to end
D
duke 已提交
203
    for (int i = 0; i < len; i++) {
204
      // update_inherited_vtable can stop for gc - ensure using handles
D
duke 已提交
205
      HandleMark hm(THREAD);
206 207
      assert(methods->at(i)->is_method(), "must be a Method*");
      methodHandle mh(THREAD, methods->at(i));
D
duke 已提交
208

209
      bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK);
D
duke 已提交
210 211 212 213 214 215 216 217

      if (needs_new_entry) {
        put_method_at(mh(), initialized);
        mh()->set_vtable_index(initialized); // set primary vtable index
        initialized++;
      }
    }

218 219 220 221 222 223 224
    // update vtable with default_methods
    Array<Method*>* default_methods = ik()->default_methods();
    if (default_methods != NULL) {
      len = default_methods->length();
      if (len > 0) {
        Array<int>* def_vtable_indices = NULL;
        if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) {
J
jiangli 已提交
225
          assert(!is_shared, "shared class def_vtable_indices does not exist");
226 227 228 229 230 231 232 233 234 235 236 237 238 239
          def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK);
        } else {
          assert(def_vtable_indices->length() == len, "reinit vtable len?");
        }
        for (int i = 0; i < len; i++) {
          HandleMark hm(THREAD);
          assert(default_methods->at(i)->is_method(), "must be a Method*");
          methodHandle mh(THREAD, default_methods->at(i));

          bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK);

          // needs new entry
          if (needs_new_entry) {
            put_method_at(mh(), initialized);
J
jiangli 已提交
240 241 242 243 244 245 246 247 248
            if (is_preinitialized_vtable()) {
              // At runtime initialize_vtable is rerun for a shared class
              // (loaded by the non-boot loader) as part of link_class_impl().
              // The dumptime vtable index should be the same as the runtime index.
              assert(def_vtable_indices->at(i) == initialized,
                     "dump time vtable index is different from runtime index");
            } else {
              def_vtable_indices->at_put(i, initialized); //set vtable index
            }
249 250 251 252 253 254 255
            initialized++;
          }
        }
      }
    }

    // add miranda methods; it will also return the updated initialized
256 257 258 259 260
    // Interfaces do not need interface methods in their vtables
    // This includes miranda methods and during later processing, default methods
    if (!ik()->is_interface()) {
      initialized = fill_in_mirandas(initialized);
    }
D
duke 已提交
261

262
    // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
263
    // package_private -> public/protected), the vtable might actually be smaller than our initial
D
duke 已提交
264 265 266 267 268 269 270 271 272
    // calculation.
    assert(initialized <= _length, "vtable initialization failed");
    for(;initialized < _length; initialized++) {
      put_method_at(NULL, initialized);
    }
    NOT_PRODUCT(verify(tty, true));
  }
}

273 274 275 276
// Called for cases where a method does not override its superclass' vtable entry
// For bytecodes not produced by javac together it is possible that a method does not override
// the superclass's method, but might indirectly override a super-super class's vtable entry
// If none found, return a null superk, else return the superk of the method this does override
277 278 279 280 281 282 283 284 285 286 287
// For public and protected methods: if they override a superclass, they will
// also be overridden themselves appropriately.
// Private methods do not override and are not overridden.
// Package Private methods are trickier:
// e.g. P1.A, pub m
// P2.B extends A, package private m
// P1.C extends B, public m
// P1.C.m needs to override P1.A.m and can not override P2.B.m
// Therefore: all package private methods need their own vtable entries for
// them to be the root of an inheritance overriding decision
// Package private methods may also override other vtable entries
288
InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method,
289
                            int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
290
  InstanceKlass* superk = initialsuper;
291
  while (superk != NULL && superk->super() != NULL) {
M
mbalao 已提交
292
    klassVtable* ssVtable = (superk->super())->vtable();
293
    if (vtable_index < ssVtable->length()) {
294
      Method* super_method = ssVtable->method_at(vtable_index);
M
mbalao 已提交
295 296 297
      // get the class holding the matching method
      // make sure you use that class for is_override
      InstanceKlass* supermethodholder = super_method->method_holder();
298
#ifndef PRODUCT
299 300 301
      Symbol* name= target_method()->name();
      Symbol* signature = target_method()->signature();
      assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");
302
#endif
M
mbalao 已提交
303 304

      if (supermethodholder->is_override(super_method, target_loader, target_classname, THREAD)) {
305 306 307
#ifndef PRODUCT
        if (PrintVtables && Verbose) {
          ResourceMark rm(THREAD);
308
          char* sig = target_method()->name_and_sig_as_C_string();
309
          tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ",
M
mbalao 已提交
310
           supermethodholder->internal_name(),
311
           _klass->internal_name(), sig, vtable_index);
312
           super_method->access_flags().print_on(tty);
313
           if (super_method->is_default_method()) {
314
             tty->print("default ");
315
           }
316 317
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
318
           if (target_method->is_default_method()) {
319
             tty->print("default ");
320
           }
321 322 323 324 325 326
        }
#endif /*PRODUCT*/
        break; // return found superk
      }
    } else  {
      // super class has no vtable entry here, stop transitive search
327
      superk = (InstanceKlass*)NULL;
328 329 330
      break;
    }
    // if no override found yet, continue to search up
331
    superk = InstanceKlass::cast(superk->super());
332
  }
D
duke 已提交
333

334
  return superk;
D
duke 已提交
335 336 337
}

// Update child's copy of super vtable for overrides
338
// OR return true if a new vtable entry is required.
339
// Only called for InstanceKlass's, i.e. not for arrays
D
duke 已提交
340
// If that changed, could not use _klass as handle for klass
341 342 343
bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method,
                                          int super_vtable_len, int default_index,
                                          bool checkconstraints, TRAPS) {
D
duke 已提交
344 345
  ResourceMark rm;
  bool allocate_new = true;
346
  assert(klass->oop_is_instance(), "must be InstanceKlass");
D
duke 已提交
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  Array<int>* def_vtable_indices = NULL;
  bool is_default = false;
  // default methods are concrete methods in superinterfaces which are added to the vtable
  // with their real method_holder
  // Since vtable and itable indices share the same storage, don't touch
  // the default method's real vtable/itable index
  // default_vtable_indices stores the vtable value relative to this inheritor
  if (default_index >= 0 ) {
    is_default = true;
    def_vtable_indices = klass->default_vtable_indices();
    assert(def_vtable_indices != NULL, "def vtable alloc?");
    assert(default_index <= def_vtable_indices->length(), "def vtable len?");
  } else {
    assert(klass == target_method()->method_holder(), "caller resp.");
    // Initialize the method's vtable index to "nonvirtual".
    // If we allocate a vtable entry, we will update it to a non-negative number.
    target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
  }
D
duke 已提交
366 367 368 369 370 371

  // Static and <init> methods are never in
  if (target_method()->is_static() || target_method()->name() ==  vmSymbols::object_initializer_name()) {
    return false;
  }

372
  if (target_method->is_final_method(klass->access_flags())) {
D
duke 已提交
373 374 375 376
    // a final method never needs a new entry; final methods can be statically
    // resolved and they have to be present in the vtable only if they override
    // a super's method, in which case they re-use its entry
    allocate_new = false;
377 378 379 380 381
  } else if (klass->is_interface()) {
    allocate_new = false;  // see note below in needs_new_vtable_entry
    // An interface never allocates new vtable slots, only inherits old ones.
    // This method will either be assigned its own itable index later,
    // or be assigned an inherited vtable index in the loop below.
382 383 384 385 386 387 388 389 390
    // default methods inherited by classes store their vtable indices
    // in the inheritor's default_vtable_indices
    // default methods inherited by interfaces may already have a
    // valid itable index, if so, don't change it
    // overpass methods in an interface will be assigned an itable index later
    // by an inheriting class
    if (!is_default || !target_method()->has_itable_index()) {
      target_method()->set_vtable_index(Method::pending_itable_index);
    }
D
duke 已提交
391 392 393
  }

  // we need a new entry if there is no superclass
J
jiangli 已提交
394 395
  Klass* super = klass->super();
  if (super == NULL) {
D
duke 已提交
396 397 398
    return allocate_new;
  }

399
  // private methods in classes always have a new entry in the vtable
400 401
  // specification interpretation since classic has
  // private methods not overriding
402
  // JDK8 adds private methods in interfaces which require invokespecial
D
duke 已提交
403 404 405 406 407 408
  if (target_method()->is_private()) {
    return allocate_new;
  }

  // search through the vtable and update overridden entries
  // Since check_signature_loaders acquires SystemDictionary_lock
409 410
  // which can block for gc, once we are in this loop, use handles
  // For classfiles built with >= jdk7, we now look for transitive overrides
D
duke 已提交
411

412 413
  Symbol* name = target_method()->name();
  Symbol* signature = target_method()->signature();
414 415 416 417 418 419 420 421 422

  KlassHandle target_klass(THREAD, target_method()->method_holder());
  if (target_klass == NULL) {
    target_klass = _klass;
  }

  Handle target_loader(THREAD, target_klass->class_loader());

  Symbol* target_classname = target_klass->name();
D
duke 已提交
423
  for(int i = 0; i < super_vtable_len; i++) {
J
jiangli 已提交
424 425 426 427 428 429 430 431 432
    Method* super_method;
    if (is_preinitialized_vtable()) {
      // If this is a shared class, the vtable is already in the final state (fully
      // initialized). Need to look at the super's vtable.
      klassVtable* superVtable = super->vtable();
      super_method = superVtable->method_at(i);
    } else {
      super_method = method_at(i);
    }
D
duke 已提交
433
    // Check if method name matches
434
    if (super_method->name() == name && super_method->signature() == signature) {
D
duke 已提交
435

436
      // get super_klass for method_holder for the found method
437
      InstanceKlass* super_klass =  super_method->method_holder();
D
duke 已提交
438

A
acorn 已提交
439 440 441
      // private methods are also never overridden
      if (!super_method->is_private() &&
          (is_default
442 443 444 445 446
          || ((super_klass->is_override(super_method, target_loader, target_classname, THREAD))
          || ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
          && ((super_klass = find_transitive_override(super_klass,
                             target_method, i, target_loader,
                             target_classname, THREAD))
A
acorn 已提交
447
                             != (InstanceKlass*)NULL)))))
448
        {
449 450 451 452 453
        // Package private methods always need a new entry to root their own
        // overriding. They may also override other methods.
        if (!target_method()->is_package_private()) {
          allocate_new = false;
        }
D
duke 已提交
454 455 456 457 458 459 460 461 462 463

        if (checkconstraints) {
        // Override vtable entry if passes loader constraint check
        // if loader constraint checking requested
        // No need to visit his super, since he and his super
        // have already made any needed loader constraints.
        // Since loader constraints are transitive, it is enough
        // to link to the first super, and we get all the others.
          Handle super_loader(THREAD, super_klass->class_loader());

464
          if (target_loader() != super_loader()) {
D
duke 已提交
465
            ResourceMark rm(THREAD);
466
            Symbol* failed_type_symbol =
467
              SystemDictionary::check_signature_loaders(signature, target_loader,
D
duke 已提交
468 469
                                                        super_loader, true,
                                                        CHECK_(false));
470
            if (failed_type_symbol != NULL) {
D
duke 已提交
471 472 473 474 475 476
              const char* msg = "loader constraint violation: when resolving "
                "overridden method \"%s\" the class loader (instance"
                " of %s) of the current class, %s, and its superclass loader "
                "(instance of %s), have different Class objects for the type "
                "%s used in the signature";
              char* sig = target_method()->name_and_sig_as_C_string();
477
              const char* loader1 = SystemDictionary::loader_name(target_loader());
478
              char* current = target_klass->name()->as_C_string();
D
duke 已提交
479
              const char* loader2 = SystemDictionary::loader_name(super_loader());
480
              char* failed_type_name = failed_type_symbol->as_C_string();
D
duke 已提交
481 482 483 484 485 486 487 488
              size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
                strlen(current) + strlen(loader2) + strlen(failed_type_name);
              char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
              jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
                           failed_type_name);
              THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
            }
          }
489
       }
D
duke 已提交
490

491 492 493 494 495
       put_method_at(target_method(), i);
       if (!is_default) {
         target_method()->set_vtable_index(i);
       } else {
         if (def_vtable_indices != NULL) {
J
jiangli 已提交
496 497 498 499 500 501 502 503 504
           if (is_preinitialized_vtable()) {
             // At runtime initialize_vtable is rerun as part of link_class_impl()
             // for a shared class loaded by the non-boot loader.
             // The dumptime vtable index should be the same as the runtime index.
             assert(def_vtable_indices->at(default_index) == i,
                    "dump time vtable index is different from runtime index");
           } else {
             def_vtable_indices->at_put(default_index, i);
           }
505 506 507 508 509 510
         }
         assert(super_method->is_default_method() || super_method->is_overpass()
                || super_method->is_abstract(), "default override error");
       }


D
duke 已提交
511
#ifndef PRODUCT
512
        if (PrintVtables && Verbose) {
513 514
          ResourceMark rm(THREAD);
          char* sig = target_method()->name_and_sig_as_C_string();
515
          tty->print("overriding with %s::%s index %d, original flags: ",
516
           target_klass->internal_name(), sig, i);
517
           super_method->access_flags().print_on(tty);
518
           if (super_method->is_default_method()) {
519
             tty->print("default ");
520 521 522 523
           }
           if (super_method->is_overpass()) {
             tty->print("overpass");
           }
524 525
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
526
           if (target_method->is_default_method()) {
527
             tty->print("default ");
528 529 530 531
           }
           if (target_method->is_overpass()) {
             tty->print("overpass");
           }
532 533
           tty->cr();
        }
D
duke 已提交
534
#endif /*PRODUCT*/
535 536 537
      } else {
        // allocate_new = true; default. We might override one entry,
        // but not override another. Once we override one, not need new
D
duke 已提交
538
#ifndef PRODUCT
539
        if (PrintVtables && Verbose) {
540 541
          ResourceMark rm(THREAD);
          char* sig = target_method()->name_and_sig_as_C_string();
542
          tty->print("NOT overriding with %s::%s index %d, original flags: ",
543
           target_klass->internal_name(), sig,i);
544
           super_method->access_flags().print_on(tty);
545
           if (super_method->is_default_method()) {
546
             tty->print("default ");
547 548 549 550
           }
           if (super_method->is_overpass()) {
             tty->print("overpass");
           }
551 552
           tty->print("overriders flags: ");
           target_method->access_flags().print_on(tty);
553
           if (target_method->is_default_method()) {
554
             tty->print("default ");
555 556 557 558
           }
           if (target_method->is_overpass()) {
             tty->print("overpass");
           }
559
           tty->cr();
D
duke 已提交
560
        }
561
#endif /*PRODUCT*/
D
duke 已提交
562 563 564 565 566 567
      }
    }
  }
  return allocate_new;
}

568
void klassVtable::put_method_at(Method* m, int index) {
J
jiangli 已提交
569 570 571 572 573 574 575 576
  if (is_preinitialized_vtable()) {
    // At runtime initialize_vtable is rerun as part of link_class_impl()
    // for shared class loaded by the non-boot loader to obtain the loader
    // constraints based on the runtime classloaders' context. The dumptime
    // method at the vtable index should be the same as the runtime method.
    assert(table()[index].method() == m,
           "archived method is different from the runtime method");
  } else {
D
duke 已提交
577
#ifndef PRODUCT
J
jiangli 已提交
578 579 580 581 582 583 584 585 586 587 588 589
    if (PrintVtables && Verbose) {
      ResourceMark rm;
      const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";
      tty->print("adding %s at index %d, flags: ", sig, index);
      if (m != NULL) {
        m->access_flags().print_on(tty);
        if (m->is_default_method()) {
          tty->print("default ");
        }
        if (m->is_overpass()) {
          tty->print("overpass");
        }
590
      }
J
jiangli 已提交
591
      tty->cr();
592
    }
D
duke 已提交
593
#endif
J
jiangli 已提交
594 595
    table()[index].set(m);
  }
D
duke 已提交
596 597 598 599 600 601 602
}

// Find out if a method "m" with superclass "super", loader "classloader" and
// name "classname" needs a new vtable entry.  Let P be a class package defined
// by "classloader" and "classname".
// NOTE: The logic used here is very similar to the one used for computing
// the vtables indices for a method. We cannot directly use that function because,
603
// we allocate the InstanceKlass at load time, and that requires that the
604 605 606 607
// superclass has been loaded.
// However, the vtable entries are filled in at link time, and therefore
// the superclass' vtable may not yet have been filled in.
bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
608
                                         Klass* super,
609
                                         Handle classloader,
610
                                         Symbol* classname,
611 612
                                         AccessFlags class_flags,
                                         TRAPS) {
613
  if (class_flags.is_interface()) {
614 615 616
    // Interfaces do not use vtables, except for java.lang.Object methods,
    // so there is no point to assigning
    // a vtable index to any of their local methods.  If we refrain from doing this,
617 618 619
    // we can use Method::_vtable_index to hold the itable index
    return false;
  }
620

621
  if (target_method->is_final_method(class_flags) ||
D
duke 已提交
622 623 624
      // a final method never needs a new entry; final methods can be statically
      // resolved and they have to be present in the vtable only if they override
      // a super's method, in which case they re-use its entry
625
      (target_method()->is_static()) ||
D
duke 已提交
626
      // static methods don't need to be in vtable
627
      (target_method()->name() ==  vmSymbols::object_initializer_name())
D
duke 已提交
628 629 630 631 632
      // <init> is never called dynamically-bound
      ) {
    return false;
  }

633 634 635 636 637 638 639 640
  // Concrete interface methods do not need new entries, they override
  // abstract method entries using default inheritance rules
  if (target_method()->method_holder() != NULL &&
      target_method()->method_holder()->is_interface()  &&
      !target_method()->is_abstract() ) {
    return false;
  }

D
duke 已提交
641 642 643 644 645
  // we need a new entry if there is no superclass
  if (super == NULL) {
    return true;
  }

646
  // private methods in classes always have a new entry in the vtable
647 648
  // specification interpretation since classic has
  // private methods not overriding
649
  // JDK8 adds private  methods in interfaces which require invokespecial
650
  if (target_method()->is_private()) {
D
duke 已提交
651 652 653
    return true;
  }

654 655 656 657 658 659
  // Package private methods always need a new entry to root their own
  // overriding. This allows transitive overriding to work.
  if (target_method()->is_package_private()) {
    return true;
  }

D
duke 已提交
660 661
  // search through the super class hierarchy to see if we need
  // a new entry
M
mbalao 已提交
662
  ResourceMark rm(THREAD);
663 664
  Symbol* name = target_method()->name();
  Symbol* signature = target_method()->signature();
665 666 667 668
  Klass* k = super;
  Method* super_method = NULL;
  InstanceKlass *holder = NULL;
  Method* recheck_method =  NULL;
669
  bool found_pkg_prvt_method = false;
D
duke 已提交
670 671
  while (k != NULL) {
    // lookup through the hierarchy for a method with matching name and sign.
672
    super_method = InstanceKlass::cast(k)->lookup_method(name, signature);
673
    if (super_method == NULL) {
D
duke 已提交
674 675 676
      break; // we still have to search for a matching miranda method
    }
    // get the class holding the matching method
677
    // make sure you use that class for is_override
678
    InstanceKlass* superk = super_method->method_holder();
679 680 681 682 683 684 685 686 687
    // we want only instance method matches
    // pretend private methods are not in the super vtable
    // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
    // ignore private, c.m pub does override a.m pub
    // For classes that were not javac'd together, we also do transitive overriding around
    // methods that have less accessibility
    if ((!super_method->is_static()) &&
       (!super_method->is_private())) {
      if (superk->is_override(super_method, classloader, classname, THREAD)) {
D
duke 已提交
688
        return false;
689
      // else keep looking for transitive overrides
D
duke 已提交
690
      }
691 692 693 694 695 696 697 698 699 700
      // If we get here then one of the super classes has a package private method
      // that will not get overridden because it is in a different package.  But,
      // that package private method does "override" any matching methods in super
      // interfaces, so there will be no miranda vtable entry created.  So, set flag
      // to TRUE for use below, in case there are no methods in super classes that
      // this target method overrides.
      assert(super_method->is_package_private(), "super_method must be package private");
      assert(!superk->is_same_class_package(classloader(), classname),
             "Must be different packages");
      found_pkg_prvt_method = true;
D
duke 已提交
701 702
    }

703 704
    // Start with lookup result and continue to search up
    k = superk->super(); // haven't found an override match yet; continue to look
D
duke 已提交
705 706
  }

707 708 709 710 711 712 713 714 715
  // If found_pkg_prvt_method is set, then the ONLY matching method in the
  // superclasses is package private in another package. That matching method will
  // prevent a miranda vtable entry from being created. Because the target method can not
  // override the package private method in another package, then it needs to be the root
  // for its own vtable entry.
  if (found_pkg_prvt_method) {
     return true;
  }

D
duke 已提交
716 717
  // if the target method is public or protected it may have a matching
  // miranda method in the super, whose entry it should re-use.
718 719
  // Actually, to handle cases that javac would not generate, we need
  // this check for all access permissions.
720
  InstanceKlass *sk = InstanceKlass::cast(super);
721
  if (sk->has_miranda_methods()) {
722
    if (sk->lookup_method_in_all_interfaces(name, signature, Klass::find_defaults) != NULL) {
723
      return false; // found a matching miranda; we do not need a new entry
D
duke 已提交
724 725 726 727 728 729 730 731
    }
  }
  return true; // found no match; we need a new entry
}

// Support for miranda methods

// get the vtable index of a miranda method with matching "name" and "signature"
732
int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {
D
duke 已提交
733 734
  // search from the bottom, might be faster
  for (int i = (length() - 1); i >= 0; i--) {
735
    Method* m = table()[i].method();
D
duke 已提交
736 737 738 739 740
    if (is_miranda_entry_at(i) &&
        m->name() == name && m->signature() == signature) {
      return i;
    }
  }
741
  return Method::invalid_vtable_index;
D
duke 已提交
742 743
}

744 745
// check if an entry at an index is miranda
// requires that method m at entry be declared ("held") by an interface.
D
duke 已提交
746
bool klassVtable::is_miranda_entry_at(int i) {
747 748 749
  Method* m = method_at(i);
  Klass* method_holder = m->method_holder();
  InstanceKlass *mhk = InstanceKlass::cast(method_holder);
D
duke 已提交
750

751
  // miranda methods are public abstract instance interface methods in a class's vtable
D
duke 已提交
752
  if (mhk->is_interface()) {
753
    assert(m->is_public(), "should be public");
D
duke 已提交
754
    assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
755 756 757
    if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super())) {
      return true;
    }
D
duke 已提交
758 759 760 761
  }
  return false;
}

762 763 764 765 766 767 768 769 770 771 772 773 774 775
// Check if a method is a miranda method, given a class's methods array,
// its default_method table and its super class.
// "Miranda" means an abstract non-private method that would not be
// overridden for the local class.
// A "miranda" method should only include non-private interface
// instance methods, i.e. not private methods, not static methods,
// not default methods (concrete interface methods), not overpass methods.
// If a given class already has a local (including overpass) method, a
// default method, or any of its superclasses has the same which would have
// overridden an abstract method, then this is not a miranda method.
//
// Miranda methods are checked multiple times.
// Pass 1: during class load/class file parsing: before vtable size calculation:
// include superinterface abstract and default methods (non-private instance).
A
acorn 已提交
776
// We include potential default methods to give them space in the vtable.
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
// During the first run, the current instanceKlass has not yet been
// created, the superclasses and superinterfaces do have instanceKlasses
// but may not have vtables, the default_methods list is empty, no overpasses.
// This is seen by default method creation.
//
// Pass 2: recalculated during vtable initialization: only include abstract methods.
// The goal of pass 2 is to walk through the superinterfaces to see if any of
// the superinterface methods (which were all abstract pre-default methods)
// need to be added to the vtable.
// With the addition of default methods, we have three new challenges:
// overpasses, static interface methods and private interface methods.
// Static and private interface methods do not get added to the vtable and
// are not seen by the method resolution process, so we skip those.
// Overpass methods are already in the vtable, so vtable lookup will
// find them and we don't need to add a miranda method to the end of
// the vtable. So we look for overpass methods and if they are found we
// return false. Note that we inherit our superclasses vtable, so
// the superclass' search also needs to use find_overpass so that if
// one is found we return false.
// False means - we don't need a miranda method added to the vtable.
//
A
acorn 已提交
798 799 800
// During the second run, default_methods is set up, so concrete methods from
// superinterfaces with matching names/signatures to default_methods are already
// in the default_methods list and do not need to be appended to the vtable
801 802 803 804 805 806 807 808 809 810 811 812
// as mirandas. Abstract methods may already have been handled via
// overpasses - either local or superclass overpasses, which may be
// in the vtable already.
//
// Pass 3: They are also checked by link resolution and selection,
// for invocation on a method (not interface method) reference that
// resolves to a method with an interface as its method_holder.
// Used as part of walking from the bottom of the vtable to find
// the vtable index for the miranda method.
//
// Part of the Miranda Rights in the US mean that if you do not have
// an attorney one will be appointed for you.
813 814
bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,
                             Array<Method*>* default_methods, Klass* super) {
815
  if (m->is_static() || m->is_private() || m->is_overpass()) {
816 817
    return false;
  }
818 819
  Symbol* name = m->name();
  Symbol* signature = m->signature();
820

821 822 823 824 825
  // First look in local methods to see if already covered
  if (InstanceKlass::find_local_method(class_methods, name, signature,
              Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL)
  {
    return false;
D
duke 已提交
826
  }
827

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  // Check local default methods
  if ((default_methods != NULL) &&
    (InstanceKlass::find_method(default_methods, name, signature) != NULL))
   {
     return false;
   }

  InstanceKlass* cursuper;
  // Iterate on all superclasses, which should have instanceKlasses
  // Note that we explicitly look for overpasses at each level.
  // Overpasses may or may not exist for supers for pass 1,
  // they should have been created for pass 2 and later.

  for (cursuper = InstanceKlass::cast(super); cursuper != NULL;  cursuper = (InstanceKlass*)cursuper->super())
  {
     if (cursuper->find_local_method(name, signature,
           Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL) {
       return false;
     }
  }

  return true;
D
duke 已提交
850 851
}

852
// Scans current_interface_methods for miranda methods that do not
853
// already appear in new_mirandas, or default methods,  and are also not defined-and-non-private
854 855 856 857 858 859
// in super (superclass).  These mirandas are added to all_mirandas if it is
// not null; in addition, those that are not duplicates of miranda methods
// inherited by super from its interfaces are added to new_mirandas.
// Thus, new_mirandas will be the set of mirandas that this class introduces,
// all_mirandas will be the set of all mirandas applicable to this class
// including all defined in superclasses.
860 861 862
void klassVtable::add_new_mirandas_to_lists(
    GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,
    Array<Method*>* current_interface_methods, Array<Method*>* class_methods,
863 864
    Array<Method*>* default_methods, Klass* super) {

D
duke 已提交
865 866 867
  // iterate thru the current interface's method to see if it a miranda
  int num_methods = current_interface_methods->length();
  for (int i = 0; i < num_methods; i++) {
868
    Method* im = current_interface_methods->at(i);
D
duke 已提交
869
    bool is_duplicate = false;
870
    int num_of_current_mirandas = new_mirandas->length();
D
duke 已提交
871 872
    // check for duplicate mirandas in different interfaces we implement
    for (int j = 0; j < num_of_current_mirandas; j++) {
873
      Method* miranda = new_mirandas->at(j);
D
duke 已提交
874 875 876 877 878 879 880 881
      if ((im->name() == miranda->name()) &&
          (im->signature() == miranda->signature())) {
        is_duplicate = true;
        break;
      }
    }

    if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
882
      if (is_miranda(im, class_methods, default_methods, super)) { // is it a miranda at all?
883
        InstanceKlass *sk = InstanceKlass::cast(super);
D
duke 已提交
884
        // check if it is a duplicate of a super's miranda
885
        if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::find_defaults) == NULL) {
886 887 888 889
          new_mirandas->append(im);
        }
        if (all_mirandas != NULL) {
          all_mirandas->append(im);
D
duke 已提交
890 891 892 893 894 895
        }
      }
    }
  }
}

896 897
void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,
                               GrowableArray<Method*>* all_mirandas,
898
                               Klass* super, Array<Method*>* class_methods,
899
                               Array<Method*>* default_methods,
900
                               Array<Klass*>* local_interfaces) {
901
  assert((new_mirandas->length() == 0) , "current mirandas must be 0");
D
duke 已提交
902 903 904 905

  // iterate thru the local interfaces looking for a miranda
  int num_local_ifs = local_interfaces->length();
  for (int i = 0; i < num_local_ifs; i++) {
906
    InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i));
907
    add_new_mirandas_to_lists(new_mirandas, all_mirandas,
908 909
                              ik->methods(), class_methods,
                              default_methods, super);
D
duke 已提交
910
    // iterate thru each local's super interfaces
911
    Array<Klass*>* super_ifs = ik->transitive_interfaces();
D
duke 已提交
912 913
    int num_super_ifs = super_ifs->length();
    for (int j = 0; j < num_super_ifs; j++) {
914
      InstanceKlass *sik = InstanceKlass::cast(super_ifs->at(j));
915
      add_new_mirandas_to_lists(new_mirandas, all_mirandas,
916 917
                                sik->methods(), class_methods,
                                default_methods, super);
D
duke 已提交
918 919 920 921
    }
  }
}

922 923 924
// Discover miranda methods ("miranda" = "interface abstract, no binding"),
// and append them into the vtable starting at index initialized,
// return the new value of initialized.
925 926
// Miranda methods use vtable entries, but do not get assigned a vtable_index
// The vtable_index is discovered by searching from the end of the vtable
927
int klassVtable::fill_in_mirandas(int initialized) {
928 929
  GrowableArray<Method*> mirandas(20);
  get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),
930
               ik()->default_methods(), ik()->local_interfaces());
931
  for (int i = 0; i < mirandas.length(); i++) {
932 933 934 935 936 937 938 939 940
    if (PrintVtables && Verbose) {
      Method* meth = mirandas.at(i);
      ResourceMark rm(Thread::current());
      if (meth != NULL) {
        char* sig = meth->name_and_sig_as_C_string();
        tty->print("fill in mirandas with %s index %d, flags: ",
          sig, initialized);
        meth->access_flags().print_on(tty);
        if (meth->is_default_method()) {
941
          tty->print("default ");
942 943 944 945
        }
        tty->cr();
      }
    }
946 947
    put_method_at(mirandas.at(i), initialized);
    ++initialized;
D
duke 已提交
948
  }
949
  return initialized;
D
duke 已提交
950 951
}

952 953
// Copy this class's vtable to the vtable beginning at start.
// Used to copy superclass vtable to prefix of subclass's vtable.
D
duke 已提交
954 955 956 957
void klassVtable::copy_vtable_to(vtableEntry* start) {
  Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
}

958
#if INCLUDE_JVMTI
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) {
  // If old_method is default, find this vtable index in default_vtable_indices
  // and replace that method in the _default_methods list
  bool updated = false;

  Array<Method*>* default_methods = ik()->default_methods();
  if (default_methods != NULL) {
    int len = default_methods->length();
    for (int idx = 0; idx < len; idx++) {
      if (vtable_index == ik()->default_vtable_indices()->at(idx)) {
        if (default_methods->at(idx) == old_method) {
          default_methods->at_put(idx, new_method);
          updated = true;
        }
        break;
      }
    }
  }
  return updated;
}
D
duke 已提交
979

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
// search the vtable for uses of either obsolete or EMCP methods
void klassVtable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {
  int prn_enabled = 0;
  for (int index = 0; index < length(); index++) {
    Method* old_method = unchecked_method_at(index);
    if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
      continue; // skip uninteresting entries
    }
    assert(!old_method->is_deleted(), "vtable methods may not be deleted");

    Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());

    assert(new_method != NULL, "method_with_idnum() should not be NULL");
    assert(old_method != new_method, "sanity check");

    put_method_at(new_method, index);
    // For default methods, need to update the _default_methods array
    // which can only have one method entry for a given signature
    bool updated_default = false;
    if (old_method->is_default_method()) {
      updated_default = adjust_default_method(index, old_method, new_method);
    }

    if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
      if (!(*trace_name_printed)) {
        // RC_TRACE_MESG macro has an embedded ResourceMark
        RC_TRACE_MESG(("adjust: klassname=%s for methods from name=%s",
                       klass()->external_name(),
                       old_method->method_holder()->external_name()));
        *trace_name_printed = true;
D
duke 已提交
1010
      }
1011 1012 1013 1014 1015
      // RC_TRACE macro has an embedded ResourceMark
      RC_TRACE(0x00100000, ("vtable method update: %s(%s), updated default = %s",
                            new_method->name()->as_C_string(),
                            new_method->signature()->as_C_string(),
                            updated_default ? "true" : "false"));
D
duke 已提交
1016 1017 1018 1019
    }
  }
}

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
// a vtable should never contain old or obsolete methods
bool klassVtable::check_no_old_or_obsolete_entries() {
  for (int i = 0; i < length(); i++) {
    Method* m = unchecked_method_at(i);
    if (m != NULL &&
        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
      return false;
    }
  }
  return true;
}

void klassVtable::dump_vtable() {
  tty->print_cr("vtable dump --");
  for (int i = 0; i < length(); i++) {
    Method* m = unchecked_method_at(i);
    if (m != NULL) {
      tty->print("      (%5d)  ", i);
      m->access_flags().print_on(tty);
1039
      if (m->is_default_method()) {
1040
        tty->print("default ");
1041 1042 1043 1044
      }
      if (m->is_overpass()) {
        tty->print("overpass");
      }
1045 1046 1047 1048 1049 1050 1051 1052
      tty->print(" --  ");
      m->print_name(tty);
      tty->cr();
    }
  }
}
#endif // INCLUDE_JVMTI

1053 1054 1055 1056 1057 1058 1059 1060 1061
// CDS/RedefineClasses support - clear vtables so they can be reinitialized
void klassVtable::clear_vtable() {
  for (int i = 0; i < _length; i++) table()[i].clear();
}

bool klassVtable::is_initialized() {
  return _length == 0 || table()[0].method() != NULL;
}

D
duke 已提交
1062 1063 1064 1065
//-----------------------------------------------------------------------------------------
// Itable code

// Initialize a itableMethodEntry
1066
void itableMethodEntry::initialize(Method* m) {
D
duke 已提交
1067 1068
  if (m == NULL) return;

J
jiangli 已提交
1069 1070 1071 1072 1073 1074 1075 1076 1077
  if (MetaspaceShared::is_in_shared_space((void*)&_method) &&
     !MetaspaceShared::remapped_readwrite()) {
    // At runtime initialize_itable is rerun as part of link_class_impl()
    // for a shared class loaded by the non-boot loader.
    // The dumptime itable method entry should be the same as the runtime entry.
    assert(_method == m, "sanity");
  } else {
    _method = m;
  }
D
duke 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086
}

klassItable::klassItable(instanceKlassHandle klass) {
  _klass = klass;

  if (klass->itable_length() > 0) {
    itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
    if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
      // First offset entry points to the first method_entry
1087
      intptr_t* method_entry  = (intptr_t *)(((address)klass()) + offset_entry->offset());
D
duke 已提交
1088 1089
      intptr_t* end         = klass->end_of_itable();

1090
      _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass();
D
duke 已提交
1091 1092 1093 1094 1095 1096 1097
      _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
      _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
      assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
      return;
    }
  }

1098
  // The length of the itable was either zero, or it has not yet been initialized.
D
duke 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107
  _table_offset      = 0;
  _size_offset_table = 0;
  _size_method_table = 0;
}

static int initialize_count = 0;

// Initialization
void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
1108
  if (_klass->is_interface()) {
1109 1110 1111
    // This needs to go after vtable indices are assigned but
    // before implementors need to know the number of itable indices.
    assign_itable_indices_for_interface(_klass());
1112 1113
  }

1114 1115 1116 1117 1118 1119 1120 1121 1122
  // Cannot be setup doing bootstrapping, interfaces don't have
  // itables, and klass with only ones entry have empty itables
  if (Universe::is_bootstrapping() ||
      _klass->is_interface() ||
      _klass->itable_length() == itableOffsetEntry::size()) return;

  // There's alway an extra itable entry so we can null-terminate it.
  guarantee(size_offset_table() >= 1, "too small");
  int num_interfaces = size_offset_table() - 1;
D
duke 已提交
1123
  if (num_interfaces > 0) {
1124 1125
    if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count,
                                    _klass->name()->as_C_string());
D
duke 已提交
1126 1127


1128
    // Iterate through all interfaces
D
duke 已提交
1129 1130 1131
    int i;
    for(i = 0; i < num_interfaces; i++) {
      itableOffsetEntry* ioe = offset_entry(i);
1132
      HandleMark hm(THREAD);
D
duke 已提交
1133 1134 1135 1136 1137 1138
      KlassHandle interf_h (THREAD, ioe->interface_klass());
      assert(interf_h() != NULL && ioe->offset() != 0, "bad offset entry in itable");
      initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK);
    }

  }
1139 1140 1141
  // Check that the last entry is empty
  itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
  guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
D
duke 已提交
1142 1143 1144
}


1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
inline bool interface_method_needs_itable_index(Method* m) {
  if (m->is_static())           return false;   // e.g., Stream.empty
  if (m->is_initializer())      return false;   // <init> or <clinit>
  // If an interface redeclares a method from java.lang.Object,
  // it should already have a vtable index, don't touch it.
  // e.g., CharSequence.toString (from initialize_vtable)
  // if (m->has_vtable_index())  return false; // NO!
  return true;
}

1155
int klassItable::assign_itable_indices_for_interface(Klass* klass) {
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  // an interface does not have an itable, but its methods need to be numbered
  if (TraceItables) tty->print_cr("%3d: Initializing itable for interface %s", ++initialize_count,
                                  klass->name()->as_C_string());
  Array<Method*>* methods = InstanceKlass::cast(klass)->methods();
  int nof_methods = methods->length();
  int ime_num = 0;
  for (int i = 0; i < nof_methods; i++) {
    Method* m = methods->at(i);
    if (interface_method_needs_itable_index(m)) {
      assert(!m->is_final_method(), "no final interface methods");
      // If m is already assigned a vtable index, do not disturb it.
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
      if (TraceItables && Verbose) {
        ResourceMark rm;
        const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";
        if (m->has_vtable_index()) {
          tty->print("itable index %d for method: %s, flags: ", m->vtable_index(), sig);
        } else {
          tty->print("itable index %d for method: %s, flags: ", ime_num, sig);
        }
        if (m != NULL) {
          m->access_flags().print_on(tty);
          if (m->is_default_method()) {
            tty->print("default ");
          }
          if (m->is_overpass()) {
            tty->print("overpass");
          }
        }
        tty->cr();
      }
1186
      if (!m->has_vtable_index()) {
J
jiangli 已提交
1187 1188 1189 1190 1191
        // A shared method could have an initialized itable_index that
        // is < 0.
        assert(m->vtable_index() == Method::pending_itable_index ||
               m->is_shared(),
               "set by initialize_vtable");
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
        m->set_itable_index(ime_num);
        // Progress to next itable entry
        ime_num++;
      }
    }
  }
  assert(ime_num == method_count_for_interface(klass), "proper sizing");
  return ime_num;
}

int klassItable::method_count_for_interface(Klass* interf) {
  assert(interf->oop_is_instance(), "must be");
  assert(interf->is_interface(), "must be");
  Array<Method*>* methods = InstanceKlass::cast(interf)->methods();
  int nof_methods = methods->length();
  while (nof_methods > 0) {
    Method* m = methods->at(nof_methods-1);
    if (m->has_itable_index()) {
      int length = m->itable_index() + 1;
#ifdef ASSERT
      while (nof_methods = 0) {
        m = methods->at(--nof_methods);
        assert(!m->has_itable_index() || m->itable_index() < length, "");
      }
#endif //ASSERT
      return length;  // return the rightmost itable index, plus one
    }
    nof_methods -= 1;
  }
1221
  // no methods have itable indices
1222 1223 1224 1225
  return 0;
}


D
duke 已提交
1226
void klassItable::initialize_itable_for_interface(int method_table_offset, KlassHandle interf_h, bool checkconstraints, TRAPS) {
1227 1228
  Array<Method*>* methods = InstanceKlass::cast(interf_h())->methods();
  int nof_methods = methods->length();
D
duke 已提交
1229
  HandleMark hm;
1230
  Handle interface_loader (THREAD, InstanceKlass::cast(interf_h())->class_loader());
D
duke 已提交
1231

1232 1233
  int ime_count = method_count_for_interface(interf_h());
  for (int i = 0; i < nof_methods; i++) {
1234
    Method* m = methods->at(i);
1235 1236
    methodHandle target;
    if (m->has_itable_index()) {
1237 1238
      // This search must match the runtime resolution, i.e. selection search for invokeinterface
      // to correctly enforce loader constraints for interface method inheritance
1239
      LinkResolver::lookup_instance_method_in_klasses(target, _klass, m->name(), m->signature(), CHECK);
D
duke 已提交
1240 1241
    }
    if (target == NULL || !target->is_public() || target->is_abstract()) {
1242 1243 1244 1245 1246 1247
      // Entry does not resolve. Leave it empty for AbstractMethodError.
        if (!(target == NULL) && !target->is_public()) {
          // Stuff an IllegalAccessError throwing method in there instead.
          itableOffsetEntry::method_entry(_klass(), method_table_offset)[m->itable_index()].
              initialize(Universe::throw_illegal_access_error());
        }
D
duke 已提交
1248 1249 1250 1251
    } else {
      // Entry did resolve, check loader constraints before initializing
      // if checkconstraints requested
      if (checkconstraints) {
1252
        Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
D
duke 已提交
1253 1254
        if (method_holder_loader() != interface_loader()) {
          ResourceMark rm(THREAD);
1255
          Symbol* failed_type_symbol =
1256
            SystemDictionary::check_signature_loaders(m->signature(),
D
duke 已提交
1257 1258 1259
                                                      method_holder_loader,
                                                      interface_loader,
                                                      true, CHECK);
1260
          if (failed_type_symbol != NULL) {
D
duke 已提交
1261 1262 1263 1264 1265 1266
            const char* msg = "loader constraint violation in interface "
              "itable initialization: when resolving method \"%s\" the class"
              " loader (instance of %s) of the current class, %s, "
              "and the class loader (instance of %s) for interface "
              "%s have different Class objects for the type %s "
              "used in the signature";
1267
            char* sig = target()->name_and_sig_as_C_string();
D
duke 已提交
1268
            const char* loader1 = SystemDictionary::loader_name(method_holder_loader());
1269
            char* current = _klass->name()->as_C_string();
D
duke 已提交
1270
            const char* loader2 = SystemDictionary::loader_name(interface_loader());
1271
            char* iface = InstanceKlass::cast(interf_h())->name()->as_C_string();
1272
            char* failed_type_name = failed_type_symbol->as_C_string();
D
duke 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
            size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
              strlen(current) + strlen(loader2) + strlen(iface) +
              strlen(failed_type_name);
            char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
            jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
                         iface, failed_type_name);
            THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
          }
        }
      }

      // ime may have moved during GC so recalculate address
1285 1286 1287
      int ime_num = m->itable_index();
      assert(ime_num < ime_count, "oob");
      itableOffsetEntry::method_entry(_klass(), method_table_offset)[ime_num].initialize(target());
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
      if (TraceItables && Verbose) {
        ResourceMark rm(THREAD);
        if (target() != NULL) {
          char* sig = target()->name_and_sig_as_C_string();
          tty->print("interface: %s, ime_num: %d, target: %s, method_holder: %s ",
                    interf_h()->internal_name(), ime_num, sig,
                    target()->method_holder()->internal_name());
          tty->print("target_method flags: ");
          target()->access_flags().print_on(tty);
          if (target()->is_default_method()) {
1298
            tty->print("default ");
1299 1300 1301 1302
          }
          tty->cr();
        }
      }
D
duke 已提交
1303 1304 1305 1306
    }
  }
}

1307 1308
// Update entry for specific Method*
void klassItable::initialize_with_method(Method* m) {
D
duke 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317
  itableMethodEntry* ime = method_entry(0);
  for(int i = 0; i < _size_method_table; i++) {
    if (ime->method() == m) {
      ime->initialize(m);
    }
    ime++;
  }
}

1318
#if INCLUDE_JVMTI
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
// search the itable for uses of either obsolete or EMCP methods
void klassItable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) {

  itableMethodEntry* ime = method_entry(0);
  for (int i = 0; i < _size_method_table; i++, ime++) {
    Method* old_method = ime->method();
    if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
      continue; // skip uninteresting entries
    }
    assert(!old_method->is_deleted(), "itable methods may not be deleted");

    Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());

    assert(new_method != NULL, "method_with_idnum() should not be NULL");
    assert(old_method != new_method, "sanity check");

    ime->initialize(new_method);

    if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
      if (!(*trace_name_printed)) {
        // RC_TRACE_MESG macro has an embedded ResourceMark
        RC_TRACE_MESG(("adjust: name=%s",
          old_method->method_holder()->external_name()));
        *trace_name_printed = true;
D
duke 已提交
1343
      }
1344 1345 1346 1347
      // RC_TRACE macro has an embedded ResourceMark
      RC_TRACE(0x00200000, ("itable method update: %s(%s)",
        new_method->name()->as_C_string(),
        new_method->signature()->as_C_string()));
D
duke 已提交
1348 1349 1350 1351
    }
  }
}

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
// an itable should never contain old or obsolete methods
bool klassItable::check_no_old_or_obsolete_entries() {
  itableMethodEntry* ime = method_entry(0);
  for (int i = 0; i < _size_method_table; i++) {
    Method* m = ime->method();
    if (m != NULL &&
        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
      return false;
    }
    ime++;
  }
  return true;
}

void klassItable::dump_itable() {
  itableMethodEntry* ime = method_entry(0);
  tty->print_cr("itable dump --");
  for (int i = 0; i < _size_method_table; i++) {
    Method* m = ime->method();
    if (m != NULL) {
      tty->print("      (%5d)  ", i);
      m->access_flags().print_on(tty);
1374
      if (m->is_default_method()) {
1375
        tty->print("default ");
1376
      }
1377 1378 1379 1380 1381 1382 1383 1384 1385
      tty->print(" --  ");
      m->print_name(tty);
      tty->cr();
    }
    ime++;
  }
}
#endif // INCLUDE_JVMTI

D
duke 已提交
1386 1387 1388
// Setup
class InterfaceVisiterClosure : public StackObj {
 public:
1389
  virtual void doit(Klass* intf, int method_count) = 0;
D
duke 已提交
1390 1391
};

1392
// Visit all interfaces with at least one itable method
1393
void visit_all_interfaces(Array<Klass*>* transitive_intf, InterfaceVisiterClosure *blk) {
D
duke 已提交
1394 1395
  // Handle array argument
  for(int i = 0; i < transitive_intf->length(); i++) {
1396
    Klass* intf = transitive_intf->at(i);
H
hseigel 已提交
1397
    assert(intf->is_interface(), "sanity check");
D
duke 已提交
1398

1399 1400 1401 1402 1403 1404 1405 1406 1407
    // Find no. of itable methods
    int method_count = 0;
    // method_count = klassItable::method_count_for_interface(intf);
    Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
    if (methods->length() > 0) {
      for (int i = methods->length(); --i >= 0; ) {
        if (interface_method_needs_itable_index(methods->at(i))) {
          method_count++;
        }
D
duke 已提交
1408 1409 1410
      }
    }

D
dbuck 已提交
1411 1412 1413 1414
    // Visit all interfaces which either have any methods or can participate in receiver type check.
    // We do not bother to count methods in transitive interfaces, although that would allow us to skip
    // this step in the rare case of a zero-method interface extending another zero-method interface.
    if (method_count > 0 || InstanceKlass::cast(intf)->transitive_interfaces()->length() > 0) {
D
duke 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
      blk->doit(intf, method_count);
    }
  }
}

class CountInterfacesClosure : public InterfaceVisiterClosure {
 private:
  int _nof_methods;
  int _nof_interfaces;
 public:
   CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }

   int nof_methods() const    { return _nof_methods; }
   int nof_interfaces() const { return _nof_interfaces; }

1430
   void doit(Klass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
D
duke 已提交
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
};

class SetupItableClosure : public InterfaceVisiterClosure  {
 private:
  itableOffsetEntry* _offset_entry;
  itableMethodEntry* _method_entry;
  address            _klass_begin;
 public:
  SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
    _klass_begin  = klass_begin;
    _offset_entry = offset_entry;
    _method_entry = method_entry;
  }

  itableMethodEntry* method_entry() const { return _method_entry; }

1447
  void doit(Klass* intf, int method_count) {
D
duke 已提交
1448 1449 1450 1451 1452 1453 1454
    int offset = ((address)_method_entry) - _klass_begin;
    _offset_entry->initialize(intf, offset);
    _offset_entry++;
    _method_entry += method_count;
  }
};

1455
int klassItable::compute_itable_size(Array<Klass*>* transitive_interfaces) {
D
duke 已提交
1456 1457
  // Count no of interfaces and total number of interface methods
  CountInterfacesClosure cic;
1458
  visit_all_interfaces(transitive_interfaces, &cic);
D
duke 已提交
1459

1460 1461
  // There's alway an extra itable entry so we can null-terminate it.
  int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
D
duke 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480

  // Statistics
  update_stats(itable_size * HeapWordSize);

  return itable_size;
}


// Fill out offset table and interface klasses into the itable space
void klassItable::setup_itable_offset_table(instanceKlassHandle klass) {
  if (klass->itable_length() == 0) return;
  assert(!klass->is_interface(), "Should have zero length itable");

  // Count no of interfaces and total number of interface methods
  CountInterfacesClosure cic;
  visit_all_interfaces(klass->transitive_interfaces(), &cic);
  int nof_methods    = cic.nof_methods();
  int nof_interfaces = cic.nof_interfaces();

1481 1482
  // Add one extra entry so we can null-terminate the table
  nof_interfaces++;
D
duke 已提交
1483

1484
  assert(compute_itable_size(klass->transitive_interfaces()) ==
D
duke 已提交
1485 1486 1487 1488 1489 1490 1491
         calc_itable_size(nof_interfaces, nof_methods),
         "mismatch calculation of itable size");

  // Fill-out offset table
  itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
  itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
  intptr_t* end               = klass->end_of_itable();
1492
  assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");
1493
  assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
D
duke 已提交
1494 1495

  // Visit all interfaces and initialize itable offset table
1496
  SetupItableClosure sic((address)klass(), ioe, ime);
D
duke 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
  visit_all_interfaces(klass->transitive_interfaces(), &sic);

#ifdef ASSERT
  ime  = sic.method_entry();
  oop* v = (oop*) klass->end_of_itable();
  assert( (oop*)(ime) == v, "wrong offset calculation (2)");
#endif
}


1507
// inverse to itable_index
1508 1509
Method* klassItable::method_for_itable_index(Klass* intf, int itable_index) {
  assert(InstanceKlass::cast(intf)->is_interface(), "sanity check");
1510
  assert(intf->verify_itable_index(itable_index), "");
1511
  Array<Method*>* methods = InstanceKlass::cast(intf)->methods();
1512

1513
  if (itable_index < 0 || itable_index >= method_count_for_interface(intf))
1514
    return NULL;                // help caller defend against bad indices
1515

1516
  int index = itable_index;
1517
  Method* m = methods->at(index);
1518 1519 1520 1521 1522 1523 1524 1525 1526
  int index2 = -1;
  while (!m->has_itable_index() ||
         (index2 = m->itable_index()) != itable_index) {
    assert(index2 < itable_index, "monotonic");
    if (++index == methods->length())
      return NULL;
    m = methods->at(index);
  }
  assert(m->itable_index() == itable_index, "correct inverse");
1527 1528 1529 1530

  return m;
}

D
duke 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
void klassVtable::verify(outputStream* st, bool forced) {
  // make sure table is initialized
  if (!Universe::is_fully_initialized()) return;
#ifndef PRODUCT
  // avoid redundant verifies
  if (!forced && _verify_count == Universe::verify_count()) return;
  _verify_count = Universe::verify_count();
#endif
  oop* end_of_obj = (oop*)_klass() + _klass()->size();
  oop* end_of_vtable = (oop *)&table()[_length];
  if (end_of_vtable > end_of_obj) {
1542 1543
    fatal(err_msg("klass %s: klass object too short (vtable extends beyond "
                  "end)", _klass->internal_name()));
D
duke 已提交
1544 1545 1546 1547
  }

  for (int i = 0; i < _length; i++) table()[i].verify(this, st);
  // verify consistency with superKlass vtable
1548
  Klass* super = _klass->super();
D
duke 已提交
1549
  if (super != NULL) {
1550
    InstanceKlass* sk = InstanceKlass::cast(super);
D
duke 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    klassVtable* vt = sk->vtable();
    for (int i = 0; i < vt->length(); i++) {
      verify_against(st, vt, i);
    }
  }
}

void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
  vtableEntry* vte = &vt->table()[index];
  if (vte->method()->name()      != table()[index].method()->name() ||
      vte->method()->signature() != table()[index].method()->signature()) {
    fatal("mismatched name/signature of vtable entries");
  }
}

#ifndef PRODUCT
void klassVtable::print() {
  ResourceMark rm;
  tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
  for (int i = 0; i < length(); i++) {
    table()[i].print();
    tty->cr();
  }
}
#endif

void vtableEntry::verify(klassVtable* vt, outputStream* st) {
  NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true));
  assert(method() != NULL, "must have set method");
  method()->verify();
  // we sub_type, because it could be a miranda method
  if (!vt->klass()->is_subtype_of(method()->method_holder())) {
#ifndef PRODUCT
    print();
#endif
1586
    fatal(err_msg("vtableEntry " PTR_FORMAT ": method is from subclass", this));
D
duke 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
  }
}

#ifndef PRODUCT

void vtableEntry::print() {
  ResourceMark rm;
  tty->print("vtableEntry %s: ", method()->name()->as_C_string());
  if (Verbose) {
    tty->print("m %#lx ", (address)method());
  }
}

class VtableStats : AllStatic {
 public:
  static int no_klasses;                // # classes with vtables
  static int no_array_klasses;          // # array classes
  static int no_instance_klasses;       // # instanceKlasses
  static int sum_of_vtable_len;         // total # of vtable entries
  static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
  static int fixed;                     // total fixed overhead in bytes
  static int filler;                    // overhead caused by filler bytes
  static int entries;                   // total bytes consumed by vtable entries
  static int array_entries;             // total bytes consumed by array vtable entries

1612 1613
  static void do_class(Klass* k) {
    Klass* kl = k;
D
duke 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
    klassVtable* vt = kl->vtable();
    if (vt == NULL) return;
    no_klasses++;
    if (kl->oop_is_instance()) {
      no_instance_klasses++;
      kl->array_klasses_do(do_class);
    }
    if (kl->oop_is_array()) {
      no_array_klasses++;
      sum_of_array_vtable_len += vt->length();
    }
    sum_of_vtable_len += vt->length();
  }

  static void compute() {
    SystemDictionary::classes_do(do_class);
    fixed  = no_klasses * oopSize;      // vtable length
    // filler size is a conservative approximation
1632
    filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);
D
duke 已提交
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    entries = sizeof(vtableEntry) * sum_of_vtable_len;
    array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
  }
};

int VtableStats::no_klasses = 0;
int VtableStats::no_array_klasses = 0;
int VtableStats::no_instance_klasses = 0;
int VtableStats::sum_of_vtable_len = 0;
int VtableStats::sum_of_array_vtable_len = 0;
int VtableStats::fixed = 0;
int VtableStats::filler = 0;
int VtableStats::entries = 0;
int VtableStats::array_entries = 0;

void klassVtable::print_statistics() {
  ResourceMark rm;
  HandleMark hm;
  VtableStats::compute();
  tty->print_cr("vtable statistics:");
  tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
  int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
  tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
  tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
  tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
  tty->print_cr("%6d bytes total", total);
}

int  klassItable::_total_classes;   // Total no. of classes with itables
long klassItable::_total_size;      // Total no. of bytes used for itables

void klassItable::print_statistics() {
 tty->print_cr("itable statistics:");
 tty->print_cr("%6d classes with itables", _total_classes);
 tty->print_cr("%6d K uses for itables (average by class: %d bytes)", _total_size / K, _total_size / _total_classes);
}

#endif // PRODUCT