1 /*
  2  * Copyright (c) 2025, 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_OOPS_TRAININGDATA_HPP
 26 #define SHARE_OOPS_TRAININGDATA_HPP
 27 
 28 #include "cds/cdsConfig.hpp"
 29 #include "classfile/classLoaderData.hpp"
 30 #include "classfile/compactHashtable.hpp"
 31 #include "compiler/compilerDefinitions.hpp"
 32 #include "compiler/compiler_globals.hpp"
 33 #include "memory/allocation.hpp"
 34 #include "memory/metaspaceClosure.hpp"
 35 #include "oops/instanceKlass.hpp"
 36 #include "oops/method.hpp"
 37 #include "runtime/handles.hpp"
 38 #include "runtime/mutexLocker.hpp"
 39 #include "utilities/count_leading_zeros.hpp"
 40 #include "utilities/resizeableResourceHash.hpp"
 41 
 42 class ciEnv;
 43 class ciBaseObject;
 44 class CompileTask;
 45 class CompileTrainingData;
 46 class KlassTrainingData;
 47 class MethodTrainingData;
 48 
 49 // Base class for all the training data varieties
 50 class TrainingData : public Metadata {
 51   friend KlassTrainingData;
 52   friend MethodTrainingData;
 53   friend CompileTrainingData;
 54 public:
 55   // Key is used to insert any TrainingData (TD) object into a hash tables. The key is currently a
 56   // pointer to a metaspace object the TD is associated with. For example,
 57   // for KlassTrainingData it's an InstanceKlass, for MethodTrainingData it's a Method.
 58   // The utility of the these hash tables is to be able to find a TD object for a given metaspace
 59   // metaspace object.
 60   class Key {
 61     mutable Metadata* _meta;
 62     // These guys can get to my constructors:
 63     friend TrainingData;
 64     friend KlassTrainingData;
 65     friend MethodTrainingData;
 66     friend CompileTrainingData;
 67 
 68     // The empty key
 69     Key() : _meta(nullptr) { }
 70     bool is_empty() const { return _meta == nullptr; }
 71   public:
 72     Key(Metadata* meta) : _meta(meta) { }
 73 
 74     static bool can_compute_cds_hash(const Key* const& k);
 75     static uint cds_hash(const Key* const& k);
 76     static unsigned hash(const Key* const& k) {
 77       return primitive_hash(k->meta());
 78     }
 79     static bool equals(const Key* const& k1, const Key* const& k2) {
 80       return k1->meta() == k2->meta();
 81     }
 82     static inline bool equals(TrainingData* value, const TrainingData::Key* key, int unused) {
 83       return equals(value->key(), key);
 84     }
 85     int cmp(const Key* that) const {
 86       auto m1 = this->meta();
 87       auto m2 = that->meta();
 88       if (m1 < m2) return -1;
 89       if (m1 > m2) return +1;
 90       return 0;
 91     }
 92     Metadata* meta() const { return _meta; }
 93     void metaspace_pointers_do(MetaspaceClosure *iter);
 94     void make_empty() const { _meta = nullptr; }
 95   };
 96 
 97   // TrainingDataLocker is used to guard read/write operations on non-MT-safe data structures.
 98   // It supports recursive locking and a read-only mode (in which case no locks are taken).
 99   // It is also a part of the TD collection termination protocol (see the "spanshot" field).
100   class TrainingDataLocker {
101     static volatile bool _snapshot; // If true we're not allocating new training data
102     static int _lock_mode;
103     const bool _recursive;
104     static void lock() {
105 #if INCLUDE_CDS
106       assert(_lock_mode != 0, "Forgot to call TrainingDataLocker::initialize()");
107       if (_lock_mode > 0) {
108         TrainingData_lock->lock();
109       }
110 #endif
111     }
112     static void unlock() {
113 #if INCLUDE_CDS
114       if (_lock_mode > 0) {
115         TrainingData_lock->unlock();
116       }
117 #endif
118     }
119     static bool safely_locked() {
120 #if INCLUDE_CDS
121       assert(_lock_mode != 0, "Forgot to call TrainingDataLocker::initialize()");
122       if (_lock_mode > 0) {
123         return is_self_locked();
124       } else {
125         return true;
126       }
127 #else
128       return true;
129 #endif
130     }
131     static bool is_self_locked() {
132       return CDS_ONLY(TrainingData_lock->owned_by_self()) NOT_CDS(false);
133     }
134 
135   public:
136     static void snapshot() {
137 #if INCLUDE_CDS
138       assert_locked();
139       _snapshot = true;
140 #endif
141     }
142     static bool can_add() {
143 #if INCLUDE_CDS
144       assert_locked();
145       return !_snapshot;
146 #else
147       return false;
148 #endif
149     }
150     static void initialize() {
151 #if INCLUDE_CDS
152       _lock_mode = need_data() ? +1 : -1;   // if -1, we go lock-free
153 #endif
154     }
155     static void assert_locked() {
156       assert(safely_locked(), "use under TrainingDataLocker");
157     }
158     static void assert_can_add() {
159       assert(can_add(), "Cannot add TrainingData objects");
160     }
161     TrainingDataLocker() : _recursive(is_self_locked()) {
162       if (!_recursive) {
163         lock();
164       }
165     }
166     ~TrainingDataLocker() {
167       if (!_recursive) {
168         unlock();
169       }
170     }
171   };
172 
173   // A set of TD objects that we collect during the training run.
174   class TrainingDataSet {
175     friend TrainingData;
176     ResizeableResourceHashtable<const Key*, TrainingData*,
177                                 AnyObj::C_HEAP, MemTag::mtCompiler,
178                                 &TrainingData::Key::hash,
179                                 &TrainingData::Key::equals>
180       _table;
181 
182   public:
183     template<typename... Arg>
184     TrainingDataSet(Arg... arg)
185       : _table(arg...) {
186     }
187     TrainingData* find(const Key* key) const {
188       TrainingDataLocker::assert_locked();
189       if (TrainingDataLocker::can_add()) {
190         auto res = _table.get(key);
191         return res == nullptr ? nullptr : *res;
192       }
193       return nullptr;
194     }
195     bool remove(const Key* key) {
196       return _table.remove(key);
197     }
198     TrainingData* install(TrainingData* td) {
199       TrainingDataLocker::assert_locked();
200       TrainingDataLocker::assert_can_add();
201       auto key = td->key();
202       if (key->is_empty()) {
203         return td;  // unkeyed TD not installed
204       }
205       bool created = false;
206       auto prior = _table.put_if_absent(key, td, &created);
207       if (prior == nullptr || *prior == td) {
208         return td;
209       }
210       assert(false, "no pre-existing elements allowed");
211       return *prior;
212     }
213     template<typename Function>
214     void iterate(const Function& fn) const { // lambda enabled API
215       iterate(const_cast<Function&>(fn));
216     }
217     template<typename Function>
218     void iterate(Function& fn) const { // lambda enabled API
219       return _table.iterate_all([&](const TrainingData::Key* k, TrainingData* td) { fn(td); });
220     }
221     int size() const { return _table.number_of_entries(); }
222 
223     void verify() const {
224       TrainingDataLocker::assert_locked();
225       iterate([&](TrainingData* td) { td->verify(); });
226     }
227   };
228 
229   // A widget to ensure that we visit TD object only once (TD objects can have pointer to
230   // other TD object that are sometimes circular).
231   class Visitor {
232     ResizeableResourceHashtable<TrainingData*, bool> _visited;
233   public:
234     Visitor(unsigned size) : _visited(size, 0x3fffffff) { }
235     bool is_visited(TrainingData* td) {
236       return _visited.contains(td);
237     }
238     void visit(TrainingData* td) {
239       bool created;
240       _visited.put_if_absent(td, &created);
241     }
242   };
243 
244   typedef OffsetCompactHashtable<const TrainingData::Key*, TrainingData*, TrainingData::Key::equals> TrainingDataDictionary;
245 private:
246   Key _key;
247 
248   // just forward all constructor arguments to the embedded key
249   template<typename... Arg>
250   TrainingData(Arg... arg)
251     : _key(arg...) { }
252 
253   // Container for recording TD during training run
254   static TrainingDataSet _training_data_set;
255   // Containter for replaying the training data (read-only, populated from the AOT image)
256   static TrainingDataDictionary _archived_training_data_dictionary;
257   // Container used for writing the AOT image
258   static TrainingDataDictionary _archived_training_data_dictionary_for_dumping;
259   class DumpTimeTrainingDataInfo {
260     TrainingData* _training_data;
261   public:
262     DumpTimeTrainingDataInfo() : DumpTimeTrainingDataInfo(nullptr) {}
263     DumpTimeTrainingDataInfo(TrainingData* training_data) : _training_data(training_data) {}
264     void metaspace_pointers_do(MetaspaceClosure* it) {
265       it->push(&_training_data);
266     }
267     TrainingData* training_data() {
268       return _training_data;
269     }
270   };
271   typedef GrowableArrayCHeap<DumpTimeTrainingDataInfo, mtClassShared> DumptimeTrainingDataDictionary;
272   // A temporary container that is used to accumulate and filter TD during dumping
273   static DumptimeTrainingDataDictionary* _dumptime_training_data_dictionary;
274 
275   static TrainingDataSet* training_data_set() { return &_training_data_set; }
276   static TrainingDataDictionary* archived_training_data_dictionary() { return &_archived_training_data_dictionary; }
277 
278  public:
279   // Returns the key under which this TD is installed, or else
280   // Key::EMPTY if it is not installed.
281   const Key* key() const { return &_key; }
282 
283   static bool have_data() { return AOTReplayTraining;  } // Going to read
284   static bool need_data() { return AOTRecordTraining;  } // Going to write
285   static bool assembling_data() { return have_data() && CDSConfig::is_dumping_final_static_archive() && CDSConfig::is_dumping_aot_linked_classes(); }
286 
287   template<typename Function>
288   static void iterate(const Function& fn) { iterate(const_cast<Function&>(fn)); }
289 
290   template<typename Function>
291   static void iterate(Function& fn) { // lambda enabled API
292     TrainingDataLocker l;
293     if (have_data()) {
294       archived_training_data_dictionary()->iterate(fn);
295     }
296     if (need_data()) {
297       training_data_set()->iterate(fn);
298     }
299   }
300 
301   virtual MethodTrainingData*   as_MethodTrainingData()  const { return nullptr; }
302   virtual KlassTrainingData*    as_KlassTrainingData()   const { return nullptr; }
303   virtual CompileTrainingData*  as_CompileTrainingData() const { return nullptr; }
304   bool is_MethodTrainingData()  const { return as_MethodTrainingData()  != nullptr; }
305   bool is_KlassTrainingData()   const { return as_KlassTrainingData()   != nullptr; }
306   bool is_CompileTrainingData() const { return as_CompileTrainingData() != nullptr; }
307 
308   virtual void prepare(Visitor& visitor) = 0;
309   virtual void cleanup(Visitor& visitor) = 0;
310 
311   static void initialize() NOT_CDS_RETURN;
312 
313   static void verify() NOT_CDS_RETURN;
314 
315   // Widget for recording dependencies, as an N-to-M graph relation,
316   // possibly cyclic.
317   template<typename E>
318   class DepList : public StackObj {
319     GrowableArrayCHeap<E, mtCompiler>* _deps_dyn;
320     Array<E>*                          _deps;
321   public:
322     DepList() {
323       _deps_dyn = nullptr;
324       _deps = nullptr;
325     }
326 
327     int length() const {
328       return (_deps_dyn != nullptr ? _deps_dyn->length()
329               : _deps   != nullptr ? _deps->length()
330               : 0);
331     }
332     E* adr_at(int i) const {
333       return (_deps_dyn != nullptr ? _deps_dyn->adr_at(i)
334               : _deps   != nullptr ? _deps->adr_at(i)
335               : nullptr);
336     }
337     E at(int i) const {
338       assert(i >= 0 && i < length(), "oob");
339       return *adr_at(i);
340     }
341     bool append_if_missing(E dep) {
342       if (_deps_dyn == nullptr) {
343         _deps_dyn = new GrowableArrayCHeap<E, mtCompiler>(10);
344         _deps_dyn->append(dep);
345         return true;
346       } else {
347         return _deps_dyn->append_if_missing(dep);
348       }
349     }
350     bool remove_if_existing(E dep) {
351       if (_deps_dyn != nullptr) {
352         return _deps_dyn->remove_if_existing(dep);
353       }
354       return false;
355     }
356     void clear() {
357       if (_deps_dyn != nullptr)  {
358         _deps_dyn->clear();
359       }
360     }
361     void append(E dep) {
362       if (_deps_dyn == nullptr) {
363         _deps_dyn = new GrowableArrayCHeap<E, mtCompiler>(10);
364       }
365       _deps_dyn->append(dep);
366     }
367     bool contains(E dep) {
368       for (int i = 0; i < length(); i++) {
369         if (dep == at(i)) {
370           return true; // found
371         }
372       }
373       return false; // not found
374     }
375 
376 #if INCLUDE_CDS
377     void remove_unshareable_info() {
378       _deps_dyn = nullptr;
379     }
380 #endif
381     void prepare(ClassLoaderData* loader_data);
382     void metaspace_pointers_do(MetaspaceClosure *iter);
383   };
384 
385   virtual void metaspace_pointers_do(MetaspaceClosure *iter);
386 
387   static void init_dumptime_table(TRAPS);
388 
389 #if INCLUDE_CDS
390   virtual void remove_unshareable_info() {}
391   static void iterate_roots(MetaspaceClosure* it);
392   static void dump_training_data();
393   static void cleanup_training_data();
394   static void serialize(SerializeClosure* soc);
395   static void print_archived_training_data_on(outputStream* st);
396   static TrainingData* lookup_archived_training_data(const Key* k);
397 #endif
398 
399   template<typename TrainingDataType, typename... ArgTypes>
400   static TrainingDataType* allocate(ArgTypes... args) {
401     assert(need_data() || have_data(), "");
402     if (TrainingDataLocker::can_add()) {
403       return new (mtClassShared) TrainingDataType(args...);
404     }
405     return nullptr;
406   }
407 };
408 
409 // Training data that is associated with an InstanceKlass
410 class KlassTrainingData : public TrainingData {
411   friend TrainingData;
412   friend CompileTrainingData;
413 
414   // Used by CDS. These classes need to access the private default constructor.
415   template <class T> friend class CppVtableTesterA;
416   template <class T> friend class CppVtableTesterB;
417   template <class T> friend class CppVtableCloner;
418 
419   // cross-link to live klass, or null if not loaded or encountered yet
420   InstanceKlass* _holder;
421   jobject _holder_mirror;   // extra link to prevent unloading by GC
422 
423   DepList<CompileTrainingData*> _comp_deps; // compiles that depend on me
424 
425   KlassTrainingData();
426   KlassTrainingData(InstanceKlass* klass);
427 
428   int comp_dep_count() const {
429     TrainingDataLocker::assert_locked();
430     return _comp_deps.length();
431   }
432   CompileTrainingData* comp_dep(int i) const {
433     TrainingDataLocker::assert_locked();
434     return _comp_deps.at(i);
435   }
436   void add_comp_dep(CompileTrainingData* ctd) {
437     TrainingDataLocker::assert_locked();
438      _comp_deps.append_if_missing(ctd);
439   }
440   void remove_comp_dep(CompileTrainingData* ctd) {
441     TrainingDataLocker::assert_locked();
442      _comp_deps.remove_if_existing(ctd);
443   }
444 
445  public:
446   Symbol* name() const {
447     precond(has_holder());
448     return holder()->name();
449   }
450   bool has_holder()       const { return _holder != nullptr; }
451   InstanceKlass* holder() const { return _holder; }
452 
453   static KlassTrainingData* make(InstanceKlass* holder,
454                                  bool null_if_not_found = false) NOT_CDS_RETURN_(nullptr);
455   static KlassTrainingData* find(InstanceKlass* holder) {
456     return make(holder, true);
457   }
458   virtual KlassTrainingData* as_KlassTrainingData() const { return const_cast<KlassTrainingData*>(this); };
459 
460   ClassLoaderData* class_loader_data() {
461     assert(has_holder(), "");
462     return holder()->class_loader_data();
463   }
464   void notice_fully_initialized() NOT_CDS_RETURN;
465 
466   void print_on(outputStream* st, bool name_only) const;
467   virtual void print_on(outputStream* st) const { print_on(st, false); }
468   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
469 
470   virtual void prepare(Visitor& visitor);
471   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
472 
473   MetaspaceObj::Type type() const {
474     return KlassTrainingDataType;
475   }
476 
477 #if INCLUDE_CDS
478   virtual void remove_unshareable_info();
479 #endif
480 
481   void metaspace_pointers_do(MetaspaceClosure *iter);
482 
483   int size() const {
484     return (int)align_metadata_size(align_up(sizeof(KlassTrainingData), BytesPerWord)/BytesPerWord);
485   }
486 
487   const char* internal_name() const {
488     return "{ klass training data }";
489   };
490 
491   void verify();
492 
493   static KlassTrainingData* allocate(InstanceKlass* holder) {
494     return TrainingData::allocate<KlassTrainingData>(holder);
495   }
496 
497   template<typename Function>
498   void iterate_comp_deps(Function fn) const { // lambda enabled API
499     TrainingDataLocker l;
500     for (int i = 0; i < comp_dep_count(); i++) {
501       fn(comp_dep(i));
502     }
503   }
504 };
505 
506 // Information about particular JIT tasks.
507 class CompileTrainingData : public TrainingData {
508   friend TrainingData;
509   friend KlassTrainingData;
510 
511   // Used by CDS. These classes need to access the private default constructor.
512   template <class T> friend class CppVtableTesterA;
513   template <class T> friend class CppVtableTesterB;
514   template <class T> friend class CppVtableCloner;
515 
516   MethodTrainingData* _method;
517   const short _level;
518   const int _compile_id;
519 
520   // classes that should be initialized before this JIT task runs
521   DepList<KlassTrainingData*> _init_deps;
522   // Number of uninitialized classes left, when it's 0, all deps are satisfied
523   volatile int _init_deps_left;
524 
525 public:
526   // ciRecords is a generic meachanism to memoize CI responses to arbitary queries. For each function we're interested in we record
527   // (return_value, argument_values) tuples in a list. Arguments are allowed to have Metaspace pointers in them.
528   class ciRecords {
529     template <typename... Ts> class Arguments {
530     public:
531       bool operator==(const Arguments<>&) const { return true; }
532       void metaspace_pointers_do(MetaspaceClosure *iter) { }
533     };
534     template <typename T, typename... Ts> class Arguments<T, Ts...> {
535     private:
536       T _first;
537       Arguments<Ts...> _remaining;
538 
539     public:
540       constexpr Arguments(const T& first, const Ts&... remaining) noexcept
541         : _first(first), _remaining(remaining...) {}
542       constexpr Arguments() noexcept : _first(), _remaining() {}
543       bool operator==(const Arguments<T, Ts...>& that) const {
544         return _first == that._first && _remaining == that._remaining;
545       }
546       template<typename U = T, ENABLE_IF(std::is_pointer<U>::value && std::is_base_of<MetaspaceObj, typename std::remove_pointer<U>::type>::value)>
547       void metaspace_pointers_do(MetaspaceClosure *iter) {
548         iter->push(&_first);
549         _remaining.metaspace_pointers_do(iter);
550       }
551       template<typename U = T, ENABLE_IF(!(std::is_pointer<U>::value && std::is_base_of<MetaspaceObj, typename std::remove_pointer<U>::type>::value))>
552       void metaspace_pointers_do(MetaspaceClosure *iter) {
553         _remaining.metaspace_pointers_do(iter);
554       }
555     };
556 
557     template <typename ReturnType, typename... Args> class ciMemoizedFunction : public StackObj {
558     public:
559       class OptionalReturnType {
560         bool _valid;
561         ReturnType _result;
562       public:
563         OptionalReturnType(bool valid, const ReturnType& result) : _valid(valid), _result(result) {}
564         bool is_valid() const { return _valid; }
565         ReturnType result() const { return _result; }
566       };
567     private:
568       typedef Arguments<Args...> ArgumentsType;
569       class Record : public MetaspaceObj {
570         ReturnType    _result;
571         ArgumentsType _arguments;
572       public:
573         Record(const ReturnType& result, const ArgumentsType& arguments) : _result(result), _arguments(arguments) {}
574         Record() { }
575         ReturnType result() const { return _result; }
576         ArgumentsType arguments() const { return _arguments; }
577         bool operator==(const Record& that) { return _arguments == that._arguments; }
578         void metaspace_pointers_do(MetaspaceClosure *iter) { _arguments.metaspace_pointers_do(iter); }
579       };
580       DepList<Record> _data;
581     public:
582       OptionalReturnType find(const Args&... args) {
583         ArgumentsType a(args...);
584         for (int i = 0; i < _data.length(); i++) {
585           if (_data.at(i).arguments() == a) {
586             return OptionalReturnType(true, _data.at(i).result());
587           }
588         }
589         return OptionalReturnType(false, ReturnType());
590       }
591       bool append_if_missing(const ReturnType& result, const Args&... args) {
592         return _data.append_if_missing(Record(result, ArgumentsType(args...)));
593       }
594 #if INCLUDE_CDS
595       void remove_unshareable_info() { _data.remove_unshareable_info(); }
596 #endif
597       void prepare(ClassLoaderData* loader_data) {
598         _data.prepare(loader_data);
599       }
600       void metaspace_pointers_do(MetaspaceClosure *iter) {
601         _data.metaspace_pointers_do(iter);
602       }
603     };
604 
605 
606 public:
607     // Record CI answers for the InlineSmallCode heuristic. It is importance since the heuristic is non-commutative and we may want to
608     // compile methods in a different order than in the training run.
609     typedef ciMemoizedFunction<int, MethodTrainingData*> ciMethod__inline_instructions_size_type;
610     ciMethod__inline_instructions_size_type ciMethod__inline_instructions_size;
611 #if INCLUDE_CDS
612     void remove_unshareable_info() {
613       ciMethod__inline_instructions_size.remove_unshareable_info();
614     }
615 #endif
616     void prepare(ClassLoaderData* loader_data) {
617       ciMethod__inline_instructions_size.prepare(loader_data);
618     }
619     void metaspace_pointers_do(MetaspaceClosure *iter) {
620       ciMethod__inline_instructions_size.metaspace_pointers_do(iter);
621     }
622   };
623 
624 private:
625   ciRecords _ci_records;
626 
627   CompileTrainingData();
628   CompileTrainingData(MethodTrainingData* mtd,
629                       int level,
630                       int compile_id)
631       : TrainingData(),  // empty key
632         _method(mtd), _level(level), _compile_id(compile_id), _init_deps_left(0) { }
633 public:
634   ciRecords& ci_records() { return _ci_records; }
635   static CompileTrainingData* make(CompileTask* task) NOT_CDS_RETURN_(nullptr);
636 
637   virtual CompileTrainingData* as_CompileTrainingData() const { return const_cast<CompileTrainingData*>(this); };
638 
639   MethodTrainingData* method() const { return _method; }
640 
641   int level() const { return _level; }
642 
643   int compile_id() const { return _compile_id; }
644 
645   int init_dep_count() const {
646     TrainingDataLocker::assert_locked();
647     return _init_deps.length();
648   }
649   KlassTrainingData* init_dep(int i) const {
650     TrainingDataLocker::assert_locked();
651     return _init_deps.at(i);
652   }
653   void add_init_dep(KlassTrainingData* ktd) {
654     TrainingDataLocker::assert_locked();
655     ktd->add_comp_dep(this);
656     _init_deps.append_if_missing(ktd);
657   }
658   void clear_init_deps() {
659     TrainingDataLocker::assert_locked();
660     for (int i = 0; i < _init_deps.length(); i++) {
661       _init_deps.at(i)->remove_comp_dep(this);
662     }
663     _init_deps.clear();
664   }
665   void dec_init_deps_left(KlassTrainingData* ktd);
666   int init_deps_left() const {
667     return Atomic::load(&_init_deps_left);
668   }
669   uint compute_init_deps_left(bool count_initialized = false);
670 
671   void notice_inlined_method(CompileTask* task, const methodHandle& method) NOT_CDS_RETURN;
672 
673   // The JIT looks at classes and objects too and can depend on their state.
674   // These simple calls just report the *possibility* of an observation.
675   void notice_jit_observation(ciEnv* env, ciBaseObject* what) NOT_CDS_RETURN;
676 
677   virtual void prepare(Visitor& visitor);
678   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
679 
680   void print_on(outputStream* st, bool name_only) const;
681   virtual void print_on(outputStream* st) const { print_on(st, false); }
682   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
683 
684 #if INCLUDE_CDS
685   virtual void remove_unshareable_info();
686 #endif
687 
688   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
689   virtual MetaspaceObj::Type type() const { return CompileTrainingDataType; }
690 
691   virtual const char* internal_name() const {
692     return "{ compile training data }";
693   };
694 
695   virtual int size() const {
696     return (int)align_metadata_size(align_up(sizeof(CompileTrainingData), BytesPerWord)/BytesPerWord);
697   }
698 
699   void verify();
700 
701   static CompileTrainingData* allocate(MethodTrainingData* mtd, int level, int compile_id) {
702     return TrainingData::allocate<CompileTrainingData>(mtd, level, compile_id);
703   }
704 };
705 
706 // Record information about a method at the time compilation is requested.
707 class MethodTrainingData : public TrainingData {
708   friend TrainingData;
709   friend CompileTrainingData;
710 
711   // Used by CDS. These classes need to access the private default constructor.
712   template <class T> friend class CppVtableTesterA;
713   template <class T> friend class CppVtableTesterB;
714   template <class T> friend class CppVtableCloner;
715 
716   KlassTrainingData* _klass;
717   Method* _holder;
718   CompileTrainingData* _last_toplevel_compiles[CompLevel_count - 1];
719   int _highest_top_level;
720   int _level_mask;  // bit-set of all possible levels
721   bool _was_toplevel;
722   // metadata snapshots of final state:
723   MethodCounters* _final_counters;
724   MethodData*     _final_profile;
725 
726   MethodTrainingData();
727   MethodTrainingData(Method* method, KlassTrainingData* ktd) : TrainingData(method) {
728     _klass = ktd;
729     _holder = method;
730     for (int i = 0; i < CompLevel_count - 1; i++) {
731       _last_toplevel_compiles[i] = nullptr;
732     }
733     _highest_top_level = CompLevel_none;
734     _level_mask = 0;
735     _was_toplevel = false;
736   }
737 
738   static int level_mask(int level) {
739     return ((level & 0xF) != level ? 0 : 1 << level);
740   }
741   static CompLevel highest_level(int mask) {
742     if (mask == 0)  return (CompLevel) 0;
743     int diff = (count_leading_zeros(level_mask(0)) - count_leading_zeros(mask));
744     return (CompLevel) diff;
745   }
746 
747  public:
748   KlassTrainingData* klass()  const { return _klass; }
749   bool has_holder()           const { return _holder != nullptr; }
750   Method* holder()            const { return _holder; }
751   bool only_inlined()         const { return !_was_toplevel; }
752   bool saw_level(CompLevel l) const { return (_level_mask & level_mask(l)) != 0; }
753   int highest_level()         const { return highest_level(_level_mask); }
754   int highest_top_level()     const { return _highest_top_level; }
755   MethodData* final_profile() const { return _final_profile; }
756 
757   Symbol* name() const {
758     precond(has_holder());
759     return holder()->name();
760   }
761   Symbol* signature() const {
762     precond(has_holder());
763     return holder()->signature();
764   }
765 
766   CompileTrainingData* last_toplevel_compile(int level) const {
767     if (level > CompLevel_none) {
768       return _last_toplevel_compiles[level - 1];
769     }
770     return nullptr;
771   }
772 
773   void notice_compilation(int level, bool inlined = false) {
774     if (!inlined) {
775       _was_toplevel = true;
776     }
777     _level_mask |= level_mask(level);
778   }
779 
780   void notice_toplevel_compilation(int level) {
781     _highest_top_level = MAX2(_highest_top_level, level);
782   }
783 
784   static MethodTrainingData* make(const methodHandle& method,
785                                   bool null_if_not_found = false,
786                                   bool use_cache = true) NOT_CDS_RETURN_(nullptr);
787   static MethodTrainingData* find_fast(const methodHandle& method) { return make(method, true, true); }
788   static MethodTrainingData* find(const methodHandle& method) { return make(method, true, false); }
789 
790   virtual MethodTrainingData* as_MethodTrainingData() const {
791     return const_cast<MethodTrainingData*>(this);
792   };
793 
794   void print_on(outputStream* st, bool name_only) const;
795   virtual void print_on(outputStream* st) const { print_on(st, false); }
796   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
797 
798   virtual void prepare(Visitor& visitor);
799   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
800 
801   template<typename Function>
802   void iterate_compiles(Function fn) const { // lambda enabled API
803     for (int i = 0; i < CompLevel_count - 1; i++) {
804       CompileTrainingData* ctd = _last_toplevel_compiles[i];
805       if (ctd != nullptr) {
806         fn(ctd);
807       }
808     }
809   }
810 
811   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
812   virtual MetaspaceObj::Type type() const { return MethodTrainingDataType; }
813 
814 #if INCLUDE_CDS
815   virtual void remove_unshareable_info();
816 #endif
817 
818   virtual int size() const {
819     return (int)align_metadata_size(align_up(sizeof(MethodTrainingData), BytesPerWord)/BytesPerWord);
820   }
821 
822   virtual const char* internal_name() const {
823     return "{ method training data }";
824   };
825 
826   void verify();
827 
828   static MethodTrainingData* allocate(Method* m, KlassTrainingData* ktd) {
829     return TrainingData::allocate<MethodTrainingData>(m, ktd);
830   }
831 };
832 #endif // SHARE_OOPS_TRAININGDATA_HPP