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