src/share/vm/classfile/defaultMethods.cpp

Tue, 09 Jul 2013 14:02:28 -0400

author
acorn
date
Tue, 09 Jul 2013 14:02:28 -0400
changeset 5377
50257d6f5aaa
parent 5209
fe00365c8f31
child 5599
91b93f523ec6
permissions
-rw-r--r--

8013635: VM should no longer create bridges for generic signatures.
Summary: Requires: 8013789: Compiler bridges, 8015402: metafactory
Reviewed-by: sspitsyn, coleenp, bharadwaj

     1 /*
     2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "classfile/bytecodeAssembler.hpp"
    27 #include "classfile/defaultMethods.hpp"
    28 #include "classfile/genericSignatures.hpp"
    29 #include "classfile/symbolTable.hpp"
    30 #include "memory/allocation.hpp"
    31 #include "memory/metadataFactory.hpp"
    32 #include "memory/resourceArea.hpp"
    33 #include "runtime/signature.hpp"
    34 #include "runtime/thread.hpp"
    35 #include "oops/instanceKlass.hpp"
    36 #include "oops/klass.hpp"
    37 #include "oops/method.hpp"
    38 #include "utilities/accessFlags.hpp"
    39 #include "utilities/exceptions.hpp"
    40 #include "utilities/ostream.hpp"
    41 #include "utilities/pair.hpp"
    42 #include "utilities/resourceHash.hpp"
    44 typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;
    46 // Because we use an iterative algorithm when iterating over the type
    47 // hierarchy, we can't use traditional scoped objects which automatically do
    48 // cleanup in the destructor when the scope is exited.  PseudoScope (and
    49 // PseudoScopeMark) provides a similar functionality, but for when you want a
    50 // scoped object in non-stack memory (such as in resource memory, as we do
    51 // here).  You've just got to remember to call 'destroy()' on the scope when
    52 // leaving it (and marks have to be explicitly added).
    53 class PseudoScopeMark : public ResourceObj {
    54  public:
    55   virtual void destroy() = 0;
    56 };
    58 class PseudoScope : public ResourceObj {
    59  private:
    60   GrowableArray<PseudoScopeMark*> _marks;
    61  public:
    63   static PseudoScope* cast(void* data) {
    64     return static_cast<PseudoScope*>(data);
    65   }
    67   void add_mark(PseudoScopeMark* psm) {
    68    _marks.append(psm);
    69   }
    71   void destroy() {
    72     for (int i = 0; i < _marks.length(); ++i) {
    73       _marks.at(i)->destroy();
    74     }
    75   }
    76 };
    78 class ContextMark : public PseudoScopeMark {
    79  private:
    80   generic::Context::Mark _mark;
    81  public:
    82   ContextMark(const generic::Context::Mark& cm) : _mark(cm) {}
    83   virtual void destroy() { _mark.destroy(); }
    84 };
    86 #ifndef PRODUCT
    87 static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {
    88   ResourceMark rm;
    89   str->print("%s%s", name->as_C_string(), signature->as_C_string());
    90 }
    92 static void print_method(outputStream* str, Method* mo, bool with_class=true) {
    93   ResourceMark rm;
    94   if (with_class) {
    95     str->print("%s.", mo->klass_name()->as_C_string());
    96   }
    97   print_slot(str, mo->name(), mo->signature());
    98 }
    99 #endif // ndef PRODUCT
   101 /**
   102  * Perform a depth-first iteration over the class hierarchy, applying
   103  * algorithmic logic as it goes.
   104  *
   105  * This class is one half of the inheritance hierarchy analysis mechanism.
   106  * It is meant to be used in conjunction with another class, the algorithm,
   107  * which is indicated by the ALGO template parameter.  This class can be
   108  * paired with any algorithm class that provides the required methods.
   109  *
   110  * This class contains all the mechanics for iterating over the class hierarchy
   111  * starting at a particular root, without recursing (thus limiting stack growth
   112  * from this point).  It visits each superclass (if present) and superinterface
   113  * in a depth-first manner, with callbacks to the ALGO class as each class is
   114  * encountered (visit()), The algorithm can cut-off further exploration of a
   115  * particular branch by returning 'false' from a visit() call.
   116  *
   117  * The ALGO class, must provide a visit() method, which each of which will be
   118  * called once for each node in the inheritance tree during the iteration.  In
   119  * addition, it can provide a memory block via new_node_data(InstanceKlass*),
   120  * which it can use for node-specific storage (and access via the
   121  * current_data() and data_at_depth(int) methods).
   122  *
   123  * Bare minimum needed to be an ALGO class:
   124  * class Algo : public HierarchyVisitor<Algo> {
   125  *   void* new_node_data(InstanceKlass* cls) { return NULL; }
   126  *   void free_node_data(void* data) { return; }
   127  *   bool visit() { return true; }
   128  * };
   129  */
   130 template <class ALGO>
   131 class HierarchyVisitor : StackObj {
   132  private:
   134   class Node : public ResourceObj {
   135    public:
   136     InstanceKlass* _class;
   137     bool _super_was_visited;
   138     int _interface_index;
   139     void* _algorithm_data;
   141     Node(InstanceKlass* cls, void* data, bool visit_super)
   142         : _class(cls), _super_was_visited(!visit_super),
   143           _interface_index(0), _algorithm_data(data) {}
   145     int number_of_interfaces() { return _class->local_interfaces()->length(); }
   146     int interface_index() { return _interface_index; }
   147     void set_super_visited() { _super_was_visited = true; }
   148     void increment_visited_interface() { ++_interface_index; }
   149     void set_all_interfaces_visited() {
   150       _interface_index = number_of_interfaces();
   151     }
   152     bool has_visited_super() { return _super_was_visited; }
   153     bool has_visited_all_interfaces() {
   154       return interface_index() >= number_of_interfaces();
   155     }
   156     InstanceKlass* interface_at(int index) {
   157       return InstanceKlass::cast(_class->local_interfaces()->at(index));
   158     }
   159     InstanceKlass* next_super() { return _class->java_super(); }
   160     InstanceKlass* next_interface() {
   161       return interface_at(interface_index());
   162     }
   163   };
   165   bool _cancelled;
   166   GrowableArray<Node*> _path;
   168   Node* current_top() const { return _path.top(); }
   169   bool has_more_nodes() const { return !_path.is_empty(); }
   170   void push(InstanceKlass* cls, void* data) {
   171     assert(cls != NULL, "Requires a valid instance class");
   172     Node* node = new Node(cls, data, has_super(cls));
   173     _path.push(node);
   174   }
   175   void pop() { _path.pop(); }
   177   void reset_iteration() {
   178     _cancelled = false;
   179     _path.clear();
   180   }
   181   bool is_cancelled() const { return _cancelled; }
   183   static bool has_super(InstanceKlass* cls) {
   184     return cls->super() != NULL && !cls->is_interface();
   185   }
   187   Node* node_at_depth(int i) const {
   188     return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);
   189   }
   191  protected:
   193   // Accessors available to the algorithm
   194   int current_depth() const { return _path.length() - 1; }
   196   InstanceKlass* class_at_depth(int i) {
   197     Node* n = node_at_depth(i);
   198     return n == NULL ? NULL : n->_class;
   199   }
   200   InstanceKlass* current_class() { return class_at_depth(0); }
   202   void* data_at_depth(int i) {
   203     Node* n = node_at_depth(i);
   204     return n == NULL ? NULL : n->_algorithm_data;
   205   }
   206   void* current_data() { return data_at_depth(0); }
   208   void cancel_iteration() { _cancelled = true; }
   210  public:
   212   void run(InstanceKlass* root) {
   213     ALGO* algo = static_cast<ALGO*>(this);
   215     reset_iteration();
   217     void* algo_data = algo->new_node_data(root);
   218     push(root, algo_data);
   219     bool top_needs_visit = true;
   221     do {
   222       Node* top = current_top();
   223       if (top_needs_visit) {
   224         if (algo->visit() == false) {
   225           // algorithm does not want to continue along this path.  Arrange
   226           // it so that this state is immediately popped off the stack
   227           top->set_super_visited();
   228           top->set_all_interfaces_visited();
   229         }
   230         top_needs_visit = false;
   231       }
   233       if (top->has_visited_super() && top->has_visited_all_interfaces()) {
   234         algo->free_node_data(top->_algorithm_data);
   235         pop();
   236       } else {
   237         InstanceKlass* next = NULL;
   238         if (top->has_visited_super() == false) {
   239           next = top->next_super();
   240           top->set_super_visited();
   241         } else {
   242           next = top->next_interface();
   243           top->increment_visited_interface();
   244         }
   245         assert(next != NULL, "Otherwise we shouldn't be here");
   246         algo_data = algo->new_node_data(next);
   247         push(next, algo_data);
   248         top_needs_visit = true;
   249       }
   250     } while (!is_cancelled() && has_more_nodes());
   251   }
   252 };
   254 #ifndef PRODUCT
   255 class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {
   256  public:
   258   bool visit() {
   259     InstanceKlass* cls = current_class();
   260     streamIndentor si(tty, current_depth() * 2);
   261     tty->indent().print_cr("%s", cls->name()->as_C_string());
   262     return true;
   263   }
   265   void* new_node_data(InstanceKlass* cls) { return NULL; }
   266   void free_node_data(void* data) { return; }
   267 };
   268 #endif // ndef PRODUCT
   270 // Used to register InstanceKlass objects and all related metadata structures
   271 // (Methods, ConstantPools) as "in-use" by the current thread so that they can't
   272 // be deallocated by class redefinition while we're using them.  The classes are
   273 // de-registered when this goes out of scope.
   274 //
   275 // Once a class is registered, we need not bother with methodHandles or
   276 // constantPoolHandles for it's associated metadata.
   277 class KeepAliveRegistrar : public StackObj {
   278  private:
   279   Thread* _thread;
   280   GrowableArray<ConstantPool*> _keep_alive;
   282  public:
   283   KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(20) {
   284     assert(thread == Thread::current(), "Must be current thread");
   285   }
   287   ~KeepAliveRegistrar() {
   288     for (int i = _keep_alive.length() - 1; i >= 0; --i) {
   289       ConstantPool* cp = _keep_alive.at(i);
   290       int idx = _thread->metadata_handles()->find_from_end(cp);
   291       assert(idx > 0, "Must be in the list");
   292       _thread->metadata_handles()->remove_at(idx);
   293     }
   294   }
   296   // Register a class as 'in-use' by the thread.  It's fine to register a class
   297   // multiple times (though perhaps inefficient)
   298   void register_class(InstanceKlass* ik) {
   299     ConstantPool* cp = ik->constants();
   300     _keep_alive.push(cp);
   301     _thread->metadata_handles()->push(cp);
   302   }
   303 };
   305 class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {
   306  private:
   307   KeepAliveRegistrar* _registrar;
   309  public:
   310   KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}
   312   void* new_node_data(InstanceKlass* cls) { return NULL; }
   313   void free_node_data(void* data) { return; }
   315   bool visit() {
   316     _registrar->register_class(current_class());
   317     return true;
   318   }
   319 };
   322 // A method family contains a set of all methods that implement a single
   323 // erased method. As members of the set are collected while walking over the
   324 // hierarchy, they are tagged with a qualification state.  The qualification
   325 // state for an erased method is set to disqualified if there exists a path
   326 // from the root of hierarchy to the method that contains an interleaving
   327 // erased method defined in an interface.
   329 class MethodFamily : public ResourceObj {
   330  private:
   332   GrowableArray<Pair<Method*,QualifiedState> > _members;
   333   ResourceHashtable<Method*, int> _member_index;
   335   Method* _selected_target;  // Filled in later, if a unique target exists
   336   Symbol* _exception_message; // If no unique target is found
   338   bool contains_method(Method* method) {
   339     int* lookup = _member_index.get(method);
   340     return lookup != NULL;
   341   }
   343   void add_method(Method* method, QualifiedState state) {
   344     Pair<Method*,QualifiedState> entry(method, state);
   345     _member_index.put(method, _members.length());
   346     _members.append(entry);
   347   }
   349   void disqualify_method(Method* method) {
   350     int* index = _member_index.get(method);
   351     guarantee(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
   352     _members.at(*index).second = DISQUALIFIED;
   353   }
   355   Symbol* generate_no_defaults_message(TRAPS) const;
   356   Symbol* generate_abstract_method_message(Method* method, TRAPS) const;
   357   Symbol* generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const;
   359  public:
   361   MethodFamily()
   362       : _selected_target(NULL), _exception_message(NULL) {}
   364   void set_target_if_empty(Method* m) {
   365     if (_selected_target == NULL && !m->is_overpass()) {
   366       _selected_target = m;
   367     }
   368   }
   370   void record_qualified_method(Method* m) {
   371     // If the method already exists in the set as qualified, this operation is
   372     // redundant.  If it already exists as disqualified, then we leave it as
   373     // disqualfied.  Thus we only add to the set if it's not already in the
   374     // set.
   375     if (!contains_method(m)) {
   376       add_method(m, QUALIFIED);
   377     }
   378   }
   380   void record_disqualified_method(Method* m) {
   381     // If not in the set, add it as disqualified.  If it's already in the set,
   382     // then set the state to disqualified no matter what the previous state was.
   383     if (!contains_method(m)) {
   384       add_method(m, DISQUALIFIED);
   385     } else {
   386       disqualify_method(m);
   387     }
   388   }
   390   bool has_target() const { return _selected_target != NULL; }
   391   bool throws_exception() { return _exception_message != NULL; }
   393   Method* get_selected_target() { return _selected_target; }
   394   Symbol* get_exception_message() { return _exception_message; }
   396   // Either sets the target or the exception error message
   397   void determine_target(InstanceKlass* root, TRAPS) {
   398     if (has_target() || throws_exception()) {
   399       return;
   400     }
   402     GrowableArray<Method*> qualified_methods;
   403     for (int i = 0; i < _members.length(); ++i) {
   404       Pair<Method*,QualifiedState> entry = _members.at(i);
   405       if (entry.second == QUALIFIED) {
   406         qualified_methods.append(entry.first);
   407       }
   408     }
   410     if (qualified_methods.length() == 0) {
   411       _exception_message = generate_no_defaults_message(CHECK);
   412     } else if (qualified_methods.length() == 1) {
   413       Method* method = qualified_methods.at(0);
   414       if (method->is_abstract()) {
   415         _exception_message = generate_abstract_method_message(method, CHECK);
   416       } else {
   417         _selected_target = qualified_methods.at(0);
   418       }
   419     } else {
   420       _exception_message = generate_conflicts_message(&qualified_methods,CHECK);
   421     }
   423     assert((has_target() ^ throws_exception()) == 1,
   424            "One and only one must be true");
   425   }
   427   bool contains_signature(Symbol* query) {
   428     for (int i = 0; i < _members.length(); ++i) {
   429       if (query == _members.at(i).first->signature()) {
   430         return true;
   431       }
   432     }
   433     return false;
   434   }
   436 #ifndef PRODUCT
   437   void print_sig_on(outputStream* str, Symbol* signature, int indent) const {
   438     streamIndentor si(str, indent * 2);
   440     str->indent().print_cr("Logical Method %s:", signature->as_C_string());
   442     streamIndentor si2(str);
   443     for (int i = 0; i < _members.length(); ++i) {
   444       str->indent();
   445       print_method(str, _members.at(i).first);
   446       if (_members.at(i).second == DISQUALIFIED) {
   447         str->print(" (disqualified)");
   448       }
   449       str->print_cr("");
   450     }
   452     if (_selected_target != NULL) {
   453       print_selected(str, 1);
   454     }
   455   }
   457   void print_selected(outputStream* str, int indent) const {
   458     assert(has_target(), "Should be called otherwise");
   459     streamIndentor si(str, indent * 2);
   460     str->indent().print("Selected method: ");
   461     print_method(str, _selected_target);
   462     str->print_cr("");
   463   }
   465   void print_exception(outputStream* str, int indent) {
   466     assert(throws_exception(), "Should be called otherwise");
   467     streamIndentor si(str, indent * 2);
   468     str->indent().print_cr("%s", _exception_message->as_C_string());
   469   }
   470 #endif // ndef PRODUCT
   471 };
   473 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
   474   return SymbolTable::new_symbol("No qualifying defaults found", CHECK_NULL);
   475 }
   477 Symbol* MethodFamily::generate_abstract_method_message(Method* method, TRAPS) const {
   478   Symbol* klass = method->klass_name();
   479   Symbol* name = method->name();
   480   Symbol* sig = method->signature();
   481   stringStream ss;
   482   ss.print("Method ");
   483   ss.write((const char*)klass->bytes(), klass->utf8_length());
   484   ss.print(".");
   485   ss.write((const char*)name->bytes(), name->utf8_length());
   486   ss.write((const char*)sig->bytes(), sig->utf8_length());
   487   ss.print(" is abstract");
   488   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
   489 }
   491 Symbol* MethodFamily::generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const {
   492   stringStream ss;
   493   ss.print("Conflicting default methods:");
   494   for (int i = 0; i < methods->length(); ++i) {
   495     Method* method = methods->at(i);
   496     Symbol* klass = method->klass_name();
   497     Symbol* name = method->name();
   498     ss.print(" ");
   499     ss.write((const char*)klass->bytes(), klass->utf8_length());
   500     ss.print(".");
   501     ss.write((const char*)name->bytes(), name->utf8_length());
   502   }
   503   return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
   504 }
   506 // A generic method family contains a set of all methods that implement a single
   507 // language-level method.  Because of erasure, these methods may have different
   508 // signatures.  As members of the set are collected while walking over the
   509 // hierarchy, they are tagged with a qualification state.  The qualification
   510 // state for an erased method is set to disqualified if there exists a path
   511 // from the root of hierarchy to the method that contains an interleaving
   512 // language-equivalent method defined in an interface.
   513 class GenericMethodFamily : public MethodFamily {
   514  private:
   516   generic::MethodDescriptor* _descriptor; // language-level description
   518  public:
   520   GenericMethodFamily(generic::MethodDescriptor* canonical_desc)
   521       : _descriptor(canonical_desc) {}
   523   generic::MethodDescriptor* descriptor() const { return _descriptor; }
   525   bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) {
   526     return descriptor()->covariant_match(md, ctx);
   527   }
   529 #ifndef PRODUCT
   530   Symbol* get_generic_sig() const {
   532     generic::Context ctx(NULL); // empty, as _descriptor already canonicalized
   533     TempNewSymbol sig = descriptor()->reify_signature(&ctx, Thread::current());
   534     return sig;
   535   }
   536 #endif // ndef PRODUCT
   537 };
   539 class StateRestorer;
   541 // StatefulMethodFamily is a wrapper around a MethodFamily that maintains the
   542 // qualification state during hierarchy visitation, and applies that state
   543 // when adding members to the MethodFamily
   544 class StatefulMethodFamily : public ResourceObj {
   545   friend class StateRestorer;
   546  private:
   547   QualifiedState _qualification_state;
   549   void set_qualification_state(QualifiedState state) {
   550     _qualification_state = state;
   551   }
   553  protected:
   554   MethodFamily* _method_family;
   556  public:
   557   StatefulMethodFamily() {
   558    _method_family = new MethodFamily();
   559    _qualification_state = QUALIFIED;
   560   }
   562   StatefulMethodFamily(MethodFamily* mf) {
   563    _method_family = mf;
   564    _qualification_state = QUALIFIED;
   565   }
   567   void set_target_if_empty(Method* m) { _method_family->set_target_if_empty(m); }
   569   MethodFamily* get_method_family() { return _method_family; }
   571   StateRestorer* record_method_and_dq_further(Method* mo);
   572 };
   575 // StatefulGenericMethodFamily is a wrapper around GenericMethodFamily that maintains the
   576 // qualification state during hierarchy visitation, and applies that state
   577 // when adding members to the GenericMethodFamily.
   578 class StatefulGenericMethodFamily : public StatefulMethodFamily {
   580  public:
   581   StatefulGenericMethodFamily(generic::MethodDescriptor* md, generic::Context* ctx)
   582   : StatefulMethodFamily(new GenericMethodFamily(md->canonicalize(ctx))) {
   584   }
   585   GenericMethodFamily* get_method_family() {
   586     return (GenericMethodFamily*)_method_family;
   587   }
   589   bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) {
   590     return get_method_family()->descriptor_matches(md, ctx);
   591   }
   592 };
   594 class StateRestorer : public PseudoScopeMark {
   595  private:
   596   StatefulMethodFamily* _method;
   597   QualifiedState _state_to_restore;
   598  public:
   599   StateRestorer(StatefulMethodFamily* dm, QualifiedState state)
   600       : _method(dm), _state_to_restore(state) {}
   601   ~StateRestorer() { destroy(); }
   602   void restore_state() { _method->set_qualification_state(_state_to_restore); }
   603   virtual void destroy() { restore_state(); }
   604 };
   606 StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) {
   607   StateRestorer* mark = new StateRestorer(this, _qualification_state);
   608   if (_qualification_state == QUALIFIED) {
   609     _method_family->record_qualified_method(mo);
   610   } else {
   611     _method_family->record_disqualified_method(mo);
   612   }
   613   // Everything found "above"??? this method in the hierarchy walk is set to
   614   // disqualified
   615   set_qualification_state(DISQUALIFIED);
   616   return mark;
   617 }
   619 class StatefulGenericMethodFamilies : public ResourceObj {
   620  private:
   621   GrowableArray<StatefulGenericMethodFamily*> _methods;
   623  public:
   624   StatefulGenericMethodFamily* find_matching(
   625       generic::MethodDescriptor* md, generic::Context* ctx) {
   626     for (int i = 0; i < _methods.length(); ++i) {
   627       StatefulGenericMethodFamily* existing = _methods.at(i);
   628       if (existing->descriptor_matches(md, ctx)) {
   629         return existing;
   630       }
   631     }
   632     return NULL;
   633   }
   635   StatefulGenericMethodFamily* find_matching_or_create(
   636       generic::MethodDescriptor* md, generic::Context* ctx) {
   637     StatefulGenericMethodFamily* method = find_matching(md, ctx);
   638     if (method == NULL) {
   639       method = new StatefulGenericMethodFamily(md, ctx);
   640       _methods.append(method);
   641     }
   642     return method;
   643   }
   645   void extract_families_into(GrowableArray<GenericMethodFamily*>* array) {
   646     for (int i = 0; i < _methods.length(); ++i) {
   647       array->append(_methods.at(i)->get_method_family());
   648     }
   649   }
   650 };
   652 // Represents a location corresponding to a vtable slot for methods that
   653 // neither the class nor any of it's ancestors provide an implementaion.
   654 // Default methods may be present to fill this slot.
   655 class EmptyVtableSlot : public ResourceObj {
   656  private:
   657   Symbol* _name;
   658   Symbol* _signature;
   659   int _size_of_parameters;
   660   MethodFamily* _binding;
   662  public:
   663   EmptyVtableSlot(Method* method)
   664       : _name(method->name()), _signature(method->signature()),
   665         _size_of_parameters(method->size_of_parameters()), _binding(NULL) {}
   667   Symbol* name() const { return _name; }
   668   Symbol* signature() const { return _signature; }
   669   int size_of_parameters() const { return _size_of_parameters; }
   671   void bind_family(MethodFamily* lm) { _binding = lm; }
   672   bool is_bound() { return _binding != NULL; }
   673   MethodFamily* get_binding() { return _binding; }
   675 #ifndef PRODUCT
   676   void print_on(outputStream* str) const {
   677     print_slot(str, name(), signature());
   678   }
   679 #endif // ndef PRODUCT
   680 };
   682 static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots(
   683     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
   685   assert(klass != NULL, "Must be valid class");
   687   GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>();
   689   // All miranda methods are obvious candidates
   690   for (int i = 0; i < mirandas->length(); ++i) {
   691     EmptyVtableSlot* slot = new EmptyVtableSlot(mirandas->at(i));
   692     slots->append(slot);
   693   }
   695   // Also any overpasses in our superclasses, that we haven't implemented.
   696   // (can't use the vtable because it is not guaranteed to be initialized yet)
   697   InstanceKlass* super = klass->java_super();
   698   while (super != NULL) {
   699     for (int i = 0; i < super->methods()->length(); ++i) {
   700       Method* m = super->methods()->at(i);
   701       if (m->is_overpass()) {
   702         // m is a method that would have been a miranda if not for the
   703         // default method processing that occurred on behalf of our superclass,
   704         // so it's a method we want to re-examine in this new context.  That is,
   705         // unless we have a real implementation of it in the current class.
   706         Method* impl = klass->lookup_method(m->name(), m->signature());
   707         if (impl == NULL || impl->is_overpass()) {
   708           slots->append(new EmptyVtableSlot(m));
   709         }
   710       }
   711     }
   712     super = super->java_super();
   713   }
   715 #ifndef PRODUCT
   716   if (TraceDefaultMethods) {
   717     tty->print_cr("Slots that need filling:");
   718     streamIndentor si(tty);
   719     for (int i = 0; i < slots->length(); ++i) {
   720       tty->indent();
   721       slots->at(i)->print_on(tty);
   722       tty->print_cr("");
   723     }
   724   }
   725 #endif // ndef PRODUCT
   726   return slots;
   727 }
   729 // Iterates over the superinterface type hierarchy looking for all methods
   730 // with a specific erased signature.
   731 class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {
   732  private:
   733   // Context data
   734   Symbol* _method_name;
   735   Symbol* _method_signature;
   736   StatefulMethodFamily*  _family;
   738  public:
   739   FindMethodsByErasedSig(Symbol* name, Symbol* signature) :
   740       _method_name(name), _method_signature(signature),
   741       _family(NULL) {}
   743   void get_discovered_family(MethodFamily** family) {
   744       if (_family != NULL) {
   745         *family = _family->get_method_family();
   746       } else {
   747         *family = NULL;
   748       }
   749   }
   751   void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }
   752   void free_node_data(void* node_data) {
   753     PseudoScope::cast(node_data)->destroy();
   754   }
   756   // Find all methods on this hierarchy that match this
   757   // method's erased (name, signature)
   758   bool visit() {
   759     PseudoScope* scope = PseudoScope::cast(current_data());
   760     InstanceKlass* iklass = current_class();
   762     Method* m = iklass->find_method(_method_name, _method_signature);
   763     if (m != NULL) {
   764       if (_family == NULL) {
   765         _family = new StatefulMethodFamily();
   766       }
   768       if (iklass->is_interface()) {
   769         StateRestorer* restorer = _family->record_method_and_dq_further(m);
   770         scope->add_mark(restorer);
   771       } else {
   772         // This is the rule that methods in classes "win" (bad word) over
   773         // methods in interfaces. This works because of single inheritance
   774         _family->set_target_if_empty(m);
   775       }
   776     }
   777     return true;
   778   }
   780 };
   782 // Iterates over the type hierarchy looking for all methods with a specific
   783 // method name.  The result of this is a set of method families each of
   784 // which is populated with a set of methods that implement the same
   785 // language-level signature.
   786 class FindMethodsByGenericSig : public HierarchyVisitor<FindMethodsByGenericSig> {
   787  private:
   788   // Context data
   789   Thread* THREAD;
   790   generic::DescriptorCache* _cache;
   791   Symbol* _method_name;
   792   generic::Context* _ctx;
   793   StatefulGenericMethodFamilies _families;
   795  public:
   797   FindMethodsByGenericSig(generic::DescriptorCache* cache, Symbol* name,
   798       generic::Context* ctx, Thread* thread) :
   799     _cache(cache), _method_name(name), _ctx(ctx), THREAD(thread) {}
   801   void get_discovered_families(GrowableArray<GenericMethodFamily*>* methods) {
   802     _families.extract_families_into(methods);
   803   }
   805   void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }
   806   void free_node_data(void* node_data) {
   807     PseudoScope::cast(node_data)->destroy();
   808   }
   810   bool visit() {
   811     PseudoScope* scope = PseudoScope::cast(current_data());
   812     InstanceKlass* klass = current_class();
   813     InstanceKlass* sub = current_depth() > 0 ? class_at_depth(1) : NULL;
   815     ContextMark* cm = new ContextMark(_ctx->mark());
   816     scope->add_mark(cm); // will restore context when scope is freed
   818     _ctx->apply_type_arguments(sub, klass, THREAD);
   820     int start, end = 0;
   821     start = klass->find_method_by_name(_method_name, &end);
   822     if (start != -1) {
   823       for (int i = start; i < end; ++i) {
   824         Method* m = klass->methods()->at(i);
   825         // This gets the method's parameter list with its generic type
   826         // parameters resolved
   827         generic::MethodDescriptor* md = _cache->descriptor_for(m, THREAD);
   829         // Find all methods on this hierarchy that match this method
   830         // (name, signature).   This class collects other families of this
   831         // method name.
   832         StatefulGenericMethodFamily* family =
   833             _families.find_matching_or_create(md, _ctx);
   835         if (klass->is_interface()) {
   836           // ???
   837           StateRestorer* restorer = family->record_method_and_dq_further(m);
   838           scope->add_mark(restorer);
   839         } else {
   840           // This is the rule that methods in classes "win" (bad word) over
   841           // methods in interfaces.  This works because of single inheritance
   842           family->set_target_if_empty(m);
   843         }
   844       }
   845     }
   846     return true;
   847   }
   848 };
   850 #ifndef PRODUCT
   851 static void print_generic_families(
   852     GrowableArray<GenericMethodFamily*>* methods, Symbol* match) {
   853   streamIndentor si(tty, 4);
   854   if (methods->length() == 0) {
   855     tty->indent();
   856     tty->print_cr("No Logical Method found");
   857   }
   858   for (int i = 0; i < methods->length(); ++i) {
   859     tty->indent();
   860     GenericMethodFamily* lm = methods->at(i);
   861     if (lm->contains_signature(match)) {
   862       tty->print_cr("<Matching>");
   863     } else {
   864       tty->print_cr("<Non-Matching>");
   865     }
   866     lm->print_sig_on(tty, lm->get_generic_sig(), 1);
   867   }
   868 }
   869 #endif // ndef PRODUCT
   871 static void create_overpasses(
   872     GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);
   874 static void generate_generic_defaults(
   875       InstanceKlass* klass, GrowableArray<EmptyVtableSlot*>* empty_slots,
   876       EmptyVtableSlot* slot, int current_slot_index, TRAPS) {
   878   if (slot->is_bound()) {
   879 #ifndef PRODUCT
   880     if (TraceDefaultMethods) {
   881       streamIndentor si(tty, 4);
   882       tty->indent().print_cr("Already bound to logical method:");
   883       GenericMethodFamily* lm = (GenericMethodFamily*)(slot->get_binding());
   884       lm->print_sig_on(tty, lm->get_generic_sig(), 1);
   885     }
   886 #endif // ndef PRODUCT
   887     return; // covered by previous processing
   888   }
   890   generic::DescriptorCache cache;
   892   generic::Context ctx(&cache);
   893   FindMethodsByGenericSig visitor(&cache, slot->name(), &ctx, CHECK);
   894   visitor.run(klass);
   896   GrowableArray<GenericMethodFamily*> discovered_families;
   897   visitor.get_discovered_families(&discovered_families);
   899 #ifndef PRODUCT
   900   if (TraceDefaultMethods) {
   901     print_generic_families(&discovered_families, slot->signature());
   902   }
   903 #endif // ndef PRODUCT
   905   // Find and populate any other slots that match the discovered families
   906   for (int j = current_slot_index; j < empty_slots->length(); ++j) {
   907     EmptyVtableSlot* open_slot = empty_slots->at(j);
   909     if (slot->name() == open_slot->name()) {
   910       for (int k = 0; k < discovered_families.length(); ++k) {
   911         GenericMethodFamily* lm = discovered_families.at(k);
   913         if (lm->contains_signature(open_slot->signature())) {
   914           lm->determine_target(klass, CHECK);
   915           open_slot->bind_family(lm);
   916         }
   917       }
   918     }
   919   }
   920 }
   922 static void generate_erased_defaults(
   923      InstanceKlass* klass, GrowableArray<EmptyVtableSlot*>* empty_slots,
   924      EmptyVtableSlot* slot, TRAPS) {
   926   // sets up a set of methods with the same exact erased signature
   927   FindMethodsByErasedSig visitor(slot->name(), slot->signature());
   928   visitor.run(klass);
   930   MethodFamily* family;
   931   visitor.get_discovered_family(&family);
   932   if (family != NULL) {
   933     family->determine_target(klass, CHECK);
   934     slot->bind_family(family);
   935   }
   936 }
   938 static void merge_in_new_methods(InstanceKlass* klass,
   939     GrowableArray<Method*>* new_methods, TRAPS);
   941 // This is the guts of the default methods implementation.  This is called just
   942 // after the classfile has been parsed if some ancestor has default methods.
   943 //
   944 // First if finds any name/signature slots that need any implementation (either
   945 // because they are miranda or a superclass's implementation is an overpass
   946 // itself).  For each slot, iterate over the hierarchy, using generic signature
   947 // information to partition any methods that match the name into method families
   948 // where each family contains methods whose signatures are equivalent at the
   949 // language level (i.e., their reified parameters match and return values are
   950 // covariant). Check those sets to see if they contain a signature that matches
   951 // the slot we're looking at (if we're lucky, there might be other empty slots
   952 // that we can fill using the same analysis).
   953 //
   954 // For each slot filled, we generate an overpass method that either calls the
   955 // unique default method candidate using invokespecial, or throws an exception
   956 // (in the case of no default method candidates, or more than one valid
   957 // candidate).  These methods are then added to the class's method list.  If
   958 // the method set we're using contains methods (qualified or not) with a
   959 // different runtime signature than the method we're creating, then we have to
   960 // create bridges with those signatures too.
   961 void DefaultMethods::generate_default_methods(
   962     InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
   964   // This resource mark is the bound for all memory allocation that takes
   965   // place during default method processing.  After this goes out of scope,
   966   // all (Resource) objects' memory will be reclaimed.  Be careful if adding an
   967   // embedded resource mark under here as that memory can't be used outside
   968   // whatever scope it's in.
   969   ResourceMark rm(THREAD);
   971   // Keep entire hierarchy alive for the duration of the computation
   972   KeepAliveRegistrar keepAlive(THREAD);
   973   KeepAliveVisitor loadKeepAlive(&keepAlive);
   974   loadKeepAlive.run(klass);
   976 #ifndef PRODUCT
   977   if (TraceDefaultMethods) {
   978     ResourceMark rm;  // be careful with these!
   979     tty->print_cr("Class %s requires default method processing",
   980         klass->name()->as_klass_external_name());
   981     PrintHierarchy printer;
   982     printer.run(klass);
   983   }
   984 #endif // ndef PRODUCT
   986   GrowableArray<EmptyVtableSlot*>* empty_slots =
   987       find_empty_vtable_slots(klass, mirandas, CHECK);
   989   for (int i = 0; i < empty_slots->length(); ++i) {
   990     EmptyVtableSlot* slot = empty_slots->at(i);
   991 #ifndef PRODUCT
   992     if (TraceDefaultMethods) {
   993       streamIndentor si(tty, 2);
   994       tty->indent().print("Looking for default methods for slot ");
   995       slot->print_on(tty);
   996       tty->print_cr("");
   997     }
   998 #endif // ndef PRODUCT
  1000     if (ParseGenericDefaults) {
  1001       generate_generic_defaults(klass, empty_slots, slot, i, CHECK);
  1002     } else {
  1003       generate_erased_defaults(klass, empty_slots, slot, CHECK);
  1006 #ifndef PRODUCT
  1007   if (TraceDefaultMethods) {
  1008     tty->print_cr("Creating overpasses...");
  1010 #endif // ndef PRODUCT
  1012   create_overpasses(empty_slots, klass, CHECK);
  1014 #ifndef PRODUCT
  1015   if (TraceDefaultMethods) {
  1016     tty->print_cr("Default method processing complete");
  1018 #endif // ndef PRODUCT
  1021 /**
  1022  * Generic analysis was used upon interface '_target' and found a unique
  1023  * default method candidate with generic signature '_method_desc'.  This
  1024  * method is only viable if it would also be in the set of default method
  1025  * candidates if we ran a full analysis on the current class.
  1027  * The only reason that the method would not be in the set of candidates for
  1028  * the current class is if that there's another covariantly matching method
  1029  * which is "more specific" than the found method -- i.e., one could find a
  1030  * path in the interface hierarchy in which the matching method appears
  1031  * before we get to '_target'.
  1033  * In order to determine this, we examine all of the implemented
  1034  * interfaces.  If we find path that leads to the '_target' interface, then
  1035  * we examine that path to see if there are any methods that would shadow
  1036  * the selected method along that path.
  1037  */
  1038 class ShadowChecker : public HierarchyVisitor<ShadowChecker> {
  1039  protected:
  1040   Thread* THREAD;
  1042   InstanceKlass* _target;
  1044   Symbol* _method_name;
  1045   InstanceKlass* _method_holder;
  1046   bool _found_shadow;
  1049  public:
  1051   ShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder,
  1052                 InstanceKlass* target)
  1053                 : THREAD(thread), _method_name(name), _method_holder(holder),
  1054                 _target(target), _found_shadow(false) {}
  1056   void* new_node_data(InstanceKlass* cls) { return NULL; }
  1057   void free_node_data(void* data) { return; }
  1059   bool visit() {
  1060     InstanceKlass* ik = current_class();
  1061     if (ik == _target && current_depth() == 1) {
  1062       return false; // This was the specified super -- no need to search it
  1064     if (ik == _method_holder || ik == _target) {
  1065       // We found a path that should be examined to see if it shadows _method
  1066       if (path_has_shadow()) {
  1067         _found_shadow = true;
  1068         cancel_iteration();
  1070       return false; // no need to continue up hierarchy
  1072     return true;
  1075   virtual bool path_has_shadow() = 0;
  1076   bool found_shadow() { return _found_shadow; }
  1077 };
  1079 // Used for Invokespecial.
  1080 // Invokespecial is allowed to invoke a concrete interface method
  1081 // and can be used to disambuiguate among qualified candidates,
  1082 // which are methods in immediate superinterfaces,
  1083 // but may not be used to invoke a candidate that would be shadowed
  1084 // from the perspective of the caller.
  1085 // Invokespecial is also used in the overpass generation today
  1086 // We re-run the shadowchecker because we can't distinguish this case,
  1087 // but it should return the same answer, since the overpass target
  1088 // is now the invokespecial caller.
  1089 class ErasedShadowChecker : public ShadowChecker {
  1090  private:
  1091   bool path_has_shadow() {
  1093     for (int i = current_depth() - 1; i > 0; --i) {
  1094       InstanceKlass* ik = class_at_depth(i);
  1096       if (ik->is_interface()) {
  1097         int end;
  1098         int start = ik->find_method_by_name(_method_name, &end);
  1099         if (start != -1) {
  1100           return true;
  1104     return false;
  1106  public:
  1108   ErasedShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder,
  1109                 InstanceKlass* target)
  1110     : ShadowChecker(thread, name, holder, target) {}
  1111 };
  1113 class GenericShadowChecker : public ShadowChecker {
  1114  private:
  1115   generic::DescriptorCache* _cache;
  1116   generic::MethodDescriptor* _method_desc;
  1118   bool path_has_shadow() {
  1119     generic::Context ctx(_cache);
  1121     for (int i = current_depth() - 1; i > 0; --i) {
  1122       InstanceKlass* ik = class_at_depth(i);
  1123       InstanceKlass* sub = class_at_depth(i + 1);
  1124       ctx.apply_type_arguments(sub, ik, THREAD);
  1126       if (ik->is_interface()) {
  1127         int end;
  1128         int start = ik->find_method_by_name(_method_name, &end);
  1129         if (start != -1) {
  1130           for (int j = start; j < end; ++j) {
  1131             Method* mo = ik->methods()->at(j);
  1132             generic::MethodDescriptor* md = _cache->descriptor_for(mo, THREAD);
  1133             if (_method_desc->covariant_match(md, &ctx)) {
  1134               return true;
  1140     return false;
  1143  public:
  1145   GenericShadowChecker(generic::DescriptorCache* cache, Thread* thread,
  1146       Symbol* name, InstanceKlass* holder, generic::MethodDescriptor* desc,
  1147       InstanceKlass* target)
  1148     : ShadowChecker(thread, name, holder, target) {
  1149       _cache = cache;
  1150       _method_desc = desc;
  1152 };
  1156 // Find the unique qualified candidate from the perspective of the super_class
  1157 // which is the resolved_klass, which must be an immediate superinterface
  1158 // of klass
  1159 Method* find_erased_super_default(InstanceKlass* current_class, InstanceKlass* super_class, Symbol* method_name, Symbol* sig, TRAPS) {
  1161   FindMethodsByErasedSig visitor(method_name, sig);
  1162   visitor.run(super_class);      // find candidates from resolved_klass
  1164   MethodFamily* family;
  1165   visitor.get_discovered_family(&family);
  1167   if (family != NULL) {
  1168     family->determine_target(current_class, CHECK_NULL);  // get target from current_class
  1171   if (family->has_target()) {
  1172     Method* target = family->get_selected_target();
  1173     InstanceKlass* holder = InstanceKlass::cast(target->method_holder());
  1175     // Verify that the identified method is valid from the context of
  1176     // the current class, which is the caller class for invokespecial
  1177     // link resolution, i.e. ensure there it is not shadowed.
  1178     // You can use invokespecial to disambiguate interface methods, but
  1179     // you can not use it to skip over an interface method that would shadow it.
  1180     ErasedShadowChecker checker(THREAD, target->name(), holder, super_class);
  1181     checker.run(current_class);
  1183     if (checker.found_shadow()) {
  1184 #ifndef PRODUCT
  1185       if (TraceDefaultMethods) {
  1186         tty->print_cr("    Only candidate found was shadowed.");
  1188 #endif // ndef PRODUCT
  1189       THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
  1190                  "Accessible default method not found", NULL);
  1191     } else {
  1192 #ifndef PRODUCT
  1193       if (TraceDefaultMethods) {
  1194         family->print_sig_on(tty, target->signature(), 1);
  1196 #endif // ndef PRODUCT
  1197       return target;
  1199   } else {
  1200     assert(family->throws_exception(), "must have target or throw");
  1201     THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
  1202                family->get_exception_message()->as_C_string(), NULL);
  1206 // super_class is assumed to be the direct super of current_class
  1207 Method* find_generic_super_default( InstanceKlass* current_class,
  1208                                     InstanceKlass* super_class,
  1209                                     Symbol* method_name, Symbol* sig, TRAPS) {
  1210   generic::DescriptorCache cache;
  1211   generic::Context ctx(&cache);
  1213   // Prime the initial generic context for current -> super_class
  1214   ctx.apply_type_arguments(current_class, super_class, CHECK_NULL);
  1216   FindMethodsByGenericSig visitor(&cache, method_name, &ctx, CHECK_NULL);
  1217   visitor.run(super_class);
  1219   GrowableArray<GenericMethodFamily*> families;
  1220   visitor.get_discovered_families(&families);
  1222 #ifndef PRODUCT
  1223   if (TraceDefaultMethods) {
  1224     print_generic_families(&families, sig);
  1226 #endif // ndef PRODUCT
  1228   GenericMethodFamily* selected_family = NULL;
  1230   for (int i = 0; i < families.length(); ++i) {
  1231     GenericMethodFamily* lm = families.at(i);
  1232     if (lm->contains_signature(sig)) {
  1233       lm->determine_target(current_class, CHECK_NULL);
  1234       selected_family = lm;
  1238   if (selected_family->has_target()) {
  1239     Method* target = selected_family->get_selected_target();
  1240     InstanceKlass* holder = InstanceKlass::cast(target->method_holder());
  1242     // Verify that the identified method is valid from the context of
  1243     // the current class
  1244     GenericShadowChecker checker(&cache, THREAD, target->name(),
  1245         holder, selected_family->descriptor(), super_class);
  1246     checker.run(current_class);
  1248     if (checker.found_shadow()) {
  1249 #ifndef PRODUCT
  1250       if (TraceDefaultMethods) {
  1251         tty->print_cr("    Only candidate found was shadowed.");
  1253 #endif // ndef PRODUCT
  1254       THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
  1255                  "Accessible default method not found", NULL);
  1256     } else {
  1257       return target;
  1259   } else {
  1260     assert(selected_family->throws_exception(), "must have target or throw");
  1261     THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(),
  1262                selected_family->get_exception_message()->as_C_string(), NULL);
  1266 // This is called during linktime when we find an invokespecial call that
  1267 // refers to a direct superinterface.  It indicates that we should find the
  1268 // default method in the hierarchy of that superinterface, and if that method
  1269 // would have been a candidate from the point of view of 'this' class, then we
  1270 // return that method.
  1271 // This logic assumes that the super is a direct superclass of the caller
  1272 Method* DefaultMethods::find_super_default(
  1273     Klass* cls, Klass* super, Symbol* method_name, Symbol* sig, TRAPS) {
  1275   ResourceMark rm(THREAD);
  1277   assert(cls != NULL && super != NULL, "Need real classes");
  1279   InstanceKlass* current_class = InstanceKlass::cast(cls);
  1280   InstanceKlass* super_class = InstanceKlass::cast(super);
  1282   // Keep entire hierarchy alive for the duration of the computation
  1283   KeepAliveRegistrar keepAlive(THREAD);
  1284   KeepAliveVisitor loadKeepAlive(&keepAlive);
  1285   loadKeepAlive.run(current_class);   // get hierarchy from current class
  1287 #ifndef PRODUCT
  1288   if (TraceDefaultMethods) {
  1289     tty->print_cr("Finding super default method %s.%s%s from %s",
  1290       super_class->name()->as_C_string(),
  1291       method_name->as_C_string(), sig->as_C_string(),
  1292       current_class->name()->as_C_string());
  1294 #endif // ndef PRODUCT
  1296   assert(super_class->is_interface(), "only call for default methods");
  1298   Method* target = NULL;
  1299   if (ParseGenericDefaults) {
  1300     target = find_generic_super_default(current_class, super_class,
  1301                                         method_name, sig, CHECK_NULL);
  1302   } else {
  1303     target = find_erased_super_default(current_class, super_class,
  1304                                        method_name, sig, CHECK_NULL);
  1307 #ifndef PRODUCT
  1308   if (target != NULL) {
  1309     if (TraceDefaultMethods) {
  1310       tty->print("    Returning ");
  1311       print_method(tty, target, true);
  1312       tty->print_cr("");
  1315 #endif // ndef PRODUCT
  1316   return target;
  1319 #ifndef PRODUCT
  1320 // Return true is broad type is a covariant return of narrow type
  1321 static bool covariant_return_type(BasicType narrow, BasicType broad) {
  1322   if (narrow == broad) {
  1323     return true;
  1325   if (broad == T_OBJECT) {
  1326     return true;
  1328   return false;
  1330 #endif // ndef PRODUCT
  1332 static int assemble_redirect(
  1333     BytecodeConstantPool* cp, BytecodeBuffer* buffer,
  1334     Symbol* incoming, Method* target, TRAPS) {
  1336   BytecodeAssembler assem(buffer, cp);
  1338   SignatureStream in(incoming, true);
  1339   SignatureStream out(target->signature(), true);
  1340   u2 parameter_count = 0;
  1342   assem.aload(parameter_count++); // load 'this'
  1344   while (!in.at_return_type()) {
  1345     assert(!out.at_return_type(), "Parameter counts do not match");
  1346     BasicType bt = in.type();
  1347     assert(out.type() == bt, "Parameter types are not compatible");
  1348     assem.load(bt, parameter_count);
  1349     if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
  1350       assem.checkcast(out.as_symbol(THREAD));
  1351     } else if (bt == T_LONG || bt == T_DOUBLE) {
  1352       ++parameter_count; // longs and doubles use two slots
  1354     ++parameter_count;
  1355     in.next();
  1356     out.next();
  1358   assert(out.at_return_type(), "Parameter counts do not match");
  1359   assert(covariant_return_type(out.type(), in.type()), "Return types are not compatible");
  1361   if (parameter_count == 1 && (in.type() == T_LONG || in.type() == T_DOUBLE)) {
  1362     ++parameter_count; // need room for return value
  1364   if (target->method_holder()->is_interface()) {
  1365     assem.invokespecial(target);
  1366   } else {
  1367     assem.invokevirtual(target);
  1370   if (in.is_object() && in.as_symbol(THREAD) != out.as_symbol(THREAD)) {
  1371     assem.checkcast(in.as_symbol(THREAD));
  1373   assem._return(in.type());
  1374   return parameter_count;
  1377 static int assemble_abstract_method_error(
  1378     BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* message, TRAPS) {
  1380   Symbol* errorName = vmSymbols::java_lang_AbstractMethodError();
  1381   Symbol* init = vmSymbols::object_initializer_name();
  1382   Symbol* sig = vmSymbols::string_void_signature();
  1384   BytecodeAssembler assem(buffer, cp);
  1386   assem._new(errorName);
  1387   assem.dup();
  1388   assem.load_string(message);
  1389   assem.invokespecial(errorName, init, sig);
  1390   assem.athrow();
  1392   return 3; // max stack size: [ exception, exception, string ]
  1395 static Method* new_method(
  1396     BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,
  1397     Symbol* sig, AccessFlags flags, int max_stack, int params,
  1398     ConstMethod::MethodType mt, TRAPS) {
  1400   address code_start = 0;
  1401   int code_length = 0;
  1402   InlineTableSizes sizes;
  1404   if (bytecodes != NULL && bytecodes->length() > 0) {
  1405     code_start = static_cast<address>(bytecodes->adr_at(0));
  1406     code_length = bytecodes->length();
  1409   Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
  1410                                code_length, flags, &sizes,
  1411                                mt, CHECK_NULL);
  1413   m->set_constants(NULL); // This will get filled in later
  1414   m->set_name_index(cp->utf8(name));
  1415   m->set_signature_index(cp->utf8(sig));
  1416 #ifdef CC_INTERP
  1417   ResultTypeFinder rtf(sig);
  1418   m->set_result_index(rtf.type());
  1419 #endif
  1420   m->set_size_of_parameters(params);
  1421   m->set_max_stack(max_stack);
  1422   m->set_max_locals(params);
  1423   m->constMethod()->set_stackmap_data(NULL);
  1424   m->set_code(code_start);
  1425   m->set_force_inline(true);
  1427   return m;
  1430 static void switchover_constant_pool(BytecodeConstantPool* bpool,
  1431     InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {
  1433   if (new_methods->length() > 0) {
  1434     ConstantPool* cp = bpool->create_constant_pool(CHECK);
  1435     if (cp != klass->constants()) {
  1436       klass->class_loader_data()->add_to_deallocate_list(klass->constants());
  1437       klass->set_constants(cp);
  1438       cp->set_pool_holder(klass);
  1440       for (int i = 0; i < new_methods->length(); ++i) {
  1441         new_methods->at(i)->set_constants(cp);
  1443       for (int i = 0; i < klass->methods()->length(); ++i) {
  1444         Method* mo = klass->methods()->at(i);
  1445         mo->set_constants(cp);
  1451 // A "bridge" is a method created by javac to bridge the gap between
  1452 // an implementation and a generically-compatible, but different, signature.
  1453 // Bridges have actual bytecode implementation in classfiles.
  1454 // An "overpass", on the other hand, performs the same function as a bridge
  1455 // but does not occur in a classfile; the VM creates overpass itself,
  1456 // when it needs a path to get from a call site to an default method, and
  1457 // a bridge doesn't exist.
  1458 static void create_overpasses(
  1459     GrowableArray<EmptyVtableSlot*>* slots,
  1460     InstanceKlass* klass, TRAPS) {
  1462   GrowableArray<Method*> overpasses;
  1463   BytecodeConstantPool bpool(klass->constants());
  1465   for (int i = 0; i < slots->length(); ++i) {
  1466     EmptyVtableSlot* slot = slots->at(i);
  1468     if (slot->is_bound()) {
  1469       MethodFamily* method = slot->get_binding();
  1470       int max_stack = 0;
  1471       BytecodeBuffer buffer;
  1473 #ifndef PRODUCT
  1474       if (TraceDefaultMethods) {
  1475         tty->print("for slot: ");
  1476         slot->print_on(tty);
  1477         tty->print_cr("");
  1478         if (method->has_target()) {
  1479           method->print_selected(tty, 1);
  1480         } else {
  1481           method->print_exception(tty, 1);
  1484 #endif // ndef PRODUCT
  1485       if (method->has_target()) {
  1486         Method* selected = method->get_selected_target();
  1487         max_stack = assemble_redirect(
  1488             &bpool, &buffer, slot->signature(), selected, CHECK);
  1489       } else if (method->throws_exception()) {
  1490         max_stack = assemble_abstract_method_error(
  1491             &bpool, &buffer, method->get_exception_message(), CHECK);
  1493       AccessFlags flags = accessFlags_from(
  1494           JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);
  1495       Method* m = new_method(&bpool, &buffer, slot->name(), slot->signature(),
  1496           flags, max_stack, slot->size_of_parameters(),
  1497           ConstMethod::OVERPASS, CHECK);
  1498       if (m != NULL) {
  1499         overpasses.push(m);
  1504 #ifndef PRODUCT
  1505   if (TraceDefaultMethods) {
  1506     tty->print_cr("Created %d overpass methods", overpasses.length());
  1508 #endif // ndef PRODUCT
  1510   switchover_constant_pool(&bpool, klass, &overpasses, CHECK);
  1511   merge_in_new_methods(klass, &overpasses, CHECK);
  1514 static void sort_methods(GrowableArray<Method*>* methods) {
  1515   // Note that this must sort using the same key as is used for sorting
  1516   // methods in InstanceKlass.
  1517   bool sorted = true;
  1518   for (int i = methods->length() - 1; i > 0; --i) {
  1519     for (int j = 0; j < i; ++j) {
  1520       Method* m1 = methods->at(j);
  1521       Method* m2 = methods->at(j + 1);
  1522       if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
  1523         methods->at_put(j, m2);
  1524         methods->at_put(j + 1, m1);
  1525         sorted = false;
  1528     if (sorted) break;
  1529     sorted = true;
  1531 #ifdef ASSERT
  1532   uintptr_t prev = 0;
  1533   for (int i = 0; i < methods->length(); ++i) {
  1534     Method* mh = methods->at(i);
  1535     uintptr_t nv = (uintptr_t)mh->name();
  1536     assert(nv >= prev, "Incorrect overpass method ordering");
  1537     prev = nv;
  1539 #endif
  1542 static void merge_in_new_methods(InstanceKlass* klass,
  1543     GrowableArray<Method*>* new_methods, TRAPS) {
  1545   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
  1547   Array<Method*>* original_methods = klass->methods();
  1548   Array<int>* original_ordering = klass->method_ordering();
  1549   Array<int>* merged_ordering = Universe::the_empty_int_array();
  1551   int new_size = klass->methods()->length() + new_methods->length();
  1553   Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
  1554       klass->class_loader_data(), new_size, NULL, CHECK);
  1556   if (original_ordering != NULL && original_ordering->length() > 0) {
  1557     merged_ordering = MetadataFactory::new_array<int>(
  1558         klass->class_loader_data(), new_size, CHECK);
  1560   int method_order_index = klass->methods()->length();
  1562   sort_methods(new_methods);
  1564   // Perform grand merge of existing methods and new methods
  1565   int orig_idx = 0;
  1566   int new_idx = 0;
  1568   for (int i = 0; i < new_size; ++i) {
  1569     Method* orig_method = NULL;
  1570     Method* new_method = NULL;
  1571     if (orig_idx < original_methods->length()) {
  1572       orig_method = original_methods->at(orig_idx);
  1574     if (new_idx < new_methods->length()) {
  1575       new_method = new_methods->at(new_idx);
  1578     if (orig_method != NULL &&
  1579         (new_method == NULL || orig_method->name() < new_method->name())) {
  1580       merged_methods->at_put(i, orig_method);
  1581       original_methods->at_put(orig_idx, NULL);
  1582       if (merged_ordering->length() > 0) {
  1583         merged_ordering->at_put(i, original_ordering->at(orig_idx));
  1585       ++orig_idx;
  1586     } else {
  1587       merged_methods->at_put(i, new_method);
  1588       if (merged_ordering->length() > 0) {
  1589         merged_ordering->at_put(i, method_order_index++);
  1591       ++new_idx;
  1593     // update idnum for new location
  1594     merged_methods->at(i)->set_method_idnum(i);
  1597   // Verify correct order
  1598 #ifdef ASSERT
  1599   uintptr_t prev = 0;
  1600   for (int i = 0; i < merged_methods->length(); ++i) {
  1601     Method* mo = merged_methods->at(i);
  1602     uintptr_t nv = (uintptr_t)mo->name();
  1603     assert(nv >= prev, "Incorrect method ordering");
  1604     prev = nv;
  1606 #endif
  1608   // Replace klass methods with new merged lists
  1609   klass->set_methods(merged_methods);
  1610   klass->set_initial_method_idnum(new_size);
  1612   ClassLoaderData* cld = klass->class_loader_data();
  1613   MetadataFactory::free_array(cld, original_methods);
  1614   if (original_ordering->length() > 0) {
  1615     klass->set_method_ordering(merged_ordering);
  1616     MetadataFactory::free_array(cld, original_ordering);

mercurial