1 /*
  2  * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_CODE_DEPENDENCIES_HPP
 26 #define SHARE_CODE_DEPENDENCIES_HPP
 27 
 28 #include "ci/ciCallSite.hpp"
 29 #include "ci/ciKlass.hpp"
 30 #include "ci/ciMethod.hpp"
 31 #include "ci/ciMethodHandle.hpp"
 32 #include "code/compressedStream.hpp"
 33 #include "code/nmethod.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "runtime/safepointVerifiers.hpp"
 36 #include "utilities/growableArray.hpp"
 37 
 38 //** Dependencies represent assertions (approximate invariants) within
 39 // the runtime system, e.g. class hierarchy changes.  An example is an
 40 // assertion that a given method is not overridden; another example is
 41 // that a type has only one concrete subtype.  Compiled code which
 42 // relies on such assertions must be discarded if they are overturned
 43 // by changes in the runtime system.  We can think of these assertions
 44 // as approximate invariants, because we expect them to be overturned
 45 // very infrequently.  We are willing to perform expensive recovery
 46 // operations when they are overturned.  The benefit, of course, is
 47 // performing optimistic optimizations (!) on the object code.
 48 //
 49 // Changes in the class hierarchy due to dynamic linking or
 50 // class evolution can violate dependencies.  There is enough
 51 // indexing between classes and nmethods to make dependency
 52 // checking reasonably efficient.
 53 
 54 class ciEnv;
 55 class nmethod;
 56 class OopRecorder;
 57 class xmlStream;
 58 class CompileLog;
 59 class CompileTask;
 60 class DepChange;
 61 class   KlassDepChange;
 62 class     NewKlassDepChange;
 63 class     KlassInitDepChange;
 64 class   CallSiteDepChange;
 65 class NoSafepointVerifier;
 66 
 67 class Dependencies: public ResourceObj {
 68  public:
 69   // Note: In the comments on dependency types, most uses of the terms
 70   // subtype and supertype are used in a "non-strict" or "inclusive"
 71   // sense, and are starred to remind the reader of this fact.
 72   // Strict uses of the terms use the word "proper".
 73   //
 74   // Specifically, every class is its own subtype* and supertype*.
 75   // (This trick is easier than continually saying things like "Y is a
 76   // subtype of X or X itself".)
 77   //
 78   // Sometimes we write X > Y to mean X is a proper supertype of Y.
 79   // The notation X > {Y, Z} means X has proper subtypes Y, Z.
 80   // The notation X.m > Y means that Y inherits m from X, while
 81   // X.m > Y.m means Y overrides X.m.  A star denotes abstractness,
 82   // as *I > A, meaning (abstract) interface I is a super type of A,
 83   // or A.*m > B.m, meaning B.m implements abstract method A.m.
 84   //
 85   // In this module, the terms "subtype" and "supertype" refer to
 86   // Java-level reference type conversions, as detected by
 87   // "instanceof" and performed by "checkcast" operations.  The method
 88   // Klass::is_subtype_of tests these relations.  Note that "subtype"
 89   // is richer than "subclass" (as tested by Klass::is_subclass_of),
 90   // since it takes account of relations involving interface and array
 91   // types.
 92   //
 93   // To avoid needless complexity, dependencies involving array types
 94   // are not accepted.  If you need to make an assertion about an
 95   // array type, make the assertion about its corresponding element
 96   // types.  Any assertion that might change about an array type can
 97   // be converted to an assertion about its element type.
 98   //
 99   // Most dependencies are evaluated over a "context type" CX, which
100   // stands for the set Subtypes(CX) of every Java type that is a subtype*
101   // of CX.  When the system loads a new class or interface N, it is
102   // responsible for re-evaluating changed dependencies whose context
103   // type now includes N, that is, all super types of N.
104   //
105   enum DepType {
106     end_marker = 0,
107 
108     // An 'evol' dependency simply notes that the contents of the
109     // method were used.  If it evolves (is replaced), the nmethod
110     // must be recompiled.  No other dependencies are implied.
111     evol_method,
112     FIRST_TYPE = evol_method,
113 
114     // A context type CX is a leaf it if has no proper subtype.
115     leaf_type,
116 
117     // An abstract class CX has exactly one concrete subtype CC.
118     abstract_with_unique_concrete_subtype,
119 
120     // Given a method M1 and a context class CX, the set MM(CX, M1) of
121     // "concrete matching methods" in CX of M1 is the set of every
122     // concrete M2 for which it is possible to create an invokevirtual
123     // or invokeinterface call site that can reach either M1 or M2.
124     // That is, M1 and M2 share a name, signature, and vtable index.
125     // We wish to notice when the set MM(CX, M1) is just {M1}, or
126     // perhaps a set of two {M1,M2}, and issue dependencies on this.
127 
128     // The set MM(CX, M1) can be computed by starting with any matching
129     // concrete M2 that is inherited into CX, and then walking the
130     // subtypes* of CX looking for concrete definitions.
131 
132     // The parameters to this dependency are the method M1 and the
133     // context class CX.  M1 must be either inherited in CX or defined
134     // in a subtype* of CX.  It asserts that MM(CX, M1) is no greater
135     // than {M1}.
136     unique_concrete_method_2, // one unique concrete method under CX
137 
138     // In addition to the method M1 and the context class CX, the parameters
139     // to this dependency are the resolved class RC1 and the
140     // resolved method RM1. It asserts that MM(CX, M1, RC1, RM1)
141     // is no greater than {M1}. RC1 and RM1 are used to improve the precision
142     // of the analysis.
143     unique_concrete_method_4, // one unique concrete method under CX
144 
145     // This dependency asserts that interface CX has a unique implementor class.
146     unique_implementor, // one unique implementor under CX
147 
148     // This dependency asserts that no instances of class or it's
149     // subclasses require finalization registration.
150     no_finalizable_subclasses,
151 
152     // This dependency asserts when the CallSite.target value changed.
153     call_site_target_value,
154 
155     TYPE_LIMIT
156   };
157   enum {
158     LG2_TYPE_LIMIT = 4,  // assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT))
159 
160     // handy categorizations of dependency types:
161     all_types           = ((1 << TYPE_LIMIT) - 1) & ((~0u) << FIRST_TYPE),
162 
163     non_klass_types     = (1 << call_site_target_value),
164     klass_types         = all_types & ~non_klass_types,
165 
166     non_ctxk_types      = (1 << evol_method) | (1 << call_site_target_value),
167     implicit_ctxk_types = 0,
168     explicit_ctxk_types = all_types & ~(non_ctxk_types | implicit_ctxk_types),
169 
170     max_arg_count = 4,   // current maximum number of arguments (incl. ctxk)
171 
172     // A "context type" is a class or interface that
173     // provides context for evaluating a dependency.
174     // When present, it is one of the arguments (dep_context_arg).
175     //
176     // If a dependency does not have a context type, there is a
177     // default context, depending on the type of the dependency.
178     // This bit signals that a default context has been compressed away.
179     default_context_type_bit = (1<<LG2_TYPE_LIMIT)
180   };
181 
182   static const char* dep_name(DepType dept);
183   static int         dep_args(DepType dept);
184 
185   static bool is_klass_type(           DepType dept) { return dept_in_mask(dept, klass_types        ); }
186 
187   static bool has_explicit_context_arg(DepType dept) { return dept_in_mask(dept, explicit_ctxk_types); }
188   static bool has_implicit_context_arg(DepType dept) { return dept_in_mask(dept, implicit_ctxk_types); }
189 
190   static int           dep_context_arg(DepType dept) { return has_explicit_context_arg(dept) ? 0 : -1; }
191   static int  dep_implicit_context_arg(DepType dept) { return has_implicit_context_arg(dept) ? 0 : -1; }
192 
193   static void check_valid_dependency_type(DepType dept);
194 
195 #if INCLUDE_JVMCI
196   // A Metadata* or object value recorded in an OopRecorder
197   class DepValue {
198    private:
199     // Unique identifier of the value within the associated OopRecorder that
200     // encodes both the category of the value (0: invalid, positive: metadata, negative: object)
201     // and the index within a category specific array (metadata: index + 1, object: -(index + 1))
202     int _id;
203 
204    public:
205     DepValue() : _id(0) {}
206     DepValue(OopRecorder* rec, Metadata* metadata, DepValue* candidate = nullptr) {
207       assert(candidate == nullptr || candidate->is_metadata(), "oops");
208       if (candidate != nullptr && candidate->as_metadata(rec) == metadata) {
209         _id = candidate->_id;
210       } else {
211         _id = rec->find_index(metadata) + 1;
212       }
213     }
214     DepValue(OopRecorder* rec, jobject obj, DepValue* candidate = nullptr) {
215       assert(candidate == nullptr || candidate->is_object(), "oops");
216       if (candidate != nullptr && candidate->as_object(rec) == obj) {
217         _id = candidate->_id;
218       } else {
219         _id = -(rec->find_index(obj) + 1);
220       }
221     }
222 
223     // Used to sort values in ascending order of index() with metadata values preceding object values
224     int sort_key() const { return -_id; }
225 
226     bool operator == (const DepValue& other) const   { return other._id == _id; }
227 
228     bool is_valid() const             { return _id != 0; }
229     int  index() const                { assert(is_valid(), "oops"); return _id < 0 ? -(_id + 1) : _id - 1; }
230     bool is_metadata() const          { assert(is_valid(), "oops"); return _id > 0; }
231     bool is_object() const            { assert(is_valid(), "oops"); return _id < 0; }
232 
233     Metadata*  as_metadata(OopRecorder* rec) const    { assert(is_metadata(), "oops"); return rec->metadata_at(index()); }
234     Klass*     as_klass(OopRecorder* rec) const {
235       Metadata* m = as_metadata(rec);
236       assert(m != nullptr, "as_metadata returned nullptr");
237       assert(m->is_klass(), "oops");
238       return (Klass*) m;
239     }
240     Method*    as_method(OopRecorder* rec) const {
241       Metadata* m = as_metadata(rec);
242       assert(m != nullptr, "as_metadata returned nullptr");
243       assert(m->is_method(), "oops");
244       return (Method*) m;
245     }
246     jobject    as_object(OopRecorder* rec) const      { assert(is_object(), "oops"); return rec->oop_at(index()); }
247   };
248 #endif // INCLUDE_JVMCI
249 
250  private:
251   // State for writing a new set of dependencies:
252   GrowableArray<int>*       _dep_seen;  // (seen[h->ident] & (1<<dept))
253   GrowableArray<ciBaseObject*>*  _deps[TYPE_LIMIT];
254 #if INCLUDE_JVMCI
255   bool _using_dep_values;
256   GrowableArray<DepValue>*  _dep_values[TYPE_LIMIT];
257 #endif
258 
259   static const char* _dep_name[TYPE_LIMIT];
260   static int         _dep_args[TYPE_LIMIT];
261 
262   static bool dept_in_mask(DepType dept, int mask) {
263     return (int)dept >= 0 && dept < TYPE_LIMIT && ((1<<dept) & mask) != 0;
264   }
265 
266   bool note_dep_seen(int dept, ciBaseObject* x) {
267     assert(dept < BitsPerInt, "oob");
268     int x_id = x->ident();
269     assert(_dep_seen != nullptr, "deps must be writable");
270     int seen = _dep_seen->at_grow(x_id, 0);
271     _dep_seen->at_put(x_id, seen | (1<<dept));
272     // return true if we've already seen dept/x
273     return (seen & (1<<dept)) != 0;
274   }
275 
276 #if INCLUDE_JVMCI
277   bool note_dep_seen(int dept, DepValue x) {
278     assert(dept < BitsPerInt, "oops");
279     // place metadata deps at even indexes, object deps at odd indexes
280     int x_id = x.is_metadata() ? x.index() * 2 : (x.index() * 2) + 1;
281     assert(_dep_seen != nullptr, "deps must be writable");
282     int seen = _dep_seen->at_grow(x_id, 0);
283     _dep_seen->at_put(x_id, seen | (1<<dept));
284     // return true if we've already seen dept/x
285     return (seen & (1<<dept)) != 0;
286   }
287 #endif
288 
289   bool maybe_merge_ctxk(GrowableArray<ciBaseObject*>* deps,
290                         int ctxk_i, ciKlass* ctxk);
291 #if INCLUDE_JVMCI
292   bool maybe_merge_ctxk(GrowableArray<DepValue>* deps,
293                         int ctxk_i, DepValue ctxk);
294 #endif
295 
296   void sort_all_deps();
297   size_t estimate_size_in_bytes();
298 
299   // Initialize _deps, etc.
300   void initialize(ciEnv* env);
301 
302   // State for making a new set of dependencies:
303   OopRecorder* _oop_recorder;
304 
305   // Logging support
306   CompileLog* _log;
307 
308   address  _content_bytes;  // everything but the oop references, encoded
309   size_t   _size_in_bytes;
310 
311  public:
312   // Make a new empty dependencies set.
313   Dependencies(ciEnv* env) {
314     initialize(env);
315   }
316 #if INCLUDE_JVMCI
317   Dependencies(Arena* arena, OopRecorder* oop_recorder, CompileLog* log);
318 #endif
319 
320  private:
321   // Check for a valid context type.
322   // Enforce the restriction against array types.
323   static void check_ctxk(ciKlass* ctxk) {
324     assert(ctxk->is_instance_klass(), "java types only");
325   }
326   static void check_ctxk_concrete(ciKlass* ctxk) {
327     assert(is_concrete_klass(ctxk->as_instance_klass()), "must be concrete");
328   }
329   static void check_ctxk_abstract(ciKlass* ctxk) {
330     check_ctxk(ctxk);
331     assert(!is_concrete_klass(ctxk->as_instance_klass()), "must be abstract");
332   }
333   static void check_unique_method(ciKlass* ctxk, ciMethod* m) {
334     assert(!m->can_be_statically_bound(ctxk->as_instance_klass()) || ctxk->is_interface(), "redundant");
335   }
336   static void check_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk) {
337     assert(ctxk->implementor() == uniqk, "not a unique implementor");
338   }
339 
340   void assert_common_1(DepType dept, ciBaseObject* x);
341   void assert_common_2(DepType dept, ciBaseObject* x0, ciBaseObject* x1);
342   void assert_common_4(DepType dept, ciKlass* ctxk, ciBaseObject* x1, ciBaseObject* x2, ciBaseObject* x3);
343 
344  public:
345   // Adding assertions to a new dependency set at compile time:
346   void assert_evol_method(ciMethod* m);
347   void assert_leaf_type(ciKlass* ctxk);
348   void assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck);
349   void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm);
350   void assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm, ciKlass* resolved_klass, ciMethod* resolved_method);
351   void assert_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk);
352   void assert_has_no_finalizable_subclasses(ciKlass* ctxk);
353   void assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle);
354 #if INCLUDE_JVMCI
355  private:
356   static void check_ctxk(Klass* ctxk) {
357     assert(ctxk->is_instance_klass(), "java types only");
358   }
359   static void check_ctxk_abstract(Klass* ctxk) {
360     check_ctxk(ctxk);
361     assert(ctxk->is_abstract(), "must be abstract");
362   }
363   static void check_unique_method(Klass* ctxk, Method* m) {
364     assert(!m->can_be_statically_bound(InstanceKlass::cast(ctxk)), "redundant");
365   }
366 
367   void assert_common_1(DepType dept, DepValue x);
368   void assert_common_2(DepType dept, DepValue x0, DepValue x1);
369 
370  public:
371   void assert_evol_method(Method* m);
372   void assert_has_no_finalizable_subclasses(Klass* ctxk);
373   void assert_leaf_type(Klass* ctxk);
374   void assert_unique_implementor(InstanceKlass* ctxk, InstanceKlass* uniqk);
375   void assert_unique_concrete_method(Klass* ctxk, Method* uniqm);
376   void assert_abstract_with_unique_concrete_subtype(Klass* ctxk, Klass* conck);
377   void assert_call_site_target_value(oop callSite, oop methodHandle);
378 #endif // INCLUDE_JVMCI
379 
380   // Define whether a given method or type is concrete.
381   // These methods define the term "concrete" as used in this module.
382   // For this module, an "abstract" class is one which is non-concrete.
383   //
384   // Future optimizations may allow some classes to remain
385   // non-concrete until their first instantiation, and allow some
386   // methods to remain non-concrete until their first invocation.
387   // In that case, there would be a middle ground between concrete
388   // and abstract (as defined by the Java language and VM).
389   static bool is_concrete_klass(Klass* k);    // k is instantiable
390   static bool is_concrete_method(Method* m, Klass* k);  // m is invocable
391   static Klass* find_finalizable_subclass(InstanceKlass* ik);
392 
393   static bool is_concrete_root_method(Method* uniqm, InstanceKlass* ctxk);
394   static Klass* find_witness_AME(InstanceKlass* ctxk, Method* m, KlassDepChange* changes = nullptr);
395 
396   // These versions of the concreteness queries work through the CI.
397   // The CI versions are allowed to skew sometimes from the VM
398   // (oop-based) versions.  The cost of such a difference is a
399   // (safely) aborted compilation, or a deoptimization, or a missed
400   // optimization opportunity.
401   //
402   // In order to prevent spurious assertions, query results must
403   // remain stable within any single ciEnv instance.  (I.e., they must
404   // not go back into the VM to get their value; they must cache the
405   // bit in the CI, either eagerly or lazily.)
406   static bool is_concrete_klass(ciInstanceKlass* k); // k appears instantiable
407   static bool has_finalizable_subclass(ciInstanceKlass* k);
408 
409   // As a general rule, it is OK to compile under the assumption that
410   // a given type or method is concrete, even if it at some future
411   // point becomes abstract.  So dependency checking is one-sided, in
412   // that it permits supposedly concrete classes or methods to turn up
413   // as really abstract.  (This shouldn't happen, except during class
414   // evolution, but that's the logic of the checking.)  However, if a
415   // supposedly abstract class or method suddenly becomes concrete, a
416   // dependency on it must fail.
417 
418   // Checking old assertions at run-time (in the VM only):
419   static Klass* check_evol_method(Method* m);
420   static Klass* check_leaf_type(InstanceKlass* ctxk);
421   static Klass* check_abstract_with_unique_concrete_subtype(InstanceKlass* ctxk, Klass* conck, NewKlassDepChange* changes = nullptr);
422   static Klass* check_unique_implementor(InstanceKlass* ctxk, Klass* uniqk, NewKlassDepChange* changes = nullptr);
423   static Klass* check_unique_concrete_method(InstanceKlass* ctxk, Method* uniqm, NewKlassDepChange* changes = nullptr);
424   static Klass* check_unique_concrete_method(InstanceKlass* ctxk, Method* uniqm, Klass* resolved_klass, Method* resolved_method, KlassDepChange* changes = nullptr);
425   static Klass* check_has_no_finalizable_subclasses(InstanceKlass* ctxk, NewKlassDepChange* changes = nullptr);
426   static Klass* check_call_site_target_value(oop call_site, oop method_handle, CallSiteDepChange* changes = nullptr);
427   // A returned Klass* is nullptr if the dependency assertion is still
428   // valid.  A non-nullptr Klass* is a 'witness' to the assertion
429   // failure, a point in the class hierarchy where the assertion has
430   // been proven false.  For example, if check_leaf_type returns
431   // non-nullptr, the value is a subtype of the supposed leaf type.  This
432   // witness value may be useful for logging the dependency failure.
433   // Note that, when a dependency fails, there may be several possible
434   // witnesses to the failure.  The value returned from the check_foo
435   // method is chosen arbitrarily.
436 
437   // The 'changes' value, if non-null, requests a limited spot-check
438   // near the indicated recent changes in the class hierarchy.
439   // It is used by DepStream::spot_check_dependency_at.
440 
441   // Detecting possible new assertions:
442   static Klass*  find_unique_concrete_subtype(InstanceKlass* ctxk);
443   static Method* find_unique_concrete_method(InstanceKlass* ctxk, Method* m,
444                                              Klass** participant = nullptr); // out parameter
445   static Method* find_unique_concrete_method(InstanceKlass* ctxk, Method* m, Klass* resolved_klass, Method* resolved_method);
446 
447 #ifdef ASSERT
448   static bool verify_method_context(InstanceKlass* ctxk, Method* m);
449 #endif // ASSERT
450 
451   // Create the encoding which will be stored in an nmethod.
452   void encode_content_bytes();
453 
454   address content_bytes() {
455     assert(_content_bytes != nullptr, "encode it first");
456     return _content_bytes;
457   }
458   size_t size_in_bytes() {
459     assert(_content_bytes != nullptr, "encode it first");
460     return _size_in_bytes;
461   }
462 
463   void set_content(address content_bytes, int size_in_bytes) {
464     assert(_content_bytes == nullptr, "not intialized expected");
465     _content_bytes = content_bytes;
466     _size_in_bytes = size_in_bytes;
467   }
468 
469   OopRecorder* oop_recorder() { return _oop_recorder; }
470   CompileLog*  log()          { return _log; }
471 
472   void copy_to(nmethod* nm);
473 
474   static bool _verify_in_progress;  // turn off logging dependencies
475 
476   DepType validate_dependencies(CompileTask* task, char** failure_detail = nullptr);
477 
478   void log_all_dependencies();
479 
480   void log_dependency(DepType dept, GrowableArray<ciBaseObject*>* args) {
481     ResourceMark rm;
482     int argslen = args->length();
483     write_dependency_to(log(), dept, args);
484     guarantee(argslen == args->length(),
485               "args array cannot grow inside nested ResoureMark scope");
486   }
487 
488   void log_dependency(DepType dept,
489                       ciBaseObject* x0,
490                       ciBaseObject* x1 = nullptr,
491                       ciBaseObject* x2 = nullptr,
492                       ciBaseObject* x3 = nullptr) {
493     if (log() == nullptr) {
494       return;
495     }
496     ResourceMark rm;
497     GrowableArray<ciBaseObject*>* ciargs =
498                 new GrowableArray<ciBaseObject*>(dep_args(dept));
499     assert (x0 != nullptr, "no log x0");
500     ciargs->push(x0);
501 
502     if (x1 != nullptr) {
503       ciargs->push(x1);
504     }
505     if (x2 != nullptr) {
506       ciargs->push(x2);
507     }
508     if (x3 != nullptr) {
509       ciargs->push(x3);
510     }
511     assert(ciargs->length() == dep_args(dept), "");
512     log_dependency(dept, ciargs);
513   }
514 
515   class DepArgument : public ResourceObj {
516    private:
517     bool  _is_oop;
518     bool  _valid;
519     void* _value;
520    public:
521     DepArgument() : _is_oop(false), _valid(false), _value(nullptr) {}
522     DepArgument(oop v): _is_oop(true), _valid(true), _value(v) {}
523     DepArgument(Metadata* v): _is_oop(false), _valid(true), _value(v) {}
524 
525     bool is_null() const               { return _value == nullptr; }
526     bool is_oop() const                { return _is_oop; }
527     bool is_metadata() const           { return !_is_oop; }
528     bool is_klass() const              { return is_metadata() && metadata_value()->is_klass(); }
529     bool is_method() const             { return is_metadata() && metadata_value()->is_method(); }
530 
531     oop oop_value() const              { assert(_is_oop && _valid, "must be"); return cast_to_oop(_value); }
532     Metadata* metadata_value() const   { assert(!_is_oop && _valid, "must be"); return (Metadata*) _value; }
533   };
534 
535   static void print_dependency(DepType dept,
536                                GrowableArray<DepArgument>* args,
537                                Klass* witness = nullptr, outputStream* st = tty);
538 
539  private:
540   // helper for encoding common context types as zero:
541   static ciKlass* ctxk_encoded_as_null(DepType dept, ciBaseObject* x);
542 
543   static Klass* ctxk_encoded_as_null(DepType dept, Metadata* x);
544 
545   static void write_dependency_to(CompileLog* log,
546                                   DepType dept,
547                                   GrowableArray<ciBaseObject*>* args,
548                                   Klass* witness = nullptr);
549   static void write_dependency_to(CompileLog* log,
550                                   DepType dept,
551                                   GrowableArray<DepArgument>* args,
552                                   Klass* witness = nullptr);
553   static void write_dependency_to(xmlStream* xtty,
554                                   DepType dept,
555                                   GrowableArray<DepArgument>* args,
556                                   Klass* witness = nullptr);
557  public:
558   // Use this to iterate over an nmethod's dependency set.
559   // Works on new and old dependency sets.
560   // Usage:
561   //
562   // ;
563   // Dependencies::DepType dept;
564   // for (Dependencies::DepStream deps(nm); deps.next(); ) {
565   //   ...
566   // }
567   //
568   // The caller must be in the VM, since oops are not wrapped in handles.
569   class DepStream {
570   private:
571     nmethod*              _code;   // null if in a compiler thread
572     Dependencies*         _deps;   // null if not in a compiler thread
573     CompressedReadStream  _bytes;
574 #ifdef ASSERT
575     size_t                _byte_limit;
576 #endif
577 
578     // iteration variables:
579     DepType               _type;
580     int                   _xi[max_arg_count+1];
581 
582     void initial_asserts(size_t byte_limit) NOT_DEBUG({});
583 
584     inline Metadata* recorded_metadata_at(int i);
585     inline oop recorded_oop_at(int i);
586 
587     Klass* check_klass_dependency(KlassDepChange* changes);
588     Klass* check_new_klass_dependency(NewKlassDepChange* changes);
589     Klass* check_klass_init_dependency(KlassInitDepChange* changes);
590     Klass* check_call_site_dependency(CallSiteDepChange* changes);
591 
592     void trace_and_log_witness(Klass* witness);
593 
594   public:
595     DepStream(Dependencies* deps)
596       : _code(nullptr),
597         _deps(deps),
598         _bytes(deps->content_bytes())
599     {
600       initial_asserts(deps->size_in_bytes());
601     }
602     DepStream(nmethod* code)
603       : _code(code),
604         _deps(nullptr),
605         _bytes(code->dependencies_begin())
606     {
607       initial_asserts(code->dependencies_size());
608     }
609 
610     bool next();
611 
612     DepType type()               { return _type; }
613     bool is_oop_argument(int i)  { return type() == call_site_target_value; }
614     uintptr_t get_identifier(int i);
615 
616     int argument_count()         { return dep_args(type()); }
617     int argument_index(int i)    { assert(0 <= i && i < argument_count(), "oob");
618                                    return _xi[i]; }
619     Metadata* argument(int i);     // => recorded_oop_at(argument_index(i))
620     oop argument_oop(int i);         // => recorded_oop_at(argument_index(i))
621     InstanceKlass* context_type();
622 
623     bool is_klass_type()         { return Dependencies::is_klass_type(type()); }
624 
625     Method* method_argument(int i) {
626       Metadata* x = argument(i);
627       assert(x->is_method(), "type");
628       return (Method*) x;
629     }
630     Klass* type_argument(int i) {
631       Metadata* x = argument(i);
632       assert(x->is_klass(), "type");
633       return (Klass*) x;
634     }
635 
636     // The point of the whole exercise:  Is this dep still OK?
637     Klass* check_dependency() {
638       Klass* result = check_klass_dependency(nullptr);
639       if (result != nullptr)  return result;
640       return check_call_site_dependency(nullptr);
641     }
642 
643     // A lighter version:  Checks only around recent changes in a class
644     // hierarchy.  (See Universe::flush_dependents_on.)
645     Klass* spot_check_dependency_at(DepChange& changes);
646 
647     // Log the current dependency to xtty or compilation log.
648     void log_dependency(Klass* witness = nullptr);
649 
650     // Print the current dependency to tty.
651     void print_dependency(outputStream* st, Klass* witness = nullptr, bool verbose = false);
652   };
653   friend class Dependencies::DepStream;
654 
655   static void print_statistics();
656 };
657 
658 
659 class DependencySignature : public ResourceObj {
660  private:
661   int                   _args_count;
662   uintptr_t             _argument_hash[Dependencies::max_arg_count];
663   Dependencies::DepType _type;
664 
665  public:
666   DependencySignature(Dependencies::DepStream& dep) {
667     _args_count = dep.argument_count();
668     _type = dep.type();
669     for (int i = 0; i < _args_count; i++) {
670       _argument_hash[i] = dep.get_identifier(i);
671     }
672   }
673 
674   static bool     equals(DependencySignature const& s1, DependencySignature const& s2);
675   static unsigned hash  (DependencySignature const& s1) { return (unsigned)(s1.arg(0) >> 2); }
676 
677   int args_count()             const { return _args_count; }
678   uintptr_t arg(int idx)       const { return _argument_hash[idx]; }
679   Dependencies::DepType type() const { return _type; }
680 
681 };
682 
683 
684 // Every particular DepChange is a sub-class of this class.
685 class DepChange : public StackObj {
686  public:
687   // What kind of DepChange is this?
688   virtual bool is_klass_change()      const { return false; }
689   virtual bool is_new_klass_change()  const { return false; }
690   virtual bool is_klass_init_change() const { return false; }
691   virtual bool is_call_site_change()  const { return false; }
692 
693   // Subclass casting with assertions.
694   KlassDepChange*    as_klass_change() {
695     assert(is_klass_change(), "bad cast");
696     return (KlassDepChange*) this;
697   }
698   NewKlassDepChange* as_new_klass_change() {
699     assert(is_new_klass_change(), "bad cast");
700     return (NewKlassDepChange*) this;
701   }
702   KlassInitDepChange* as_klass_init_change() {
703     assert(is_klass_init_change(), "bad cast");
704     return (KlassInitDepChange*) this;
705   }
706   CallSiteDepChange* as_call_site_change() {
707     assert(is_call_site_change(), "bad cast");
708     return (CallSiteDepChange*) this;
709   }
710 
711   void print();
712   void print_on(outputStream* st);
713 
714  public:
715   enum ChangeType {
716     NO_CHANGE = 0,              // an uninvolved klass
717     Change_new_type,            // a newly loaded type
718     Change_new_sub,             // a super with a new subtype
719     Change_new_impl,            // an interface with a new implementation
720     CHANGE_LIMIT,
721     Start_Klass = CHANGE_LIMIT  // internal indicator for ContextStream
722   };
723 
724   // Usage:
725   // for (DepChange::ContextStream str(changes); str.next(); ) {
726   //   InstanceKlass* k = str.klass();
727   //   switch (str.change_type()) {
728   //     ...
729   //   }
730   // }
731   class ContextStream : public StackObj {
732    private:
733     DepChange&  _changes;
734     friend class DepChange;
735 
736     // iteration variables:
737     ChangeType     _change_type;
738     InstanceKlass* _klass;
739     Array<InstanceKlass*>* _ti_base;    // i.e., transitive_interfaces
740     int         _ti_index;
741     int         _ti_limit;
742 
743     // start at the beginning:
744     void start();
745 
746    public:
747     ContextStream(DepChange& changes)
748       : _changes(changes)
749     { start(); }
750 
751     ContextStream(DepChange& changes, NoSafepointVerifier& nsv)
752       : _changes(changes)
753       // the nsv argument makes it safe to hold oops like _klass
754     { start(); }
755 
756     bool next();
757 
758     ChangeType change_type()     { return _change_type; }
759     InstanceKlass* klass()       { return _klass; }
760   };
761   friend class DepChange::ContextStream;
762 };
763 
764 
765 // A class hierarchy change coming through the VM (under the Compile_lock).
766 // The change is structured as a single type with any number of supers
767 // and implemented interface types.  Other than the type, any of the
768 // super types can be context types for a relevant dependency, which the
769 // type could invalidate.
770 class KlassDepChange : public DepChange {
771  private:
772   // each change set is rooted in exactly one type (at present):
773   InstanceKlass* _type;
774 
775   void initialize();
776 
777  protected:
778   // notes the type, marks it and all its super-types
779   KlassDepChange(InstanceKlass* type) : _type(type) {
780     initialize();
781   }
782 
783   // cleans up the marks
784   ~KlassDepChange();
785 
786  public:
787   // What kind of DepChange is this?
788   virtual bool is_klass_change() const { return true; }
789 
790   InstanceKlass* type() { return _type; }
791 
792   // involves_context(k) is true if k == _type or any of its super types
793   bool involves_context(Klass* k);
794 };
795 
796 // A class hierarchy change: new type is loaded.
797 class NewKlassDepChange : public KlassDepChange {
798  public:
799   NewKlassDepChange(InstanceKlass* new_type) : KlassDepChange(new_type) {}
800 
801   // What kind of DepChange is this?
802   virtual bool is_new_klass_change() const { return true; }
803 
804   InstanceKlass* new_type() { return type(); }
805 };
806 
807 // Change in initialization state of a loaded class.
808 class KlassInitDepChange : public KlassDepChange {
809  public:
810   KlassInitDepChange(InstanceKlass* type) : KlassDepChange(type) {}
811 
812   // What kind of DepChange is this?
813   virtual bool is_klass_init_change() const { return true; }
814 };
815 
816 // A CallSite has changed its target.
817 class CallSiteDepChange : public DepChange {
818  private:
819   Handle _call_site;
820   Handle _method_handle;
821 
822  public:
823   CallSiteDepChange(Handle call_site, Handle method_handle);
824 
825   // What kind of DepChange is this?
826   virtual bool is_call_site_change() const { return true; }
827 
828   oop call_site()     const { return _call_site();     }
829   oop method_handle() const { return _method_handle(); }
830 };
831 
832 #endif // SHARE_CODE_DEPENDENCIES_HPP