blob: 5ee88718dc9db44866109664c493fbbd031edf8a [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit.h"
18
19#include <dlfcn.h>
20
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000023#include "base/file_utils.h"
Andreas Gampe57943812017-12-06 21:39:13 -080024#include "base/logging.h" // For VLOG.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010025#include "base/memfd.h"
Andreas Gampe0897e1c2017-05-16 08:36:56 -070026#include "base/memory_tool.h"
Andreas Gampedcc528d2017-12-07 13:37:10 -080027#include "base/runtime_debug.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000028#include "base/scoped_flock.h"
David Sehrc431b9d2018-03-02 12:01:51 -080029#include "base/utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010030#include "class_root-inl.h"
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +010031#include "compilation_kind.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070032#include "debugger.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010033#include "dex/type_lookup_table.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010034#include "gc/space/image_space.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010035#include "entrypoints/entrypoint_utils-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "entrypoints/runtime_asm_entrypoints.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010037#include "image-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080038#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000039#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080040#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010041#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010042#include "mirror/method_handle_impl.h"
43#include "mirror/var_handle.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010044#include "oat_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010045#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000046#include "oat_quick_method_header.h"
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +010047#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070048#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000049#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080050#include "runtime.h"
51#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070052#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000053#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070054#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010055#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080056
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010057using android::base::unique_fd;
58
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080059namespace art {
60namespace jit {
61
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000062static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000063
Orion Hodson4fa78a02019-09-12 09:35:24 +010064// Maximum permitted threshold value.
65static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
66
Andreas Gampe7897cec2017-07-19 16:28:59 -070067// Different compilation threshold constants. These can be overridden on the command line.
Orion Hodson4fa78a02019-09-12 09:35:24 +010068
69// Non-debug default
70static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
71// Fast-debug build.
72static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
73// Slow-debug build.
74static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
75
76// Different warm-up threshold constants. These default to the equivalent compile thresholds divided
77// by 2, but can be overridden at the command-line.
78static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
79static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
80static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
81 kJitSlowStressDefaultCompileThreshold / 2;
Andreas Gampe7897cec2017-07-19 16:28:59 -070082
David Srbecky21821472019-07-29 15:10:31 +010083DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
84
Mathieu Chartier72918ea2016-03-24 11:07:06 -070085// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080086void* Jit::jit_library_handle_ = nullptr;
David Srbecky46b53532019-08-06 13:39:05 +010087JitCompilerInterface* Jit::jit_compiler_ = nullptr;
88JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070089
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080090JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080091 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010092 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +000093 jit_options->use_profiled_jit_compilation_ =
94 options.GetOrDefault(RuntimeArgumentMap::UseProfiledJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000095
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000096 jit_options->code_cache_initial_capacity_ =
97 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
98 jit_options->code_cache_max_capacity_ =
99 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700100 jit_options->dump_info_on_shutdown_ =
101 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +0100102 jit_options->profile_saver_options_ =
103 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100104 jit_options->thread_pool_pthread_priority_ =
105 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +0000106 jit_options->zygote_thread_pool_pthread_priority_ =
107 options.GetOrDefault(RuntimeArgumentMap::JITZygotePoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000108
Orion Hodson853fc2e2020-07-27 17:01:44 +0100109 // Set default compile threshold to aid with checking defaults.
Orion Hodson4fa78a02019-09-12 09:35:24 +0100110 jit_options->compile_threshold_ =
111 kIsDebugBuild
112 ? (Jit::kSlowMode
113 ? kJitSlowStressDefaultCompileThreshold
114 : kJitStressDefaultCompileThreshold)
115 : kJitDefaultCompileThreshold;
116
117 // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
118 const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
119
Orion Hodson853fc2e2020-07-27 17:01:44 +0100120 // Set default warm-up threshold to aid with checking defaults.
Orion Hodson4fa78a02019-09-12 09:35:24 +0100121 jit_options->warmup_threshold_ =
122 kIsDebugBuild ? (Jit::kSlowMode
123 ? kJitSlowStressDefaultWarmUpThreshold
124 : kJitStressDefaultWarmUpThreshold)
125 : kJitDefaultWarmUpThreshold;
126
127 // Warmup threshold should be less than compile threshold (so long as compile threshold is not
128 // zero == JIT-on-first-use).
129 DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
130 DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
131 jit_options->warmup_threshold_);
132
Andreas Gampe7897cec2017-07-19 16:28:59 -0700133 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
134 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
Andreas Gampe7897cec2017-07-19 16:28:59 -0700135 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100136 jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000137
138 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
139 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000140 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100141 jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000142
143 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
144 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000145 } else {
146 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
Orion Hodson4fa78a02019-09-12 09:35:24 +0100147 if (jit_options->osr_threshold_ > kJitMaxThreshold) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000148 jit_options->osr_threshold_ =
Orion Hodson4fa78a02019-09-12 09:35:24 +0100149 RoundDown(kJitMaxThreshold, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000150 }
151 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100152 jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
153
154 // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
155 // threshold is 0).
156 if (jit_options->compile_threshold_ != 0) {
157 // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
158 jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
159 2u * kJitThresholdStep,
160 RoundDown(kJitMaxThreshold, kJitThresholdStep));
161 jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
162 kJitThresholdStep,
163 jit_options->osr_threshold_ - kJitThresholdStep);
164 jit_options->warmup_threshold_ =
165 std::clamp(jit_options->warmup_threshold_,
166 0u,
167 jit_options->compile_threshold_ - kJitThresholdStep);
168 }
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000169
Calin Juravleb2771b42016-04-07 17:09:25 +0100170 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
171 jit_options->priority_thread_weight_ =
172 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
173 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
174 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
175 } else if (jit_options->priority_thread_weight_ == 0) {
176 LOG(FATAL) << "Priority thread weight cannot be 0.";
177 }
178 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100179 jit_options->priority_thread_weight_ = std::max(
180 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
181 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100182 }
183
Calin Juravle155ff3d2016-04-27 14:14:58 +0100184 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100185 jit_options->invoke_transition_weight_ =
186 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100187 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
188 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
189 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100190 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100191 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100192 } else {
193 jit_options->invoke_transition_weight_ = std::max(
194 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800195 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100196 }
197
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800198 return jit_options;
199}
200
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700201void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000202 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700203 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000204 MutexLock mu(Thread::Current(), lock_);
205 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700206}
207
Calin Juravleb8e69992016-03-09 15:37:48 +0000208void Jit::DumpForSigQuit(std::ostream& os) {
209 DumpInfo(os);
210 ProfileSaver::DumpInstanceInfo(os);
211}
212
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700213void Jit::AddTimingLogger(const TimingLogger& logger) {
214 cumulative_timings_.AddLogger(logger);
215}
216
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100217Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
218 : code_cache_(code_cache),
219 options_(options),
David Srbeckybfcea3d2019-08-05 15:44:00 +0100220 boot_completed_lock_("Jit::boot_completed_lock_"),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100221 cumulative_timings_("JIT timings"),
222 memory_use_("Memory used for compilation", 16),
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000223 lock_("JIT memory use lock"),
224 zygote_mapping_methods_(),
225 fd_methods_(-1),
226 fd_methods_size_(0) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800227
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100228Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000229 if (jit_load_ == nullptr) {
230 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800231 return nullptr;
232 }
David Srbecky46b53532019-08-06 13:39:05 +0100233 jit_compiler_ = (jit_load_)();
234 if (jit_compiler_ == nullptr) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000235 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
236 return nullptr;
237 }
238 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000239
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000240 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000241 // With 'perf', we want a 1-1 mapping between an address and a method.
242 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
243 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000244 if (code_cache->GetGarbageCollectCode()) {
David Srbecky46b53532019-08-06 13:39:05 +0100245 code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000246 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
247 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100248
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000249 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000250 << PrettySize(options->GetCodeCacheInitialCapacity())
251 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000252 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100253 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100254
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +0000255 // We want to know whether the compiler is compiling baseline, as this
256 // affects how we GC ProfilingInfos.
257 for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
258 if (option == "--baseline") {
259 options->SetUseBaselineCompiler();
260 break;
261 }
262 }
263
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100264 // Notify native debugger about the classes already loaded before the creation of the jit.
265 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800266 return jit.release();
267}
268
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000269template <typename T>
270bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
271 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
272 if (*address == nullptr) {
273 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
274 return false;
275 }
276 return true;
277}
278
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000279bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800280 jit_library_handle_ = dlopen(
281 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
282 if (jit_library_handle_ == nullptr) {
283 std::ostringstream oss;
284 oss << "JIT could not load libart-compiler.so: " << dlerror();
285 *error_msg = oss.str();
286 return false;
287 }
David Srbecky46b53532019-08-06 13:39:05 +0100288 if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800289 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000290 return false;
291 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700292 return true;
293}
294
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100295bool Jit::CompileMethod(ArtMethod* method,
296 Thread* self,
297 CompilationKind compilation_kind,
298 bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100299 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800300 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000301
Alex Light0fa17862017-10-24 13:43:05 -0700302 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700304 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
305 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
306 << " due to not being safe to jit according to runtime-callbacks. For example, there"
307 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700308 return false;
309 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100310
Alex Light986914b2019-11-19 01:12:25 +0000311 if (!method->IsCompilable()) {
312 DCHECK(method->GetDeclaringClass()->IsObsoleteObject() ||
313 method->IsProxyMethod()) << method->PrettyMethod();
314 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to method being made "
315 << "obsolete while waiting for JIT task to run. This probably happened due to "
316 << "concurrent structural class redefinition.";
317 return false;
318 }
319
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100320 // Don't compile the method if we are supposed to be deoptimized.
321 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
322 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700323 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100324 return false;
325 }
326
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000327 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100328 if ((compilation_kind == CompilationKind::kOsr) && GetCodeCache()->IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100329 VLOG(jit) << "JIT not osr compiling "
330 << method->PrettyMethod()
331 << " due to using shared region";
332 return false;
333 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000334
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000335 // If we get a request to compile a proxy method, we pass the actual Java method
336 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700337 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffray60ef3992020-08-07 07:49:57 +0000338 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, compilation_kind, prejit)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100339 return false;
340 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100341
342 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700343 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100344 << " kind=" << compilation_kind;
345 bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, compilation_kind);
346 code_cache_->DoneCompiling(method_to_compile, self, compilation_kind);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100347 if (!success) {
348 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700349 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100350 << " kind=" << compilation_kind;
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100351 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800352 if (kIsDebugBuild) {
353 if (self->IsExceptionPending()) {
354 mirror::Throwable* exception = self->GetException();
355 LOG(FATAL) << "No pending exception expected after compiling "
356 << ArtMethod::PrettyMethod(method)
357 << ": "
358 << exception->Dump();
359 }
360 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100361 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800362}
363
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800364void Jit::WaitForWorkersToBeCreated() {
365 if (thread_pool_ != nullptr) {
366 thread_pool_->WaitForWorkersToBeCreated();
367 }
368}
369
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800370void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100371 Thread* self = Thread::Current();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100372 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700373 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100374 {
375 ScopedSuspendAll ssa(__FUNCTION__);
376 // Clear thread_pool_ field while the threads are suspended.
377 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700378 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100379 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700380
381 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000382 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700383 pool->StopWorkers(self);
384 pool->RemoveAllTasks(self);
385 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100386 // We could just suspend all threads, but we know those threads
387 // will finish in a short period, so it's not worth adding a suspend logic
388 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700389 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800390 }
391}
392
Calin Juravlebeb9f202021-06-02 14:42:03 -0700393void Jit::StartProfileSaver(const std::string& profile_filename,
394 const std::vector<std::string>& code_paths,
395 const std::string& ref_profile_filename) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100396 if (options_->GetSaveProfilingInfo()) {
Calin Juravlebeb9f202021-06-02 14:42:03 -0700397 ProfileSaver::Start(options_->GetProfileSaverOptions(),
398 profile_filename,
399 code_cache_,
400 code_paths,
401 ref_profile_filename);
Calin Juravle31f2c152015-10-23 17:56:15 +0100402 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000403}
404
405void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100406 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
407 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100408 }
409}
410
Siva Chandra05d24152016-01-05 17:43:17 -0800411bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100412 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800413}
414
Nicolas Geoffray35122442016-03-02 12:05:30 +0000415bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
416 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
417}
418
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800419Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100420 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
421 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700422 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100423 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700424 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800425 DeleteThreadPool();
David Srbecky46b53532019-08-06 13:39:05 +0100426 if (jit_compiler_ != nullptr) {
427 delete jit_compiler_;
428 jit_compiler_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800429 }
430 if (jit_library_handle_ != nullptr) {
431 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700432 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800433 }
434}
435
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000436void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100437 if (!Runtime::Current()->UseJitCompilation()) {
438 // No need to notify if we only use the JIT to save profiles.
439 return;
440 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000441 jit::Jit* jit = Runtime::Current()->GetJit();
David Srbecky46b53532019-08-06 13:39:05 +0100442 if (jit->jit_compiler_->GenerateDebugInfo()) {
443 jit_compiler_->TypesLoaded(&type, 1);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000444 }
445}
446
447void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
448 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100449 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700450 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000451 return true;
452 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800453 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000454 };
455
David Srbecky46b53532019-08-06 13:39:05 +0100456 if (jit_compiler_->GenerateDebugInfo()) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000457 ScopedObjectAccess so(Thread::Current());
458
459 CollectClasses visitor;
460 linker->VisitClasses(&visitor);
David Srbecky46b53532019-08-06 13:39:05 +0100461 jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000462 }
463}
464
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000465extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700466 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000467 const uint8_t* native_pc,
468 JValue* result,
469 const char* shorty,
470 Thread* self);
471
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000472OsrData* Jit::PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000473 if (!kEnableOnStackReplacement) {
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000474 return nullptr;
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000475 }
476
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000477 // Cheap check if the method has been compiled already. That's an indicator that we should
478 // osr into it.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000479 if (!GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
480 return nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000481 }
482
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000483 // Fetch some data before looking up for an OSR method. We don't want thread
484 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
485 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000486 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800487 const size_t number_of_vregs = accessor.RegistersSize();
David Sehr709b0702016-10-13 09:12:37 -0700488 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000489 OsrData* osr_data = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000490
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000491 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700492 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000493 const OatQuickMethodHeader* osr_method = GetCodeCache()->LookupOsrMethodHeader(method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000494 if (osr_method == nullptr) {
495 // No osr method yet, just return to the interpreter.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000496 return nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000497 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000498
David Srbecky052f8ca2018-04-26 15:42:54 +0100499 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000500
501 // Find stack map starting at the target dex_pc.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000502 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000503 if (!stack_map.IsValid()) {
504 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
505 // hope that the next branch has one.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000506 return nullptr;
Aart Bik29bdaee2016-05-18 15:44:07 -0700507 }
508
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000509 // We found a stack map, now fill the frame with dex register values from the interpreter's
510 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100511 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Artem Serov2808be82018-12-20 19:15:11 +0000512 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000513
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000514 size_t frame_size = osr_method->GetFrameSizeInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000515
516 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
517 // stack.
518 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
519 // but that is engineering complexity not worth the effort for something like OSR.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000520 osr_data = reinterpret_cast<OsrData*>(malloc(sizeof(OsrData) + frame_size));
521 if (osr_data == nullptr) {
522 return nullptr;
523 }
524 memset(osr_data, 0, sizeof(OsrData) + frame_size);
525 osr_data->frame_size = frame_size;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000526
527 // Art ABI: ArtMethod is at the bottom of the stack.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000528 osr_data->memory[0] = method;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000529
David Srbeckyfd89b072018-06-03 12:00:22 +0100530 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000531 // If we don't have a dex register map, then there are no live dex registers at
532 // this dex pc.
533 } else {
534 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100535 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000536 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000537 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000538 continue;
539 }
540
541 if (location == DexRegisterLocation::Kind::kConstant) {
542 // We skip constants because the compiled code knows how to handle them.
543 continue;
544 }
545
David Srbecky7dc11782016-02-25 13:23:56 +0000546 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000547
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000548 int32_t vreg_value = vregs[vreg];
David Srbeckye1402122018-06-13 18:20:45 +0100549 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000550 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
551 DCHECK_GT(slot_offset, 0);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000552 (reinterpret_cast<int32_t*>(osr_data->memory))[slot_offset / sizeof(int32_t)] = vreg_value;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000553 }
554 }
555
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000556 osr_data->native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000557 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000558 VLOG(jit) << "Jumping to "
559 << method_name
560 << "@"
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000561 << std::hex << reinterpret_cast<uintptr_t>(osr_data->native_pc);
562 }
563 return osr_data;
564}
565
566bool Jit::MaybeDoOnStackReplacement(Thread* thread,
567 ArtMethod* method,
568 uint32_t dex_pc,
569 int32_t dex_pc_offset,
570 JValue* result) {
571 Jit* jit = Runtime::Current()->GetJit();
572 if (jit == nullptr) {
573 return false;
574 }
575
576 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
577 // Don't attempt to do an OSR if we are close to the stack limit. Since
578 // the interpreter frames are still on stack, OSR has the potential
579 // to stack overflow even for a simple loop.
580 // b/27094810.
581 return false;
582 }
583
584 // Get the actual Java method if this method is from a proxy class. The compiler
585 // and the JIT code cache do not expect methods from proxy classes.
586 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
587
588 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
589 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
590 // disable OSR when single stepping, but that's currently hard to know at this point.
591 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
592 return false;
593 }
594
595 ShadowFrame* shadow_frame = thread->GetManagedStack()->GetTopShadowFrame();
596 OsrData* osr_data = jit->PrepareForOsr(method,
597 dex_pc + dex_pc_offset,
598 shadow_frame->GetVRegArgs(0));
599
600 if (osr_data == nullptr) {
601 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000602 }
603
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000604 {
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000605 thread->PopShadowFrame();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000606 ManagedStack fragment;
607 thread->PushManagedStackFragment(&fragment);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000608 (*art_quick_osr_stub)(osr_data->memory,
609 osr_data->frame_size,
610 osr_data->native_pc,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000611 result,
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000612 method->GetShorty(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000613 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000614
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000615 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
616 thread->DeoptimizeWithDeoptimizationException(result);
617 }
618 thread->PopManagedStackFragment(fragment);
619 }
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000620 free(osr_data);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000621 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000622 VLOG(jit) << "Done running OSR code for " << method->PrettyMethod();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000623 return true;
624}
625
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000626void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
627 if (bytes > 4 * MB) {
628 LOG(INFO) << "Compiler allocated "
629 << PrettySize(bytes)
630 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700631 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000632 }
633 MutexLock mu(Thread::Current(), lock_);
634 memory_use_.AddValue(bytes);
635}
636
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000637void Jit::NotifyZygoteCompilationDone() {
638 if (fd_methods_ == -1) {
639 return;
640 }
641
642 size_t offset = 0;
643 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
644 const ImageHeader& header = space->GetImageHeader();
645 const ImageSection& section = header.GetMethodsSection();
646 // Because mremap works at page boundaries, we can only handle methods
647 // within a page range. For methods that falls above or below the range,
648 // the child processes will copy their contents to their private mapping
649 // in `child_mapping_methods`. See `MapBootImageMethods`.
650 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
651 uint8_t* page_end =
652 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
653 if (page_end > page_start) {
654 uint64_t capacity = page_end - page_start;
655 memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
656 offset += capacity;
657 }
658 }
659
660 // Do an msync to ensure we are not affected by writes still being in caches.
661 if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
662 PLOG(WARNING) << "Failed to sync boot image methods memory";
663 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
664 return;
665 }
666
667 // We don't need the shared mapping anymore, and we need to drop it in case
668 // the file hasn't been sealed writable.
669 zygote_mapping_methods_ = MemMap::Invalid();
670
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000671 // Seal writes now. Zygote and children will map the memory private in order
672 // to write to it.
673 if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
674 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
675 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
676 return;
677 }
678
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000679 std::string error_str;
680 MemMap child_mapping_methods = MemMap::MapFile(
681 fd_methods_size_,
682 PROT_READ | PROT_WRITE,
683 MAP_PRIVATE,
684 fd_methods_,
685 /* start= */ 0,
686 /* low_4gb= */ false,
687 "boot-image-methods",
688 &error_str);
689
690 if (!child_mapping_methods.IsValid()) {
691 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
692 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
693 return;
694 }
695
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000696 // Ensure the contents are the same as before: there was a window between
697 // the memcpy and the sealing where other processes could have changed the
698 // contents.
699 // Note this would not be needed if we could have used F_SEAL_FUTURE_WRITE,
700 // see b/143833776.
701 offset = 0;
702 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
703 const ImageHeader& header = space->GetImageHeader();
704 const ImageSection& section = header.GetMethodsSection();
705 // Because mremap works at page boundaries, we can only handle methods
706 // within a page range. For methods that falls above or below the range,
707 // the child processes will copy their contents to their private mapping
708 // in `child_mapping_methods`. See `MapBootImageMethods`.
709 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
710 uint8_t* page_end =
711 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
712 if (page_end > page_start) {
713 uint64_t capacity = page_end - page_start;
714 if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
715 LOG(WARNING) << "Contents differ in boot image methods data";
716 code_cache_->GetZygoteMap()->SetCompilationState(
717 ZygoteCompilationState::kNotifiedFailure);
718 return;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000719 }
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000720 offset += capacity;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000721 }
722 }
723
724 // Future spawned processes don't need the fd anymore.
725 fd_methods_.reset();
726
727 // In order to have the zygote and children share the memory, we also remap
728 // the memory into the zygote process.
729 offset = 0;
730 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
731 const ImageHeader& header = space->GetImageHeader();
732 const ImageSection& section = header.GetMethodsSection();
733 // Because mremap works at page boundaries, we can only handle methods
734 // within a page range. For methods that falls above or below the range,
735 // the child processes will copy their contents to their private mapping
736 // in `child_mapping_methods`. See `MapBootImageMethods`.
737 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
738 uint8_t* page_end =
739 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
740 if (page_end > page_start) {
741 uint64_t capacity = page_end - page_start;
742 if (mremap(child_mapping_methods.Begin() + offset,
743 capacity,
744 capacity,
745 MREMAP_FIXED | MREMAP_MAYMOVE,
746 page_start) == MAP_FAILED) {
747 // Failing to remap is safe as the process will just use the old
748 // contents.
749 PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
750 }
751 offset += capacity;
752 }
753 }
754
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000755 LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
756
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000757 // Mark that compilation of boot classpath is done, and memory can now be
758 // shared. Other processes will pick up this information.
759 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
760
761 // The private mapping created for this process has been mremaped. We can
762 // reset it.
763 child_mapping_methods.Reset();
764}
765
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100766class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100767 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000768 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100769 kCompile,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100770 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100771 };
772
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100773 JitCompileTask(ArtMethod* method, TaskKind task_kind, CompilationKind compilation_kind)
774 : method_(method), kind_(task_kind), compilation_kind_(compilation_kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100775 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000776 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
777 // until compilation is done.
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +0000778 // When we precompile, this is either with boot classpath methods, or main
779 // class loader methods, so we don't need to keep a global reference.
780 if (method->GetDeclaringClass()->GetClassLoader() != nullptr &&
781 kind_ != TaskKind::kPreCompile) {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000782 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
783 CHECK(klass_ != nullptr);
784 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100785 }
786
787 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000788 if (klass_ != nullptr) {
789 ScopedObjectAccess soa(Thread::Current());
790 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
791 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100792 }
793
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100794 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700795 {
796 ScopedObjectAccess soa(self);
797 switch (kind_) {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700798 case TaskKind::kCompile:
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100799 case TaskKind::kPreCompile: {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700800 Runtime::Current()->GetJit()->CompileMethod(
801 method_,
802 self,
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100803 compilation_kind_,
Andreas Gampe4bd52342019-07-15 15:09:04 -0700804 /* prejit= */ (kind_ == TaskKind::kPreCompile));
805 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000806 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100807 }
808 }
Calin Juravlea2638922016-04-29 16:44:11 +0100809 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100810 }
811
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100812 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100813 delete this;
814 }
815
816 private:
817 ArtMethod* const method_;
818 const TaskKind kind_;
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +0100819 const CompilationKind compilation_kind_;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100820 jobject klass_;
821
822 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
823};
824
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100825static std::string GetProfileFile(const std::string& dex_location) {
826 // Hardcoded assumption where the profile file is.
827 // TODO(ngeoffray): this is brittle and we would need to change change if we
828 // wanted to do more eager JITting of methods in a profile. This is
829 // currently only for system server.
830 return dex_location + ".prof";
831}
832
833static std::string GetBootProfileFile(const std::string& profile) {
834 // The boot profile can be found next to the compilation profile, with a
835 // different extension.
836 return ReplaceFileExtension(profile, "bprof");
837}
838
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100839/**
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100840 * A JIT task to run after all profile compilation is done.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100841 */
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100842class JitDoneCompilingProfileTask final : public SelfDeletingTask {
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100843 public:
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100844 explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100845 : dex_files_(dex_files) {}
846
847 void Run(Thread* self ATTRIBUTE_UNUSED) override {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100848 // Madvise DONTNEED dex files now that we're done compiling methods.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100849 for (const DexFile* dex_file : dex_files_) {
850 if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
851 int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
852 RoundUp(dex_file->Size(), kPageSize),
853 MADV_DONTNEED);
854 if (result == -1) {
855 PLOG(WARNING) << "Madvise failed";
856 }
857 }
858 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100859
860 if (Runtime::Current()->IsZygote()) {
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000861 // Record that we are done compiling the profile.
862 Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
863 ZygoteCompilationState::kDone);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100864 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100865 }
866
867 private:
868 std::vector<const DexFile*> dex_files_;
869
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100870 DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100871};
872
Nicolas Geoffrayb2028732020-04-08 15:41:41 +0100873/**
874 * A JIT task to run Java verification of boot classpath classes that were not
875 * verified at compile-time.
876 */
877class ZygoteVerificationTask final : public Task {
878 public:
879 ZygoteVerificationTask() {}
880
881 void Run(Thread* self) override {
Nicolas Geoffray3a079092020-05-09 14:48:35 +0100882 // We are going to load class and run verification, which may also need to load
883 // classes. If the thread cannot load classes (typically when the runtime is
884 // debuggable), then just return.
885 if (!self->CanLoadClasses()) {
886 return;
887 }
Nicolas Geoffrayb2028732020-04-08 15:41:41 +0100888 Runtime* runtime = Runtime::Current();
889 ClassLinker* linker = runtime->GetClassLinker();
890 const std::vector<const DexFile*>& boot_class_path =
891 runtime->GetClassLinker()->GetBootClassPath();
892 ScopedObjectAccess soa(self);
893 StackHandleScope<1> hs(self);
894 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
895 uint64_t start_ns = ThreadCpuNanoTime();
896 uint64_t number_of_classes = 0;
897 for (const DexFile* dex_file : boot_class_path) {
898 if (dex_file->GetOatDexFile() != nullptr &&
899 dex_file->GetOatDexFile()->GetOatFile() != nullptr) {
900 // If backed by an .oat file, we have already run verification at
901 // compile-time. Note that some classes may still have failed
902 // verification there if they reference updatable mainline module
903 // classes.
904 continue;
905 }
906 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
907 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
908 const char* descriptor = dex_file->GetClassDescriptor(class_def);
909 ScopedNullHandle<mirror::ClassLoader> null_loader;
910 klass.Assign(linker->FindClass(self, descriptor, null_loader));
911 if (klass == nullptr) {
912 self->ClearException();
913 LOG(WARNING) << "Could not find " << descriptor;
914 continue;
915 }
916 ++number_of_classes;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +0000917 if (linker->VerifyClass(self, /* verifier_deps= */ nullptr, klass) ==
918 verifier::FailureKind::kHardFailure) {
Nicolas Geoffray12b7ea12020-05-07 14:59:31 +0100919 DCHECK(self->IsExceptionPending());
920 LOG(FATAL) << "Methods in the boot classpath failed to verify: "
921 << self->GetException()->Dump();
922 }
923 CHECK(!self->IsExceptionPending());
Nicolas Geoffrayb2028732020-04-08 15:41:41 +0100924 }
925 }
926 LOG(INFO) << "Verified "
927 << number_of_classes
928 << " classes from mainline modules in "
929 << PrettyDuration(ThreadCpuNanoTime() - start_ns);
930 }
931};
932
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000933class ZygoteTask final : public Task {
934 public:
935 ZygoteTask() {}
936
937 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100938 Runtime* runtime = Runtime::Current();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +0100939 uint32_t added_to_queue = 0;
Nicolas Geoffray4cbb51a2020-02-07 11:25:54 +0000940 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
941 const std::string& profile_file = space->GetProfileFile();
942 if (profile_file.empty()) {
943 continue;
944 }
945 LOG(INFO) << "JIT Zygote looking at profile " << profile_file;
946
947 const std::vector<const DexFile*>& boot_class_path =
948 runtime->GetClassLinker()->GetBootClassPath();
949 ScopedNullHandle<mirror::ClassLoader> null_handle;
950 // We add to the queue for zygote so that we can fork processes in-between
951 // compilations.
952 if (Runtime::Current()->IsPrimaryZygote()) {
953 std::string boot_profile = GetBootProfileFile(profile_file);
954 // We avoid doing compilation at boot for the secondary zygote, as apps
955 // forked from it are not critical for boot.
956 added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
957 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
958 }
959 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
960 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraya6f35832019-08-09 13:34:19 +0100961 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100962
963 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
964 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100965 }
966
967 void Finalize() override {
968 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000969 }
970
971 private:
972 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
973};
974
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100975class JitProfileTask final : public Task {
976 public:
977 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100978 jobject class_loader) {
979 ScopedObjectAccess soa(Thread::Current());
980 StackHandleScope<1> hs(soa.Self());
981 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
982 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100983 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
984 for (const auto& dex_file : dex_files) {
985 dex_files_.push_back(dex_file.get());
986 // Register the dex file so that we can guarantee it doesn't get deleted
987 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100988 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100989 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100990 // We also create our own global ref to use this class loader later.
991 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100992 }
993
994 void Run(Thread* self) override {
995 ScopedObjectAccess soa(self);
996 StackHandleScope<1> hs(self);
997 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
998 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100999
1000 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
1001 std::string boot_profile = GetBootProfileFile(profile);
1002
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001003 Jit* jit = Runtime::Current()->GetJit();
1004
1005 jit->CompileMethodsFromBootProfile(
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001006 self,
1007 dex_files_,
1008 boot_profile,
1009 loader,
1010 /* add_to_queue= */ false);
1011
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001012 jit->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001013 self,
1014 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001015 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001016 loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001017 /* add_to_queue= */ true);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001018 }
1019
1020 void Finalize() override {
1021 delete this;
1022 }
1023
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +01001024 ~JitProfileTask() {
1025 ScopedObjectAccess soa(Thread::Current());
1026 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
1027 }
1028
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001029 private:
1030 std::vector<const DexFile*> dex_files_;
1031 jobject class_loader_;
1032
1033 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
1034};
1035
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001036static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
1037 if (memcmp(s1, s2, n) != 0) {
1038 memcpy(s1, s2, n);
1039 }
1040}
1041
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001042void Jit::MapBootImageMethods() {
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +00001043 if (Runtime::Current()->IsJavaDebuggable()) {
1044 LOG(INFO) << "Not mapping boot image methods due to process being debuggable";
1045 return;
1046 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001047 CHECK_NE(fd_methods_.get(), -1);
1048 if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
1049 LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
Nicolas Geoffrayecd95022020-01-27 09:35:10 +00001050 // We don't need the fd anymore.
1051 fd_methods_.reset();
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001052 return;
1053 }
1054
1055 std::string error_str;
1056 MemMap child_mapping_methods = MemMap::MapFile(
1057 fd_methods_size_,
1058 PROT_READ | PROT_WRITE,
1059 MAP_PRIVATE,
1060 fd_methods_,
1061 /* start= */ 0,
1062 /* low_4gb= */ false,
1063 "boot-image-methods",
1064 &error_str);
1065
1066 // We don't need the fd anymore.
1067 fd_methods_.reset();
1068
1069 if (!child_mapping_methods.IsValid()) {
1070 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001071 return;
1072 }
Nicolas Geoffrayaf17e5f2020-12-04 09:55:27 +00001073 // We are going to mremap the child mapping into the image:
1074 //
1075 // ImageSection ChildMappingMethods
1076 //
1077 // section start --> -----------
1078 // | |
1079 // | |
1080 // page_start --> | | <----- -----------
1081 // | | | |
1082 // | | | |
1083 // | | | |
1084 // | | | |
1085 // | | | |
1086 // | | | |
1087 // | | | |
1088 // page_end --> | | <----- -----------
1089 // | |
1090 // section end --> -----------
1091 //
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001092 size_t offset = 0;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001093 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1094 const ImageHeader& header = space->GetImageHeader();
1095 const ImageSection& section = header.GetMethodsSection();
1096 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1097 uint8_t* page_end =
1098 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1099 if (page_end <= page_start) {
1100 // Section doesn't contain one aligned entire page.
1101 continue;
1102 }
1103 uint64_t capacity = page_end - page_start;
Nicolas Geoffrayaf17e5f2020-12-04 09:55:27 +00001104 // Walk over methods in the boot image, and check for:
1105 // 1) methods whose class is not initialized in the process, but are in the
1106 // zygote process. For such methods, we need their entrypoints to be stubs
1107 // that do the initialization check.
1108 // 2) native methods whose data pointer is different than the one in the
1109 // zygote. Such methods may have had custom native implementation provided
1110 // by JNI RegisterNatives.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001111 header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffrayd8fd5992020-02-19 22:25:19 +00001112 // Methods in the boot image should never have their single
1113 // implementation flag set (and therefore never have a `data_` pointing
1114 // to an ArtMethod for single implementation).
1115 CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001116 if (method.IsRuntimeMethod()) {
1117 return;
1118 }
Nicolas Geoffrayaf17e5f2020-12-04 09:55:27 +00001119
1120 // Pointer to the method we're currently using.
1121 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
1122 // The data pointer of that method that we want to keep.
1123 uint8_t* data_pointer = pointer + ArtMethod::DataOffset(kRuntimePointerSize).Int32Value();
1124 if (method.IsNative() && data_pointer >= page_start && data_pointer < page_end) {
1125 // The data pointer of the ArtMethod in the shared memory we are going to remap into our
1126 // own mapping. This is the data that we will see after the remap.
1127 uint8_t* new_data_pointer =
1128 child_mapping_methods.Begin() + offset + (data_pointer - page_start);
1129 CopyIfDifferent(new_data_pointer, data_pointer, sizeof(void*));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001130 }
1131
Nicolas Geoffrayaf17e5f2020-12-04 09:55:27 +00001132 // The entrypoint of the method we're currently using and that we want to
1133 // keep.
1134 uint8_t* entry_point_pointer = pointer +
1135 ArtMethod::EntryPointFromQuickCompiledCodeOffset(kRuntimePointerSize).Int32Value();
1136 if (!method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() &&
1137 method.IsStatic() &&
1138 !method.IsConstructor() &&
1139 entry_point_pointer >= page_start &&
1140 entry_point_pointer < page_end) {
1141 // The entry point of the ArtMethod in the shared memory we are going to remap into our
1142 // own mapping. This is the entrypoint that we will see after the remap.
1143 uint8_t* new_entry_point_pointer =
1144 child_mapping_methods.Begin() + offset + (entry_point_pointer - page_start);
1145 CopyIfDifferent(new_entry_point_pointer, entry_point_pointer, sizeof(void*));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001146 }
1147 }, space->Begin(), kRuntimePointerSize);
1148
1149 // Map the memory in the boot image range.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001150 if (mremap(child_mapping_methods.Begin() + offset,
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001151 capacity,
1152 capacity,
1153 MREMAP_FIXED | MREMAP_MAYMOVE,
1154 page_start) == MAP_FAILED) {
1155 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1156 }
1157 offset += capacity;
1158 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001159
1160 // The private mapping created for this process has been mremaped. We can
1161 // reset it.
1162 child_mapping_methods.Reset();
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001163 LOG(INFO) << "Successfully mapped boot image methods";
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001164}
1165
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001166// Return whether a boot image has a profile. This means we'll need to pre-JIT
1167// methods in that profile for performance.
1168static bool HasImageWithProfile() {
1169 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1170 if (!space->GetProfileFile().empty()) {
1171 return true;
1172 }
1173 }
1174 return false;
1175}
1176
Hans Boehmae7c8da2021-02-12 20:17:20 -08001177bool Jit::InZygoteUsingJit() {
1178 Runtime* runtime = Runtime::Current();
1179 return runtime->IsZygote() && HasImageWithProfile() && runtime->UseJitCompilation();
1180}
1181
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001182void Jit::CreateThreadPool() {
1183 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1184 // is not null when we instrument.
1185
1186 // We need peers as we may report the JIT thread, e.g., in the debugger.
1187 constexpr bool kJitPoolNeedsPeers = true;
1188 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1189
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001190 Runtime* runtime = Runtime::Current();
1191 thread_pool_->SetPthreadPriority(
1192 runtime->IsZygote()
1193 ? options_->GetZygoteThreadPoolPthreadPriority()
1194 : options_->GetThreadPoolPthreadPriority());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001195 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001196
Nicolas Geoffrayb2028732020-04-08 15:41:41 +01001197 if (runtime->IsZygote()) {
1198 // To speed up class lookups, generate a type lookup table for
1199 // dex files not backed by oat file.
1200 for (const DexFile* dex_file : runtime->GetClassLinker()->GetBootClassPath()) {
1201 if (dex_file->GetOatDexFile() == nullptr) {
1202 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1203 type_lookup_tables_.push_back(
1204 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1205 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1206 }
1207 }
1208
1209 // Add a task that will verify boot classpath jars that were not
1210 // pre-compiled.
1211 thread_pool_->AddTask(Thread::Current(), new ZygoteVerificationTask());
1212 }
1213
Hans Boehmae7c8da2021-02-12 20:17:20 -08001214 if (InZygoteUsingJit()) {
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001215 // If we have an image with a profile, request a JIT task to
1216 // compile all methods in that profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001217 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001218
1219 // And create mappings to share boot image methods memory from the zygote to
1220 // child processes.
1221
1222 // Compute the total capacity required for the boot image methods.
1223 uint64_t total_capacity = 0;
1224 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1225 const ImageHeader& header = space->GetImageHeader();
1226 const ImageSection& section = header.GetMethodsSection();
1227 // Mappings need to be at the page level.
1228 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1229 uint8_t* page_end =
1230 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1231 if (page_end > page_start) {
1232 total_capacity += (page_end - page_start);
1233 }
1234 }
1235
1236 // Create the child and zygote mappings to the boot image methods.
1237 if (total_capacity > 0) {
1238 // Start with '/boot' and end with '.art' to match the pattern recognized
1239 // by android_os_Debug.cpp for boot images.
1240 const char* name = "/boot-image-methods.art";
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001241 unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001242 if (mem_fd.get() == -1) {
1243 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1244 return;
1245 }
1246 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1247 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1248 return;
1249 }
1250 std::string error_str;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001251
1252 // Create the shared mapping eagerly, as this prevents other processes
1253 // from adding the writable seal.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001254 zygote_mapping_methods_ = MemMap::MapFile(
1255 total_capacity,
1256 PROT_READ | PROT_WRITE,
1257 MAP_SHARED,
1258 mem_fd,
1259 /* start= */ 0,
1260 /* low_4gb= */ false,
1261 "boot-image-methods",
1262 &error_str);
1263
1264 if (!zygote_mapping_methods_.IsValid()) {
1265 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1266 return;
1267 }
1268 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1269 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1270 zygote_mapping_methods_ = MemMap();
1271 return;
1272 }
1273
Nicolas Geoffray831f20f2019-11-03 20:54:28 +00001274 // We should use the F_SEAL_FUTURE_WRITE flag, but this has unexpected
1275 // behavior on private mappings after fork (the mapping becomes shared between
1276 // parent and children), see b/143833776.
1277 // We will seal the write once we are done writing to the shared mapping.
1278 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1279 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1280 zygote_mapping_methods_ = MemMap();
1281 return;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001282 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001283 fd_methods_ = unique_fd(mem_fd.release());
1284 fd_methods_size_ = total_capacity;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001285 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001286 }
1287}
1288
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001289void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +01001290 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001291 if (dex_files.empty()) {
1292 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001293 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001294 Runtime* runtime = Runtime::Current();
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +00001295 // If the runtime is debuggable, no need to precompile methods.
1296 if (runtime->IsSystemServer() &&
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001297 UseJitCompilation() &&
1298 options_->UseProfiledJitCompilation() &&
1299 HasImageWithProfile() &&
Nicolas Geoffrayc76232e2020-03-18 11:23:33 +00001300 !runtime->IsJavaDebuggable()) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001301 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1302 }
1303}
1304
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001305bool Jit::CompileMethodFromProfile(Thread* self,
1306 ClassLinker* class_linker,
1307 uint32_t method_idx,
1308 Handle<mirror::DexCache> dex_cache,
1309 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001310 bool add_to_queue,
1311 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001312 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1313 method_idx, dex_cache, class_loader);
1314 if (method == nullptr) {
1315 self->ClearException();
1316 return false;
1317 }
1318 if (!method->IsCompilable() || !method->IsInvokable()) {
1319 return false;
1320 }
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001321 if (method->IsPreCompiled()) {
1322 // Already seen by another profile.
1323 return false;
1324 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001325 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1326 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1327 class_linker->IsQuickGenericJniStub(entry_point) ||
Nicolas Geoffray2e299f42020-10-08 20:27:22 +01001328 (entry_point == interpreter::GetNterpEntryPoint()) ||
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001329 // We explicitly check for the stub. The trampoline is for methods backed by
1330 // a .oat file that has a compiled version of the method.
1331 (entry_point == GetQuickResolutionStub())) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001332 method->SetPreCompiled();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001333 if (!add_to_queue) {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001334 CompileMethod(method, self, CompilationKind::kOptimized, /* prejit= */ true);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001335 } else {
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001336 Task* task = new JitCompileTask(
1337 method, JitCompileTask::TaskKind::kPreCompile, CompilationKind::kOptimized);
David Srbeckybfcea3d2019-08-05 15:44:00 +01001338 if (compile_after_boot) {
1339 MutexLock mu(Thread::Current(), boot_completed_lock_);
1340 if (!boot_completed_) {
1341 tasks_after_boot_.push_back(task);
1342 return true;
1343 }
1344 DCHECK(tasks_after_boot_.empty());
1345 }
1346 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001347 return true;
1348 }
1349 }
1350 return false;
1351}
1352
1353uint32_t Jit::CompileMethodsFromBootProfile(
1354 Thread* self,
1355 const std::vector<const DexFile*>& dex_files,
1356 const std::string& profile_file,
1357 Handle<mirror::ClassLoader> class_loader,
1358 bool add_to_queue) {
1359 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1360
1361 if (profile.Fd() == -1) {
1362 PLOG(WARNING) << "No boot profile: " << profile_file;
1363 return 0u;
1364 }
1365
1366 ProfileBootInfo profile_info;
1367 if (!profile_info.Load(profile.Fd(), dex_files)) {
1368 LOG(ERROR) << "Could not load profile file: " << profile_file;
1369 return 0u;
1370 }
1371
1372 ScopedObjectAccess soa(self);
1373 VariableSizedHandleScope handles(self);
1374 std::vector<Handle<mirror::DexCache>> dex_caches;
1375 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1376 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1377 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1378 }
1379
1380 uint32_t added_to_queue = 0;
1381 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1382 if (CompileMethodFromProfile(self,
1383 class_linker,
1384 pair.second,
1385 dex_caches[pair.first],
1386 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001387 add_to_queue,
1388 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001389 ++added_to_queue;
1390 }
1391 }
1392 return added_to_queue;
1393}
1394
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001395uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001396 Thread* self,
1397 const std::vector<const DexFile*>& dex_files,
1398 const std::string& profile_file,
1399 Handle<mirror::ClassLoader> class_loader,
1400 bool add_to_queue) {
1401
1402 if (profile_file.empty()) {
1403 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001404 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001405 }
1406
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001407 // We don't generate boot profiles on device, therefore we don't
1408 // need to lock the file.
1409 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001410
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001411 if (profile.Fd() == -1) {
1412 PLOG(WARNING) << "No profile: " << profile_file;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001413 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001414 }
1415
1416 ProfileCompilationInfo profile_info;
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001417 if (!profile_info.Load(profile.Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001418 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001419 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001420 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001421 ScopedObjectAccess soa(self);
1422 StackHandleScope<1> hs(self);
1423 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001424 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001425 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001426 for (const DexFile* dex_file : dex_files) {
Martin Stjernholme58624f2019-09-20 15:53:40 +01001427 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1428 // The ART module jars are already preopted.
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001429 continue;
1430 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001431
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001432 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001433 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001434 if (!profile_info.GetClassesAndMethods(*dex_file,
1435 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001436 &all_methods,
1437 &all_methods,
1438 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001439 // This means the profile file did not reference the dex file, which is the case
1440 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001441 continue;
1442 }
1443 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1444 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001445
1446 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001447 if (CompileMethodFromProfile(self,
1448 class_linker,
1449 method_idx,
1450 dex_cache,
1451 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001452 add_to_queue,
1453 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001454 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001455 }
1456 }
1457 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001458
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001459 // Add a task to run when all compilation is done.
1460 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001461 MutexLock mu(Thread::Current(), boot_completed_lock_);
1462 if (!boot_completed_) {
1463 tasks_after_boot_.push_back(task);
1464 } else {
1465 DCHECK(tasks_after_boot_.empty());
1466 thread_pool_->AddTask(self, task);
1467 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001468 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001469}
1470
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +00001471bool Jit::IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +01001472 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001473 // We do not want to compile such methods.
1474 return true;
1475 }
1476 if (method->IsNative()) {
1477 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001478 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1479 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001480 // MethodHandle and VarHandle invocation methods are required to throw an
1481 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001482 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001483 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1484 // stubs. Since these stubs have different stack representations we can then crash in stack
1485 // walking (b/78151261).
1486 return true;
1487 }
1488 }
1489 return false;
1490}
1491
David Srbeckye3fc2d12018-11-30 13:41:14 +00001492bool Jit::MaybeCompileMethod(Thread* self,
1493 ArtMethod* method,
1494 uint32_t old_count,
1495 uint32_t new_count,
1496 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001497 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001498 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001499 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001500 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001501 if (!NeedsClinitCheckBeforeCall(method) ||
1502 method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001503 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1504 if (entry_point != nullptr) {
1505 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1506 return true;
1507 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001508 }
1509 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001510
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001511 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001512 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001513 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001514 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +00001515 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +00001516 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +00001517 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001518 DCHECK_GT(WarmMethodThreshold(), 0);
1519 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1520 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1521 DCHECK_GE(PriorityThreadWeight(), 1);
1522 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001523
David Srbeckye3fc2d12018-11-30 13:41:14 +00001524 if (UseJitCompilation()) {
1525 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1526 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001527 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001528 thread_pool_->AddTask(
1529 self,
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001530 new JitCompileTask(
1531 method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
Calin Juravleffc87072016-04-20 14:22:09 +01001532 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001533 }
1534 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001535 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001536 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001537 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001538 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001539 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001540 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001541 thread_pool_->AddTask(
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001542 self,
1543 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001544 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001545 }
1546 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001547 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001548}
1549
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001550void Jit::EnqueueOptimizedCompilation(ArtMethod* method, Thread* self) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00001551 if (thread_pool_ == nullptr) {
1552 return;
1553 }
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001554 // We arrive here after a baseline compiled code has reached its baseline
Nicolas Geoffrayb96d6f32020-08-05 15:40:29 +01001555 // hotness threshold. If we're not only using the baseline compiler, enqueue a compilation
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001556 // task that will compile optimize the method.
Nicolas Geoffrayb96d6f32020-08-05 15:40:29 +01001557 if (!options_->UseBaselineCompiler()) {
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001558 thread_pool_->AddTask(
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001559 self,
1560 new JitCompileTask(method,
1561 JitCompileTask::TaskKind::kCompile,
1562 CompilationKind::kOptimized));
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001563 }
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001564}
1565
Alex Light59b950f2018-10-08 10:43:06 -07001566class ScopedSetRuntimeThread {
1567 public:
1568 explicit ScopedSetRuntimeThread(Thread* self)
1569 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1570 self_->SetIsRuntimeThread(true);
1571 }
1572
1573 ~ScopedSetRuntimeThread() {
1574 self_->SetIsRuntimeThread(was_runtime_thread_);
1575 }
1576
1577 private:
1578 Thread* self_;
1579 bool was_runtime_thread_;
1580};
1581
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001582void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001583 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001584 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001585 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001586 if (np_method->IsCompilable()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001587 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1588 // conflicts with jitzygote optimizations.
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001589 JitCompileTask compile_task(
1590 method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOptimized);
Alex Light59b950f2018-10-08 10:43:06 -07001591 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1592 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001593 compile_task.Run(thread);
1594 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001595 return;
1596 }
1597
Nicolas Geoffray1a277a62020-07-31 16:07:17 +01001598 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001599}
1600
1601void Jit::WaitForCompilationToFinish(Thread* self) {
1602 if (thread_pool_ != nullptr) {
1603 thread_pool_->Wait(self, false, false);
1604 }
1605}
1606
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001607void Jit::Stop() {
1608 Thread* self = Thread::Current();
1609 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1610 WaitForCompilationToFinish(self);
1611 GetThreadPool()->StopWorkers(self);
1612 WaitForCompilationToFinish(self);
1613}
1614
1615void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001616 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001617}
1618
Andreas Gampef149b3f2016-11-16 14:58:24 -08001619ScopedJitSuspend::ScopedJitSuspend() {
1620 jit::Jit* jit = Runtime::Current()->GetJit();
1621 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1622 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001623 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001624 }
1625}
1626
1627ScopedJitSuspend::~ScopedJitSuspend() {
1628 if (was_on_) {
1629 DCHECK(Runtime::Current()->GetJit() != nullptr);
1630 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001631 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001632 }
1633}
1634
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001635static void* RunPollingThread(void* arg) {
1636 Jit* jit = reinterpret_cast<Jit*>(arg);
1637 do {
1638 sleep(10);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001639 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001640
1641 // We will suspend other threads: we can only do that if we're attached to the
1642 // runtime.
1643 Runtime* runtime = Runtime::Current();
1644 bool thread_attached = runtime->AttachCurrentThread(
1645 "BootImagePollingThread",
1646 /* as_daemon= */ true,
1647 /* thread_group= */ nullptr,
1648 /* create_peer= */ false);
1649 CHECK(thread_attached);
1650
1651 {
1652 // Prevent other threads from running while we are remapping the boot image
1653 // ArtMethod's. Native threads might still be running, but they cannot
1654 // change the contents of ArtMethod's.
1655 ScopedSuspendAll ssa(__FUNCTION__);
1656 runtime->GetJit()->MapBootImageMethods();
1657 }
1658
1659 Runtime::Current()->DetachCurrentThread();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001660 return nullptr;
1661}
1662
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001663void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraye9455f62019-08-15 20:57:04 +01001664 // Clear the potential boot tasks inherited from the zygote.
1665 {
1666 MutexLock mu(Thread::Current(), boot_completed_lock_);
1667 tasks_after_boot_.clear();
1668 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001669
Mathieu Chartier3a6ef942019-12-18 11:04:42 -08001670 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001671 // Check if we'll need to remap the boot image methods.
1672 if (!is_zygote && fd_methods_ != -1) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001673 // Create a thread that will poll the status of zygote compilation, and map
1674 // the private mapping of boot image methods.
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001675 // For child zygote, we instead query IsCompilationNotified() post zygote fork.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001676 zygote_mapping_methods_.ResetInForkedProcess();
1677 pthread_t polling_thread;
1678 pthread_attr_t attr;
1679 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1680 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1681 "PTHREAD_CREATE_DETACHED");
1682 CHECK_PTHREAD_CALL(
1683 pthread_create,
1684 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1685 "Methods maps thread");
1686 }
1687
Mathieu Chartier3a6ef942019-12-18 11:04:42 -08001688 if (is_zygote || runtime->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001689 // Delete the thread pool, we are not going to JIT.
1690 thread_pool_.reset(nullptr);
1691 return;
1692 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001693 // At this point, the compiler options have been adjusted to the particular configuration
1694 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001695 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001696
1697 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001698 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001699 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001700
Nicolas Geoffray2c2248c2020-03-06 14:50:45 +00001701 if (is_system_server && HasImageWithProfile()) {
Nicolas Geoffraya67daeb2019-08-12 10:41:25 +01001702 // Disable garbage collection: we don't want it to delete methods we're compiling
1703 // through boot and system server profiles.
1704 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1705 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001706 }
Nicolas Geoffray371390f2019-09-27 09:57:38 +01001707
1708 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1709 // applies to a child.
1710 NativeDebugInfoPostFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001711}
1712
1713void Jit::PreZygoteFork() {
1714 if (thread_pool_ == nullptr) {
1715 return;
1716 }
1717 thread_pool_->DeleteThreads();
David Srbecky1550a662019-08-14 17:16:46 +01001718
1719 NativeDebugInfoPreFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001720}
1721
1722void Jit::PostZygoteFork() {
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001723 Runtime* runtime = Runtime::Current();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001724 if (thread_pool_ == nullptr) {
Nicolas Geoffrayecd95022020-01-27 09:35:10 +00001725 // If this is a child zygote, check if we need to remap the boot image
1726 // methods.
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001727 if (runtime->IsZygote() &&
Nicolas Geoffray58cc76d2020-02-18 10:18:54 +00001728 fd_methods_ != -1 &&
1729 code_cache_->GetZygoteMap()->IsCompilationNotified()) {
Nicolas Geoffrayecd95022020-01-27 09:35:10 +00001730 ScopedSuspendAll ssa(__FUNCTION__);
1731 MapBootImageMethods();
1732 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001733 return;
1734 }
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001735 if (runtime->IsZygote() && code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
Nicolas Geoffray8852e532019-10-30 09:43:35 +00001736 // Copy the boot image methods data to the mappings we created to share
1737 // with the children. We do this here as we are the only thread running and
1738 // we don't risk other threads concurrently updating the ArtMethod's.
1739 CHECK_EQ(GetTaskCount(), 1);
1740 NotifyZygoteCompilationDone();
1741 CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1742 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001743 thread_pool_->CreateThreads();
Nicolas Geoffray4bf753d2020-12-14 20:33:53 +00001744 thread_pool_->SetPthreadPriority(
1745 runtime->IsZygote()
1746 ? options_->GetZygoteThreadPoolPthreadPriority()
1747 : options_->GetThreadPoolPthreadPriority());
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001748}
1749
David Srbeckybfcea3d2019-08-05 15:44:00 +01001750void Jit::BootCompleted() {
1751 Thread* self = Thread::Current();
1752 std::deque<Task*> tasks;
1753 {
1754 MutexLock mu(self, boot_completed_lock_);
1755 tasks = std::move(tasks_after_boot_);
1756 boot_completed_ = true;
1757 }
1758 for (Task* task : tasks) {
1759 thread_pool_->AddTask(self, task);
1760 }
1761}
1762
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001763bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1764 return !is_for_shared_region ||
1765 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001766}
1767
1768bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001769 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001770}
1771
1772bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001773 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001774}
1775
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001776bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1777 if (!is_for_shared_region) {
1778 return cls->IsInitialized();
1779 } else {
1780 // Look up the class status in the oat file.
1781 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1782 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1783 // In case we run without an image there won't be a backing oat file.
1784 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1785 return false;
1786 }
1787 uint16_t class_def_index = cls->GetDexClassDefIndex();
1788 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1789 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001790}
1791
Nicolas Geoffray00391822019-12-10 10:17:23 +00001792void Jit::EnqueueCompilationFromNterp(ArtMethod* method, Thread* self) {
1793 if (thread_pool_ == nullptr) {
1794 return;
1795 }
1796 if (GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1797 // If we already have compiled code for it, nterp may be stuck in a loop.
1798 // Compile OSR.
1799 thread_pool_->AddTask(
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001800 self,
1801 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kOsr));
Nicolas Geoffray00391822019-12-10 10:17:23 +00001802 return;
1803 }
Nicolas Geoffray4d7e1a82020-01-26 19:57:02 +00001804 if (GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray4d7e1a82020-01-26 19:57:02 +00001805 thread_pool_->AddTask(
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001806 self,
1807 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile, CompilationKind::kBaseline));
Nicolas Geoffray4d7e1a82020-01-26 19:57:02 +00001808 } else {
1809 thread_pool_->AddTask(
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001810 self,
1811 new JitCompileTask(method,
1812 JitCompileTask::TaskKind::kCompile,
1813 CompilationKind::kOptimized));
Nicolas Geoffray4d7e1a82020-01-26 19:57:02 +00001814 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00001815}
1816
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001817} // namespace jit
1818} // namespace art