1 /*
  2  * Copyright (c) 2025, 2026, 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 #include "cds/aotCompressedPointers.hpp"
 26 #include "cds/cdsConfig.hpp"
 27 #include "ci/ciEnv.hpp"
 28 #include "ci/ciMetadata.hpp"
 29 #include "classfile/compactHashtable.hpp"
 30 #include "classfile/javaClasses.hpp"
 31 #include "classfile/symbolTable.hpp"
 32 #include "classfile/systemDictionaryShared.hpp"
 33 #include "compiler/compileTask.hpp"
 34 #include "memory/metadataFactory.hpp"
 35 #include "memory/metaspaceClosure.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "memory/universe.hpp"
 38 #include "oops/method.hpp"
 39 #include "oops/method.inline.hpp"
 40 #include "oops/methodCounters.hpp"
 41 #include "oops/trainingData.hpp"
 42 #include "runtime/arguments.hpp"
 43 #include "runtime/javaThread.inline.hpp"
 44 #include "runtime/jniHandles.inline.hpp"
 45 #include "utilities/growableArray.hpp"
 46 
 47 TrainingData::TrainingDataSet TrainingData::_training_data_set(1024, 0x3fffffff);
 48 TrainingData::TrainingDataDictionary TrainingData::_archived_training_data_dictionary;
 49 TrainingData::TrainingDataDictionary TrainingData::_archived_training_data_dictionary_for_dumping;
 50 TrainingData::DumptimeTrainingDataDictionary* TrainingData::_dumptime_training_data_dictionary = nullptr;
 51 int TrainingData::TrainingDataLocker::_lock_mode;
 52 volatile bool TrainingData::TrainingDataLocker::_snapshot = false;
 53 
 54 MethodTrainingData::MethodTrainingData() {
 55   // Used by cppVtables.cpp only
 56   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 57 }
 58 
 59 KlassTrainingData::KlassTrainingData() {
 60   // Used by cppVtables.cpp only
 61   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 62 }
 63 
 64 CompileTrainingData::CompileTrainingData() : _level(-1), _compile_id(-1) {
 65   // Used by cppVtables.cpp only
 66   assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
 67 }
 68 
 69 void TrainingData::initialize() {
 70   // this is a nop if training modes are not enabled
 71   if (have_data() || need_data()) {
 72     // Data structures that we have do not currently support iterative training. So you cannot replay
 73     // and train at the same time. Going forward we may want to adjust iteration/search to enable that.
 74     guarantee(have_data() != need_data(), "Iterative training is not supported");
 75     TrainingDataLocker::initialize();
 76   }
 77 }
 78 
 79 static void verify_archived_entry(TrainingData* td, const TrainingData::Key* k) {
 80   guarantee(TrainingData::Key::can_compute_cds_hash(k), "");
 81   TrainingData* td1 = TrainingData::lookup_archived_training_data(k);
 82   guarantee(td == td1, "");
 83 }
 84 
 85 void TrainingData::verify() {
 86   if (TrainingData::have_data() && !TrainingData::assembling_data()) {
 87     archived_training_data_dictionary()->iterate_all([&](TrainingData* td) {
 88       if (td->is_KlassTrainingData()) {
 89         KlassTrainingData* ktd = td->as_KlassTrainingData();
 90         if (ktd->has_holder() && ktd->holder()->is_loaded()) {
 91           Key k(ktd->holder());
 92           verify_archived_entry(td, &k);
 93         }
 94         ktd->verify();
 95       } else if (td->is_MethodTrainingData()) {
 96         MethodTrainingData* mtd = td->as_MethodTrainingData();
 97         if (mtd->has_holder() && mtd->holder()->method_holder()->is_loaded()) {
 98           Key k(mtd->holder());
 99           verify_archived_entry(td, &k);
100         }
101         mtd->verify(/*verify_dep_counter*/true);
102       }
103     });
104   }
105   if (TrainingData::need_data()) {
106     TrainingDataLocker l;
107     training_data_set()->iterate([&](TrainingData* td) {
108       if (td->is_KlassTrainingData()) {
109         KlassTrainingData* ktd = td->as_KlassTrainingData();
110         ktd->verify();
111       } else if (td->is_MethodTrainingData()) {
112         MethodTrainingData* mtd = td->as_MethodTrainingData();
113         // During the training run init deps tracking is not setup yet,
114         // don't verify it.
115         mtd->verify(/*verify_dep_counter*/false);
116       }
117     });
118   }
119 }
120 
121 MethodTrainingData* MethodTrainingData::make(const methodHandle& method, bool null_if_not_found, bool use_cache) {
122   MethodTrainingData* mtd = nullptr;
123   if (!have_data() && !need_data()) {
124     return mtd;
125   }
126   // Try grabbing the cached value first.
127   // Cache value is stored in MethodCounters and the following are the
128   // possible states:
129   // 1. Cached value is method_training_data_sentinel().
130   //    This is an initial state and needs a full lookup.
131   // 2. Cached value is null.
132   //    Lookup failed the last time, if we don't plan to create a new TD object,
133   //    i.e. null_if_no_found == true, then just return a null.
134   // 3. Cache value is not null.
135   //    Return it, the value of training_data_lookup_failed doesn't matter.
136   MethodCounters* mcs = method->method_counters();
137   if (mcs != nullptr) {
138     mtd = mcs->method_training_data();
139     if (mtd != nullptr && mtd != mcs->method_training_data_sentinel()) {
140       return mtd;
141     }
142     if (null_if_not_found && mtd == nullptr) {
143       assert(mtd == nullptr, "No training data found");
144       return nullptr;
145     }
146   } else if (use_cache) {
147     mcs = Method::build_method_counters(Thread::current(), method());
148   }
149 
150   TrainingData* td = nullptr;
151 
152   Key key(method());
153   if (have_data()) {
154     td = lookup_archived_training_data(&key);
155     if (td != nullptr) {
156       mtd = td->as_MethodTrainingData();
157     } else {
158       mtd = nullptr;
159     }
160     // Cache the pointer to MTD in MethodCounters for faster lookup (could be null if not found)
161     method->init_training_data(mtd);
162   }
163 
164   if (need_data()) {
165     TrainingDataLocker l;
166     td = training_data_set()->find(&key);
167     if (td == nullptr) {
168       if (!null_if_not_found) {
169         KlassTrainingData* ktd = KlassTrainingData::make(method->method_holder());
170         if (ktd == nullptr) {
171           return nullptr; // allocation failure
172         }
173         mtd = MethodTrainingData::allocate(method(), ktd);
174         if (mtd == nullptr) {
175           return nullptr; // allocation failure
176         }
177         td = training_data_set()->install(mtd);
178         assert(td == mtd, "");
179       } else {
180         mtd = nullptr;
181       }
182     } else {
183       mtd = td->as_MethodTrainingData();
184     }
185     // Cache the pointer to MTD in MethodCounters for faster lookup (could be null if not found)
186     method->init_training_data(mtd);
187   }
188 
189   return mtd;
190 }
191 
192 void MethodTrainingData::print_on(outputStream* st, bool name_only) const {
193   if (has_holder()) {
194     _klass->print_on(st, true);
195     st->print(".");
196     name()->print_symbol_on(st);
197     signature()->print_symbol_on(st);
198   }
199   if (name_only) {
200     return;
201   }
202   if (!has_holder()) {
203     st->print("[SYM]");
204   }
205   if (_level_mask) {
206     st->print(" LM%d", _level_mask);
207   }
208   st->print(" mc=%p mdo=%p", _final_counters, _final_profile);
209 }
210 
211 CompileTrainingData* CompileTrainingData::make(CompileTask* task) {
212   int level = task->comp_level();
213   int compile_id = task->compile_id();
214   Thread* thread = Thread::current();
215   methodHandle m(thread, task->method());
216   if (m->method_holder() == nullptr) {
217     return nullptr; // do not record (dynamically generated method)
218   }
219   MethodTrainingData* mtd = MethodTrainingData::make(m);
220   if (mtd == nullptr) {
221     return nullptr; // allocation failure
222   }
223   mtd->notice_compilation(level);
224 
225   TrainingDataLocker l;
226   CompileTrainingData* ctd = CompileTrainingData::allocate(mtd, level, compile_id);
227   if (ctd != nullptr) {
228     CompileTrainingData*& last_ctd = mtd->_last_toplevel_compiles[level - 1];
229     if (last_ctd != nullptr) {
230       assert(mtd->highest_top_level() >= level, "consistency");
231       if (last_ctd->compile_id() < compile_id) {
232         last_ctd->clear_init_deps();
233         last_ctd = ctd;
234       }
235     } else {
236       last_ctd = ctd;
237       mtd->notice_toplevel_compilation(level);
238     }
239   }
240   return ctd;
241 }
242 
243 
244 void CompileTrainingData::dec_init_deps_left_release(KlassTrainingData* ktd) {
245   LogStreamHandle(Trace, training) log;
246   if (log.is_enabled()) {
247     log.print("CTD "); print_on(&log); log.cr();
248     log.print("KTD "); ktd->print_on(&log); log.cr();
249   }
250   assert(ktd!= nullptr && ktd->has_holder(), "");
251   assert(_init_deps.contains(ktd), "");
252   assert(_init_deps_left > 0, "");
253 
254   uint init_deps_left1 = AtomicAccess::sub(&_init_deps_left, 1);
255 
256   if (log.is_enabled()) {
257     uint init_deps_left2 = compute_init_deps_left();
258     log.print("init_deps_left: %d (%d)", init_deps_left1, init_deps_left2);
259     ktd->print_on(&log, true);
260   }
261 }
262 
263 uint CompileTrainingData::compute_init_deps_left(bool count_initialized) {
264   int left = 0;
265   for (int i = 0; i < _init_deps.length(); i++) {
266     KlassTrainingData* ktd = _init_deps.at(i);
267     // Ignore symbolic refs and already initialized classes (unless explicitly requested).
268     if (ktd->has_holder()) {
269       InstanceKlass* holder = ktd->holder();
270       if (!ktd->holder()->is_initialized() || count_initialized) {
271         ++left;
272       } else if (holder->defined_by_other_loaders()) {
273         Key k(holder);
274         if (CDS_ONLY(!Key::can_compute_cds_hash(&k)) NOT_CDS(true)) {
275           ++left;
276         }
277       }
278     }
279   }
280   return left;
281 }
282 
283 void CompileTrainingData::print_on(outputStream* st, bool name_only) const {
284   _method->print_on(st, true);
285   st->print("#%dL%d", _compile_id, _level);
286   if (name_only) {
287     return;
288   }
289   if (_init_deps.length() > 0) {
290     if (_init_deps_left > 0) {
291       st->print(" udeps=%d", _init_deps_left);
292     }
293     for (int i = 0, len = _init_deps.length(); i < len; i++) {
294       st->print(" dep:");
295       _init_deps.at(i)->print_on(st, true);
296     }
297   }
298 }
299 
300 void CompileTrainingData::notice_inlined_method(CompileTask* task,
301                                                 const methodHandle& method) {
302   MethodTrainingData* mtd = MethodTrainingData::make(method);
303   if (mtd != nullptr) {
304     mtd->notice_compilation(task->comp_level(), true);
305   }
306 }
307 
308 void CompileTrainingData::notice_jit_observation(ciEnv* env, ciBaseObject* what) {
309   // A JIT is starting to look at class k.
310   // We could follow the queries that it is making, but it is
311   // simpler to assume, conservatively, that the JIT will
312   // eventually depend on the initialization state of k.
313   CompileTask* task = env->task();
314   assert(task != nullptr, "");
315   Method* method = task->method();
316   if (what->is_metadata()) {
317     ciMetadata* md = what->as_metadata();
318     if (md->is_loaded() && md->is_instance_klass()) {
319       ciInstanceKlass* cik = md->as_instance_klass();
320 
321       if (cik->is_initialized()) {
322         InstanceKlass* ik = md->as_instance_klass()->get_instanceKlass();
323         KlassTrainingData* ktd = KlassTrainingData::make(ik);
324         if (ktd == nullptr) {
325           // Allocation failure or snapshot in progress
326           return;
327         }
328         // This JIT task is (probably) requesting that ik be initialized,
329         // so add him to my _init_deps list.
330         TrainingDataLocker l;
331         if (l.can_add()) {
332           add_init_dep(ktd);
333         }
334       }
335     }
336   }
337 }
338 
339 void KlassTrainingData::prepare(Visitor& visitor) {
340   if (visitor.is_visited(this)) {
341     return;
342   }
343   visitor.visit(this);
344   _comp_deps.prepare();
345 }
346 
347 void MethodTrainingData::prepare(Visitor& visitor) {
348   if (visitor.is_visited(this)) {
349     return;
350   }
351   visitor.visit(this);
352   klass()->prepare(visitor);
353   if (has_holder()) {
354     _final_counters = holder()->method_counters();
355     _final_profile  = holder()->method_data();
356     assert(_final_profile == nullptr || _final_profile->method() == holder(), "");
357     _invocation_count = holder()->invocation_count();
358     _backedge_count = holder()->backedge_count();
359   }
360   for (int i = 0; i < CompLevel_count - 1; i++) {
361     CompileTrainingData* ctd = _last_toplevel_compiles[i];
362     if (ctd != nullptr) {
363       ctd->prepare(visitor);
364     }
365   }
366 }
367 
368 void CompileTrainingData::prepare(Visitor& visitor) {
369   if (visitor.is_visited(this)) {
370     return;
371   }
372   visitor.visit(this);
373   method()->prepare(visitor);
374   _init_deps.prepare();
375   _ci_records.prepare();
376 }
377 
378 KlassTrainingData* KlassTrainingData::make(InstanceKlass* holder, bool null_if_not_found) {
379   Key key(holder);
380   TrainingData* td = CDS_ONLY(have_data() ? lookup_archived_training_data(&key) :) nullptr;
381   KlassTrainingData* ktd = nullptr;
382   if (td != nullptr) {
383     ktd = td->as_KlassTrainingData();
384     guarantee(!ktd->has_holder() || ktd->holder() == holder, "");
385     if (ktd->has_holder()) {
386       return ktd;
387     } else {
388       ktd = nullptr;
389     }
390   }
391   if (need_data()) {
392     TrainingDataLocker l;
393     td = training_data_set()->find(&key);
394     if (td == nullptr) {
395       if (null_if_not_found) {
396         return nullptr;
397       }
398       ktd = KlassTrainingData::allocate(holder);
399       if (ktd == nullptr) {
400         return nullptr; // allocation failure
401       }
402       td = training_data_set()->install(ktd);
403       assert(ktd == td, "");
404     } else {
405       ktd = td->as_KlassTrainingData();
406       guarantee(ktd->holder() != nullptr, "null holder");
407     }
408     assert(ktd != nullptr, "");
409     guarantee(ktd->holder() == holder, "");
410   }
411   return ktd;
412 }
413 
414 void KlassTrainingData::print_on(outputStream* st, bool name_only) const {
415   if (has_holder()) {
416     name()->print_symbol_on(st);
417     switch (holder()->init_state()) {
418       case InstanceKlass::allocated:            st->print("[A]"); break;
419       case InstanceKlass::loaded:               st->print("[D]"); break;
420       case InstanceKlass::linked:               st->print("[L]"); break;
421       case InstanceKlass::being_initialized:    st->print("[i]"); break;
422       case InstanceKlass::fully_initialized:                      break;
423       case InstanceKlass::initialization_error: st->print("[E]"); break;
424       default: fatal("unknown state: %d", holder()->init_state());
425     }
426     if (holder()->is_interface()) {
427       st->print("I");
428     }
429   } else {
430     st->print("[SYM]");
431   }
432   if (name_only) {
433     return;
434   }
435   if (_comp_deps.length() > 0) {
436     for (int i = 0, len = _comp_deps.length(); i < len; i++) {
437       st->print(" dep:");
438       _comp_deps.at(i)->print_on(st, true);
439     }
440   }
441 }
442 
443 KlassTrainingData::KlassTrainingData(InstanceKlass* klass) : TrainingData(klass) {
444   assert(klass != nullptr, "");
445   // The OopHandle constructor will allocate a handle. We don't need to ever release it so we don't preserve
446   // the handle object.
447   OopHandle handle(Universe::vm_global(), klass->java_mirror());
448   _holder = klass;
449   assert(holder() == klass, "");
450 }
451 
452 void KlassTrainingData::notice_fully_initialized() {
453   ResourceMark rm;
454   assert(has_holder(), "");
455   assert(holder()->is_initialized(), "wrong state: %s %s",
456          holder()->name()->as_C_string(), holder()->init_state_name());
457 
458   TrainingDataLocker l; // Not a real lock if we don't collect the data,
459                         // that's why we need the atomic decrement below.
460   for (int i = 0; i < comp_dep_count(); i++) {
461     comp_dep(i)->dec_init_deps_left_release(this);
462   }
463   holder()->set_has_init_deps_processed();
464 }
465 
466 void TrainingData::init_dumptime_table(TRAPS) {
467   precond((!assembling_data() && !need_data()) || need_data() != assembling_data());
468   if (assembling_data()) {
469     _dumptime_training_data_dictionary = new DumptimeTrainingDataDictionary();
470     _archived_training_data_dictionary.iterate_all([&](TrainingData* record) {
471       _dumptime_training_data_dictionary->append(record);
472     });
473   }
474   if (need_data()) {
475     _dumptime_training_data_dictionary = new DumptimeTrainingDataDictionary();
476     TrainingDataLocker l;
477     TrainingDataLocker::snapshot();
478     ResourceMark rm;
479     Visitor visitor(training_data_set()->size());
480     training_data_set()->iterate([&](TrainingData* td) {
481       td->prepare(visitor);
482       if (!td->is_CompileTrainingData()) {
483         _dumptime_training_data_dictionary->append(td);
484       }
485     });
486   }
487 
488   if (AOTVerifyTrainingData) {
489     TrainingData::verify();
490   }
491 }
492 
493 void TrainingData::iterate_roots(MetaspaceClosure* it) {
494   if (_dumptime_training_data_dictionary != nullptr) {
495     for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) {
496       _dumptime_training_data_dictionary->at(i).metaspace_pointers_do(it);
497     }
498   }
499 }
500 
501 void TrainingData::dump_training_data() {
502   if (_dumptime_training_data_dictionary != nullptr) {
503     CompactHashtableStats stats;
504     _archived_training_data_dictionary_for_dumping.reset();
505     CompactHashtableWriter writer(_dumptime_training_data_dictionary->length(), &stats);
506     for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) {
507       TrainingData* td = _dumptime_training_data_dictionary->at(i).training_data();
508 #ifdef ASSERT
509       for (int j = i+1; j < _dumptime_training_data_dictionary->length(); j++) {
510         TrainingData* td1 = _dumptime_training_data_dictionary->at(j).training_data();
511         assert(!TrainingData::Key::equals(td1, td->key(), -1), "conflict");
512       }
513 #endif // ASSERT
514       td = ArchiveBuilder::current()->get_buffered_addr(td);
515       uint hash = TrainingData::Key::cds_hash(td->key());
516       writer.add(hash, AOTCompressedPointers::encode_not_null(td));
517     }
518     writer.dump(&_archived_training_data_dictionary_for_dumping, "training data dictionary");
519   }
520 }
521 
522 void TrainingData::cleanup_training_data() {
523   if (_dumptime_training_data_dictionary != nullptr) {
524     ResourceMark rm;
525     Visitor visitor(_dumptime_training_data_dictionary->length());
526     for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) {
527       TrainingData* td = _dumptime_training_data_dictionary->at(i).training_data();
528       td->cleanup(visitor);
529     }
530     // Throw away all elements with empty keys
531     int j = 0;
532     for (int i = 0; i < _dumptime_training_data_dictionary->length(); i++) {
533       TrainingData* td = _dumptime_training_data_dictionary->at(i).training_data();
534       if (td->key()->is_empty()) {
535         continue;
536       }
537       if (i != j) { // no need to copy if it's the same
538         _dumptime_training_data_dictionary->at_put(j, td);
539       }
540       j++;
541     }
542     _dumptime_training_data_dictionary->trunc_to(j);
543   }
544 }
545 
546 void KlassTrainingData::cleanup(Visitor& visitor) {
547   if (visitor.is_visited(this)) {
548     return;
549   }
550   visitor.visit(this);
551   if (has_holder()) {
552     bool is_excluded = !holder()->is_loaded();
553     if (CDSConfig::is_at_aot_safepoint()) {
554       // Check for AOT exclusion only at AOT safe point.
555       is_excluded |= SystemDictionaryShared::should_be_excluded(holder());
556     }
557     if (is_excluded) {
558       ResourceMark rm;
559       log_debug(aot, training)("Cleanup KTD %s", name()->as_klass_external_name());
560       _holder = nullptr;
561       key()->make_empty();
562     }
563   }
564   for (int i = 0; i < _comp_deps.length(); i++) {
565     _comp_deps.at(i)->cleanup(visitor);
566   }
567 }
568 
569 void MethodTrainingData::cleanup(Visitor& visitor) {
570   if (visitor.is_visited(this)) {
571     return;
572   }
573   visitor.visit(this);
574   if (has_holder()) {
575     if (CDSConfig::is_at_aot_safepoint() && SystemDictionaryShared::should_be_excluded(holder()->method_holder())) {
576       // Check for AOT exclusion only at AOT safe point.
577       log_debug(aot, training)("Cleanup MTD %s::%s", name()->as_klass_external_name(), signature()->as_utf8());
578       if (_final_profile != nullptr && _final_profile->method() != _holder) {
579         log_warning(aot, training)("Stale MDO for  %s::%s", name()->as_klass_external_name(), signature()->as_utf8());
580       }
581       _final_profile = nullptr;
582       _final_counters = nullptr;
583       _holder = nullptr;
584       key()->make_empty();
585     }
586   }
587   for (int i = 0; i < CompLevel_count - 1; i++) {
588     CompileTrainingData* ctd = _last_toplevel_compiles[i];
589     if (ctd != nullptr) {
590       ctd->cleanup(visitor);
591     }
592   }
593 }
594 
595 void KlassTrainingData::verify() {
596   for (int i = 0; i < comp_dep_count(); i++) {
597     CompileTrainingData* ctd = comp_dep(i);
598     if (!ctd->_init_deps.contains(this)) {
599       print_on(tty); tty->cr();
600       ctd->print_on(tty); tty->cr();
601     }
602     guarantee(ctd->_init_deps.contains(this), "");
603   }
604 }
605 
606 void MethodTrainingData::verify(bool verify_dep_counter) {
607   iterate_compiles([&](CompileTrainingData* ctd) {
608     ctd->verify(verify_dep_counter);
609   });
610 }
611 
612 void CompileTrainingData::verify(bool verify_dep_counter) {
613   for (int i = 0; i < init_dep_count(); i++) {
614     KlassTrainingData* ktd = init_dep(i);
615     if (ktd->has_holder() && ktd->holder()->defined_by_other_loaders()) {
616       LogStreamHandle(Info, training) log;
617       if (log.is_enabled()) {
618         ResourceMark rm;
619         log.print("CTD "); print_value_on(&log);
620         log.print(" depends on unregistered class %s", ktd->holder()->name()->as_C_string());
621       }
622     }
623     if (!ktd->_comp_deps.contains(this)) {
624       print_on(tty); tty->cr();
625       ktd->print_on(tty); tty->cr();
626     }
627     guarantee(ktd->_comp_deps.contains(this), "");
628   }
629 
630   if (verify_dep_counter) {
631     int init_deps_left1 = init_deps_left_acquire();
632     int init_deps_left2 = compute_init_deps_left();
633 
634     bool invariant = (init_deps_left1 >= init_deps_left2);
635     if (!invariant) {
636       print_on(tty);
637       tty->cr();
638     }
639     guarantee(invariant, "init deps invariant violation: %d >= %d", init_deps_left1, init_deps_left2);
640   }
641 }
642 
643 void CompileTrainingData::cleanup(Visitor& visitor) {
644   if (visitor.is_visited(this)) {
645     return;
646   }
647   visitor.visit(this);
648   method()->cleanup(visitor);
649 }
650 
651 void TrainingData::serialize(SerializeClosure* soc) {
652   if (soc->writing()) {
653     _archived_training_data_dictionary_for_dumping.serialize_header(soc);
654   } else {
655     _archived_training_data_dictionary.serialize_header(soc);
656   }
657 }
658 
659 class TrainingDataPrinter : StackObj {
660   outputStream* _st;
661   int _index;
662 public:
663   TrainingDataPrinter(outputStream* st) : _st(st), _index(0) {}
664   void do_value(TrainingData* td) {
665     const char* type = (td->is_KlassTrainingData()   ? "K" :
666                         td->is_MethodTrainingData()  ? "M" :
667                         td->is_CompileTrainingData() ? "C" : "?");
668     _st->print("%4d: %p %s ", _index++, td, type);
669     td->print_on(_st);
670     _st->cr();
671     if (td->is_KlassTrainingData()) {
672       td->as_KlassTrainingData()->iterate_comp_deps([&](CompileTrainingData* ctd) {
673         ResourceMark rm;
674         _st->print_raw("  C ");
675         ctd->print_on(_st);
676         _st->cr();
677       });
678     } else if (td->is_MethodTrainingData()) {
679       td->as_MethodTrainingData()->iterate_compiles([&](CompileTrainingData* ctd) {
680         ResourceMark rm;
681         _st->print_raw("  C ");
682         ctd->print_on(_st);
683         _st->cr();
684       });
685     } else if (td->is_CompileTrainingData()) {
686       // ?
687     }
688   }
689 };
690 
691 void TrainingData::print_archived_training_data_on(outputStream* st) {
692   st->print_cr("Archived TrainingData Dictionary");
693   TrainingDataPrinter tdp(st);
694   TrainingDataLocker::initialize();
695   _archived_training_data_dictionary.iterate_all(&tdp);
696 }
697 
698 void TrainingData::Key::metaspace_pointers_do(MetaspaceClosure *iter) {
699   iter->push(const_cast<Metadata**>(&_meta));
700 }
701 
702 void TrainingData::metaspace_pointers_do(MetaspaceClosure* iter) {
703   _key.metaspace_pointers_do(iter);
704 }
705 
706 bool TrainingData::Key::can_compute_cds_hash(const Key* const& k) {
707   return k->meta() == nullptr || MetaspaceObj::in_aot_cache(k->meta());
708 }
709 
710 uint TrainingData::Key::cds_hash(const Key* const& k) {
711   return SystemDictionaryShared::hash_for_shared_dictionary((address)k->meta());
712 }
713 
714 TrainingData* TrainingData::lookup_archived_training_data(const Key* k) {
715   // For this to work, all components of the key must be in shared metaspace.
716   if (!TrainingData::Key::can_compute_cds_hash(k) || _archived_training_data_dictionary.empty()) {
717     return nullptr;
718   }
719   uint hash = TrainingData::Key::cds_hash(k);
720   TrainingData* td = _archived_training_data_dictionary.lookup(k, hash, -1 /*unused*/);
721   if (td != nullptr) {
722     if ((td->is_KlassTrainingData()  && td->as_KlassTrainingData()->has_holder()) ||
723         (td->is_MethodTrainingData() && td->as_MethodTrainingData()->has_holder())) {
724       return td;
725     } else {
726       ShouldNotReachHere();
727     }
728   }
729   return nullptr;
730 }
731 
732 template <typename T>
733 void TrainingData::DepList<T>::metaspace_pointers_do(MetaspaceClosure* iter) {
734   iter->push(&_deps);
735 }
736 
737 void KlassTrainingData::metaspace_pointers_do(MetaspaceClosure* iter) {
738   log_trace(aot, training)("Iter(KlassTrainingData): %p", this);
739   TrainingData::metaspace_pointers_do(iter);
740   _comp_deps.metaspace_pointers_do(iter);
741   iter->push(&_holder);
742 }
743 
744 void MethodTrainingData::metaspace_pointers_do(MetaspaceClosure* iter) {
745   log_trace(aot, training)("Iter(MethodTrainingData): %p", this);
746   TrainingData::metaspace_pointers_do(iter);
747   iter->push(&_klass);
748   iter->push((Method**)&_holder);
749   for (int i = 0; i < CompLevel_count - 1; i++) {
750     iter->push(&_last_toplevel_compiles[i]);
751   }
752   iter->push(&_final_profile);
753   iter->push(&_final_counters);
754 }
755 
756 void CompileTrainingData::metaspace_pointers_do(MetaspaceClosure* iter) {
757   log_trace(aot, training)("Iter(CompileTrainingData): %p", this);
758   TrainingData::metaspace_pointers_do(iter);
759   _init_deps.metaspace_pointers_do(iter);
760   _ci_records.metaspace_pointers_do(iter);
761   iter->push(&_method);
762 }
763 
764 template <typename T>
765 void TrainingData::DepList<T>::prepare() {
766   if (_deps == nullptr && _deps_dyn != nullptr) {
767     int len = _deps_dyn->length();
768     _deps = MetadataFactory::new_array_from_c_heap<T>(len, mtClassShared);
769     for (int i = 0; i < len; i++) {
770       _deps->at_put(i, _deps_dyn->at(i)); // copy
771     }
772   }
773 }
774 
775 void KlassTrainingData::remove_unshareable_info() {
776   TrainingData::remove_unshareable_info();
777   _comp_deps.remove_unshareable_info();
778 }
779 
780 void MethodTrainingData::remove_unshareable_info() {
781   TrainingData::remove_unshareable_info();
782   if (_final_counters != nullptr) {
783     _final_counters->remove_unshareable_info();
784   }
785   if (_final_profile != nullptr) {
786     _final_profile->remove_unshareable_info();
787   }
788 }
789 
790 void CompileTrainingData::remove_unshareable_info() {
791   TrainingData::remove_unshareable_info();
792   _init_deps.remove_unshareable_info();
793   _ci_records.remove_unshareable_info();
794   _init_deps_left = compute_init_deps_left(true);
795 }