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