1 /*
  2  * Copyright (c) 2023, 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 #include "cds/archiveBuilder.hpp"
 26 #include "cds/cdsAccess.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/runTimeClassInfo.hpp"
 29 #include "code/SCCache.hpp"
 30 #include "compiler/compileBroker.hpp"
 31 #include "compiler/compiler_globals.hpp"
 32 #include "compiler/precompiler.hpp"
 33 #include "logging/logStream.hpp"
 34 #include "memory/allocation.hpp"
 35 #include "oops/trainingData.hpp"
 36 #include "runtime/handles.inline.hpp"
 37 
 38 class PrecompileIterator : StackObj {
 39 private:
 40   CompLevel _comp_level;
 41   CompLevel _search_level;
 42   bool _for_preload;
 43   Thread* _thread;
 44   GrowableArray<Method*> _methods;
 45 
 46 public:
 47   PrecompileIterator(CompLevel comp_level, bool for_preload, CompLevel search_level, JavaThread* thread)
 48   : _comp_level(comp_level), _search_level(search_level), _for_preload(for_preload), _thread(thread) {
 49     assert(TrainingData::have_data(), "sanity");
 50   }
 51 
 52   bool include(Method* m) {
 53     if (m->is_native() || m->is_abstract()) {
 54       return false;
 55     }
 56     DirectiveSet* directives = DirectivesStack::getMatchingDirective(methodHandle(_thread, m), nullptr);
 57     if (directives->DontPrecompileOption) {
 58       return false; // excluded
 59     } else if (directives->PrecompileRecordedOption > 0) {
 60       return true;
 61     }
 62     int cid = compile_id(m, _search_level);
 63     return (cid < INT_MAX);
 64   }
 65 
 66   void do_value(const RunTimeClassInfo* record) {
 67     Array<Method*>* methods = record->klass()->methods();
 68     for (int i = 0; i < methods->length(); i++) {
 69       Method* m = methods->at(i);
 70       if (include(m)) {
 71         _methods.push(m);
 72       }
 73     }
 74   }
 75   void operator()(TrainingData* td) {
 76     if (td->is_MethodTrainingData()) {
 77       MethodTrainingData* mtd = td->as_MethodTrainingData();
 78       if (mtd->has_holder() && include((Method*)mtd->holder())) {
 79         _methods.push((Method*)mtd->holder());
 80       }
 81     }
 82   }
 83 
 84   static int compile_id(Method* m, int level) {
 85     MethodTrainingData* mtd = m->method_holder()->is_loaded() ? MethodTrainingData::find(methodHandle(Thread::current(), m)) : nullptr;
 86     if (mtd != nullptr && mtd->highest_level() == level) {
 87       CompileTrainingData* ctd = mtd->last_toplevel_compile(level);
 88       if (ctd != nullptr) {
 89         return ctd->compile_id();
 90       }
 91     }
 92     return INT_MAX; // treat as the last compilation
 93   }
 94 
 95   static int compare_by_compile_id(Method** m1, Method** m2, CompLevel comp_level) {
 96     int id1 = compile_id(*m1, comp_level);
 97     int id2 = compile_id(*m2, comp_level);
 98     return (id1 - id2);
 99   }
100 
101   static int compare_by_compile_id_tier1(Method** m1, Method** m2) {
102     return compare_by_compile_id(m1, m2, CompLevel_simple);
103   }
104 
105   static int compare_by_compile_id_tier2(Method** m1, Method** m2) {
106     return compare_by_compile_id(m1, m2, CompLevel_limited_profile);
107   }
108 
109   static int compare_by_compile_id_tier3(Method** m1, Method** m2) {
110     return compare_by_compile_id(m1, m2, CompLevel_full_profile);
111   }
112 
113   static int compare_by_compile_id_tier4(Method** m1, Method** m2) {
114     return compare_by_compile_id(m1, m2, CompLevel_full_optimization);
115   }
116 
117   void sort_methods_by_compile_id() {
118     switch(_search_level) {
119       case CompLevel_simple:            _methods.sort(&compare_by_compile_id_tier1); break;
120       case CompLevel_limited_profile:   _methods.sort(&compare_by_compile_id_tier2); break;
121       case CompLevel_full_profile:      _methods.sort(&compare_by_compile_id_tier3); break;
122       case CompLevel_full_optimization: _methods.sort(&compare_by_compile_id_tier4); break;
123 
124       default: fatal("%d", _search_level);
125     }
126   }
127 
128   void schedule_compilations(TRAPS) {
129     for (int i = 0; i < _methods.length(); i++) {
130       Method* m = _methods.at(i);
131       methodHandle mh(THREAD, m);
132       assert(mh()->method_holder()->is_linked(), "required");
133 
134       assert(!HAS_PENDING_EXCEPTION, "");
135       CompileBroker::compile_method(mh, InvocationEntryBci, _comp_level,
136                                     methodHandle(), 0,
137                                     true /*requires_online_comp*/,
138                                     _for_preload ? CompileTask::Reason_PrecompileForPreload : CompileTask::Reason_Precompile,
139                                     THREAD);
140       if (HAS_PENDING_EXCEPTION) {
141         CLEAR_PENDING_EXCEPTION;
142       }
143     }
144   }
145 
146   void print_compilation_status(ArchiveBuilder* builder) {
147     int success_count = 0;
148     const int log_comp_level = _comp_level + (_for_preload ? 1 : 0);
149 
150     for (int i = 0; i < _methods.length(); i++) {
151       Method* m = _methods.at(i);
152 
153       bool is_success = !m->is_not_compilable(_comp_level);
154       if (is_success) {
155         success_count++;
156       }
157 
158       LogStreamHandle(Info, precompile) log;
159       if (log.is_enabled()) {
160         ResourceMark rm;
161         log.print("[%4d] T%d Compiled %s [%p", i, log_comp_level, m->external_name(), m);
162         if (builder != nullptr) {
163           Method* requested_m = builder->to_requested(builder->get_buffered_addr(m));
164           log.print(" -> %p", requested_m);
165         }
166         log.print("] [%d] (%s)", SCCache::store_entries_cnt(), (is_success ? "success" : "FAILED"));
167       }
168     }
169 
170     log_info(precompile)("Precompilation for level %d finished (%d successful out of %d total)",
171       log_comp_level, success_count, _methods.length());
172   }
173 
174   void precompile(ArchiveBuilder* builder, TRAPS) {
175     sort_methods_by_compile_id();
176     schedule_compilations(THREAD);
177     CompileBroker::wait_for_no_active_tasks();
178     print_compilation_status(builder);
179   }
180 };
181 
182 void Precompiler::compile_cached_code(CompLevel search_level, bool for_preload, CompLevel comp_level, TRAPS) {
183   ResourceMark rm;
184   PrecompileIterator pi(comp_level, for_preload, search_level, THREAD);
185   TrainingData::iterate(pi);
186   pi.precompile((ArchiveBuilder*)nullptr, THREAD);
187 }
188 
189 void Precompiler::compile_cached_code(TRAPS) {
190   log_info(precompile)("Precompilation started");
191   if (TrainingData::have_data()) {
192     TrainingData::iterate([&](TrainingData* td) {
193       if (td->is_KlassTrainingData()) {
194         KlassTrainingData *ktd = td->as_KlassTrainingData();
195         if (ktd->has_holder()) {
196           assert(!HAS_PENDING_EXCEPTION, "");
197           ktd->holder()->link_class(THREAD);
198           if (HAS_PENDING_EXCEPTION) {
199             LogStreamHandle(Warning, precompile) log;
200             if (log.is_enabled()) {
201               ResourceMark rm;
202               log.print("Linkage failed for %s: ", ktd->holder()->external_name());
203               PENDING_EXCEPTION->print_on(&log);
204             }
205             CLEAR_PENDING_EXCEPTION;
206           }
207         }
208       }
209     });
210 
211     compile_cached_code(CompLevel_full_optimization, true, CompLevel_full_optimization, CHECK);
212 
213     compile_cached_code(CompLevel_full_optimization, false, CompLevel_full_optimization, CHECK);
214     compile_cached_code(CompLevel_full_profile,      false, CompLevel_limited_profile,   CHECK);
215     compile_cached_code(CompLevel_limited_profile,   false, CompLevel_limited_profile,   CHECK);
216     compile_cached_code(CompLevel_simple,            false, CompLevel_simple,            CHECK);
217   }
218 }
219 
220 // New workflow only
221 void Precompiler::compile_cached_code(ArchiveBuilder* builder, TRAPS) {
222   assert(CDSConfig::is_dumping_final_static_archive() && StoreCachedCode, "sanity");
223   if (TrainingData::have_data()) {
224     ResourceMark rm;
225 
226     {
227       PrecompileIterator pi(CompLevel_full_optimization, true /*for_preload*/, CompLevel_full_optimization, THREAD);
228       TrainingData::iterate(pi);
229       pi.precompile(builder, THREAD);
230     }
231 
232     for (int level = CompLevel_simple; level <= CompLevel_full_optimization; level++) {
233       CompLevel comp_level = (CompLevel)level;
234       if (comp_level == CompLevel_full_profile) {
235         comp_level = CompLevel_limited_profile;
236       }
237       PrecompileIterator pi(comp_level, false /*for_preload*/, (CompLevel)level, THREAD);
238       TrainingData::iterate(pi);
239       pi.precompile(builder, THREAD);
240     }
241   }
242 }