blob: 48a51f1c5ac79855e4613a12f3f41ca8b6cc6c35 [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 Markoc7aa87e2018-05-24 15:19:52 +010030#include "class_root.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070031#include "debugger.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010032#include "dex/type_lookup_table.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010033#include "gc/space/image_space.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010034#include "entrypoints/entrypoint_utils-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "entrypoints/runtime_asm_entrypoints.h"
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010036#include "image-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000038#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010040#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010041#include "mirror/method_handle_impl.h"
42#include "mirror/var_handle.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010043#include "oat_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010044#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000045#include "oat_quick_method_header.h"
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +010046#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070047#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000048#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080049#include "runtime.h"
50#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070051#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000052#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070053#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010054#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080055
Nicolas Geoffray623d4f12019-09-30 13:45:51 +010056using android::base::unique_fd;
57
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080058namespace art {
59namespace jit {
60
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000061static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000062
Orion Hodson4fa78a02019-09-12 09:35:24 +010063// Maximum permitted threshold value.
64static constexpr uint32_t kJitMaxThreshold = std::numeric_limits<uint16_t>::max();
65
Andreas Gampe7897cec2017-07-19 16:28:59 -070066// Different compilation threshold constants. These can be overridden on the command line.
Orion Hodson4fa78a02019-09-12 09:35:24 +010067
68// Non-debug default
69static constexpr uint32_t kJitDefaultCompileThreshold = 20 * kJitSamplesBatchSize;
70// Fast-debug build.
71static constexpr uint32_t kJitStressDefaultCompileThreshold = 2 * kJitSamplesBatchSize;
72// Slow-debug build.
73static constexpr uint32_t kJitSlowStressDefaultCompileThreshold = 2;
74
75// Different warm-up threshold constants. These default to the equivalent compile thresholds divided
76// by 2, but can be overridden at the command-line.
77static constexpr uint32_t kJitDefaultWarmUpThreshold = kJitDefaultCompileThreshold / 2;
78static constexpr uint32_t kJitStressDefaultWarmUpThreshold = kJitStressDefaultCompileThreshold / 2;
79static constexpr uint32_t kJitSlowStressDefaultWarmUpThreshold =
80 kJitSlowStressDefaultCompileThreshold / 2;
Andreas Gampe7897cec2017-07-19 16:28:59 -070081
David Srbecky21821472019-07-29 15:10:31 +010082DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
83
Mathieu Chartier72918ea2016-03-24 11:07:06 -070084// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080085void* Jit::jit_library_handle_ = nullptr;
David Srbecky46b53532019-08-06 13:39:05 +010086JitCompilerInterface* Jit::jit_compiler_ = nullptr;
87JitCompilerInterface* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070088
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080089JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080090 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010091 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +000092 jit_options->use_tiered_jit_compilation_ =
93 options.GetOrDefault(RuntimeArgumentMap::UseTieredJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000094
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000095 jit_options->code_cache_initial_capacity_ =
96 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
97 jit_options->code_cache_max_capacity_ =
98 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070099 jit_options->dump_info_on_shutdown_ =
100 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +0100101 jit_options->profile_saver_options_ =
102 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100103 jit_options->thread_pool_pthread_priority_ =
104 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000105
Orion Hodson4fa78a02019-09-12 09:35:24 +0100106 // Set default compile threshold to aide with sanity checking defaults.
107 jit_options->compile_threshold_ =
108 kIsDebugBuild
109 ? (Jit::kSlowMode
110 ? kJitSlowStressDefaultCompileThreshold
111 : kJitStressDefaultCompileThreshold)
112 : kJitDefaultCompileThreshold;
113
114 // When not running in slow-mode, thresholds are quantized to kJitSamplesbatchsize.
115 const uint32_t kJitThresholdStep = Jit::kSlowMode ? 1u : kJitSamplesBatchSize;
116
117 // Set default warm-up threshold to aide with sanity checking defaults.
118 jit_options->warmup_threshold_ =
119 kIsDebugBuild ? (Jit::kSlowMode
120 ? kJitSlowStressDefaultWarmUpThreshold
121 : kJitStressDefaultWarmUpThreshold)
122 : kJitDefaultWarmUpThreshold;
123
124 // Warmup threshold should be less than compile threshold (so long as compile threshold is not
125 // zero == JIT-on-first-use).
126 DCHECK_LT(jit_options->warmup_threshold_, jit_options->compile_threshold_);
127 DCHECK_EQ(RoundUp(jit_options->warmup_threshold_, kJitThresholdStep),
128 jit_options->warmup_threshold_);
129
Andreas Gampe7897cec2017-07-19 16:28:59 -0700130 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
131 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
Andreas Gampe7897cec2017-07-19 16:28:59 -0700132 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100133 jit_options->compile_threshold_ = RoundUp(jit_options->compile_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000134
135 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
136 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000137 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100138 jit_options->warmup_threshold_ = RoundUp(jit_options->warmup_threshold_, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000139
140 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
141 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000142 } else {
143 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
Orion Hodson4fa78a02019-09-12 09:35:24 +0100144 if (jit_options->osr_threshold_ > kJitMaxThreshold) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000145 jit_options->osr_threshold_ =
Orion Hodson4fa78a02019-09-12 09:35:24 +0100146 RoundDown(kJitMaxThreshold, kJitThresholdStep);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000147 }
148 }
Orion Hodson4fa78a02019-09-12 09:35:24 +0100149 jit_options->osr_threshold_ = RoundUp(jit_options->osr_threshold_, kJitThresholdStep);
150
151 // Enforce ordering constraints between thresholds if not jit-on-first-use (when the compile
152 // threshold is 0).
153 if (jit_options->compile_threshold_ != 0) {
154 // Clamp thresholds such that OSR > compile > warm-up (see Jit::MaybeCompileMethod).
155 jit_options->osr_threshold_ = std::clamp(jit_options->osr_threshold_,
156 2u * kJitThresholdStep,
157 RoundDown(kJitMaxThreshold, kJitThresholdStep));
158 jit_options->compile_threshold_ = std::clamp(jit_options->compile_threshold_,
159 kJitThresholdStep,
160 jit_options->osr_threshold_ - kJitThresholdStep);
161 jit_options->warmup_threshold_ =
162 std::clamp(jit_options->warmup_threshold_,
163 0u,
164 jit_options->compile_threshold_ - kJitThresholdStep);
165 }
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000166
Calin Juravleb2771b42016-04-07 17:09:25 +0100167 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
168 jit_options->priority_thread_weight_ =
169 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
170 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
171 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
172 } else if (jit_options->priority_thread_weight_ == 0) {
173 LOG(FATAL) << "Priority thread weight cannot be 0.";
174 }
175 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100176 jit_options->priority_thread_weight_ = std::max(
177 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
178 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100179 }
180
Calin Juravle155ff3d2016-04-27 14:14:58 +0100181 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100182 jit_options->invoke_transition_weight_ =
183 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100184 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
185 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
186 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100187 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100188 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100189 } else {
190 jit_options->invoke_transition_weight_ = std::max(
191 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800192 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100193 }
194
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800195 return jit_options;
196}
197
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700198void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000199 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700200 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000201 MutexLock mu(Thread::Current(), lock_);
202 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700203}
204
Calin Juravleb8e69992016-03-09 15:37:48 +0000205void Jit::DumpForSigQuit(std::ostream& os) {
206 DumpInfo(os);
207 ProfileSaver::DumpInstanceInfo(os);
208}
209
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700210void Jit::AddTimingLogger(const TimingLogger& logger) {
211 cumulative_timings_.AddLogger(logger);
212}
213
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100214Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
215 : code_cache_(code_cache),
216 options_(options),
David Srbeckybfcea3d2019-08-05 15:44:00 +0100217 boot_completed_lock_("Jit::boot_completed_lock_"),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100218 cumulative_timings_("JIT timings"),
219 memory_use_("Memory used for compilation", 16),
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000220 lock_("JIT memory use lock"),
221 zygote_mapping_methods_(),
222 fd_methods_(-1),
223 fd_methods_size_(0) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800224
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100225Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000226 if (jit_load_ == nullptr) {
227 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800228 return nullptr;
229 }
David Srbecky46b53532019-08-06 13:39:05 +0100230 jit_compiler_ = (jit_load_)();
231 if (jit_compiler_ == nullptr) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000232 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
233 return nullptr;
234 }
235 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000236
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000237 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000238 // With 'perf', we want a 1-1 mapping between an address and a method.
239 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
240 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000241 if (code_cache->GetGarbageCollectCode()) {
David Srbecky46b53532019-08-06 13:39:05 +0100242 code_cache->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000243 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
244 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100245
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000246 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000247 << PrettySize(options->GetCodeCacheInitialCapacity())
248 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000249 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100250 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100251
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +0000252 // We want to know whether the compiler is compiling baseline, as this
253 // affects how we GC ProfilingInfos.
254 for (const std::string& option : Runtime::Current()->GetCompilerOptions()) {
255 if (option == "--baseline") {
256 options->SetUseBaselineCompiler();
257 break;
258 }
259 }
260
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100261 // Notify native debugger about the classes already loaded before the creation of the jit.
262 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800263 return jit.release();
264}
265
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000266template <typename T>
267bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
268 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
269 if (*address == nullptr) {
270 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
271 return false;
272 }
273 return true;
274}
275
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000276bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800277 jit_library_handle_ = dlopen(
278 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
279 if (jit_library_handle_ == nullptr) {
280 std::ostringstream oss;
281 oss << "JIT could not load libart-compiler.so: " << dlerror();
282 *error_msg = oss.str();
283 return false;
284 }
David Srbecky46b53532019-08-06 13:39:05 +0100285 if (!LoadSymbol(&jit_load_, "jit_load", error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800286 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000287 return false;
288 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700289 return true;
290}
291
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100292bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr, bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100293 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800294 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000295
Alex Light0fa17862017-10-24 13:43:05 -0700296 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100297 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700298 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
299 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
300 << " due to not being safe to jit according to runtime-callbacks. For example, there"
301 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700302 return false;
303 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100304
Alex Light986914b2019-11-19 01:12:25 +0000305 if (!method->IsCompilable()) {
306 DCHECK(method->GetDeclaringClass()->IsObsoleteObject() ||
307 method->IsProxyMethod()) << method->PrettyMethod();
308 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to method being made "
309 << "obsolete while waiting for JIT task to run. This probably happened due to "
310 << "concurrent structural class redefinition.";
311 return false;
312 }
313
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100314 // Don't compile the method if we are supposed to be deoptimized.
315 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
316 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700317 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100318 return false;
319 }
320
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000321 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100322 if (osr && GetCodeCache()->IsSharedRegion(*region)) {
323 VLOG(jit) << "JIT not osr compiling "
324 << method->PrettyMethod()
325 << " due to using shared region";
326 return false;
327 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000328
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000329 // If we get a request to compile a proxy method, we pass the actual Java method
330 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700331 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +0000332 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr, prejit, baseline, region)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100333 return false;
334 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100335
336 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700337 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +0000338 << " osr=" << std::boolalpha << osr
339 << " baseline=" << std::boolalpha << baseline;
David Srbecky46b53532019-08-06 13:39:05 +0100340 bool success = jit_compiler_->CompileMethod(self, region, method_to_compile, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700341 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100342 if (!success) {
343 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700344 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100345 << " osr=" << std::boolalpha << osr;
346 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800347 if (kIsDebugBuild) {
348 if (self->IsExceptionPending()) {
349 mirror::Throwable* exception = self->GetException();
350 LOG(FATAL) << "No pending exception expected after compiling "
351 << ArtMethod::PrettyMethod(method)
352 << ": "
353 << exception->Dump();
354 }
355 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100356 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800357}
358
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800359void Jit::WaitForWorkersToBeCreated() {
360 if (thread_pool_ != nullptr) {
361 thread_pool_->WaitForWorkersToBeCreated();
362 }
363}
364
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800365void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100366 Thread* self = Thread::Current();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100367 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700368 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100369 {
370 ScopedSuspendAll ssa(__FUNCTION__);
371 // Clear thread_pool_ field while the threads are suspended.
372 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700373 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100374 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700375
376 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000377 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700378 pool->StopWorkers(self);
379 pool->RemoveAllTasks(self);
380 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100381 // We could just suspend all threads, but we know those threads
382 // will finish in a short period, so it's not worth adding a suspend logic
383 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700384 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800385 }
386}
387
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000388void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800389 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100390 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100391 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100392 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000393}
394
395void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100396 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
397 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100398 }
399}
400
Siva Chandra05d24152016-01-05 17:43:17 -0800401bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100402 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800403}
404
Nicolas Geoffray35122442016-03-02 12:05:30 +0000405bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
406 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
407}
408
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800409Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100410 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
411 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700412 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100413 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700414 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800415 DeleteThreadPool();
David Srbecky46b53532019-08-06 13:39:05 +0100416 if (jit_compiler_ != nullptr) {
417 delete jit_compiler_;
418 jit_compiler_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800419 }
420 if (jit_library_handle_ != nullptr) {
421 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700422 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800423 }
424}
425
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000426void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100427 if (!Runtime::Current()->UseJitCompilation()) {
428 // No need to notify if we only use the JIT to save profiles.
429 return;
430 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000431 jit::Jit* jit = Runtime::Current()->GetJit();
David Srbecky46b53532019-08-06 13:39:05 +0100432 if (jit->jit_compiler_->GenerateDebugInfo()) {
433 jit_compiler_->TypesLoaded(&type, 1);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000434 }
435}
436
437void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
438 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100439 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700440 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000441 return true;
442 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800443 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000444 };
445
David Srbecky46b53532019-08-06 13:39:05 +0100446 if (jit_compiler_->GenerateDebugInfo()) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000447 ScopedObjectAccess so(Thread::Current());
448
449 CollectClasses visitor;
450 linker->VisitClasses(&visitor);
David Srbecky46b53532019-08-06 13:39:05 +0100451 jit_compiler_->TypesLoaded(visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000452 }
453}
454
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000455extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700456 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000457 const uint8_t* native_pc,
458 JValue* result,
459 const char* shorty,
460 Thread* self);
461
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000462OsrData* Jit::PrepareForOsr(ArtMethod* method, uint32_t dex_pc, uint32_t* vregs) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000463 if (!kEnableOnStackReplacement) {
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000464 return nullptr;
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000465 }
466
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000467 // Cheap check if the method has been compiled already. That's an indicator that we should
468 // osr into it.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000469 if (!GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
470 return nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000471 }
472
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000473 // Fetch some data before looking up for an OSR method. We don't want thread
474 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
475 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000476 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800477 const size_t number_of_vregs = accessor.RegistersSize();
David Sehr709b0702016-10-13 09:12:37 -0700478 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000479 OsrData* osr_data = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000480
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000481 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700482 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000483 const OatQuickMethodHeader* osr_method = GetCodeCache()->LookupOsrMethodHeader(method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000484 if (osr_method == nullptr) {
485 // No osr method yet, just return to the interpreter.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000486 return nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000487 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000488
David Srbecky052f8ca2018-04-26 15:42:54 +0100489 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000490
491 // Find stack map starting at the target dex_pc.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000492 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000493 if (!stack_map.IsValid()) {
494 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
495 // hope that the next branch has one.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000496 return nullptr;
Aart Bik29bdaee2016-05-18 15:44:07 -0700497 }
498
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000499 // We found a stack map, now fill the frame with dex register values from the interpreter's
500 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100501 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Artem Serov2808be82018-12-20 19:15:11 +0000502 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000503
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000504 size_t frame_size = osr_method->GetFrameSizeInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000505
506 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
507 // stack.
508 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
509 // but that is engineering complexity not worth the effort for something like OSR.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000510 osr_data = reinterpret_cast<OsrData*>(malloc(sizeof(OsrData) + frame_size));
511 if (osr_data == nullptr) {
512 return nullptr;
513 }
514 memset(osr_data, 0, sizeof(OsrData) + frame_size);
515 osr_data->frame_size = frame_size;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000516
517 // Art ABI: ArtMethod is at the bottom of the stack.
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000518 osr_data->memory[0] = method;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000519
David Srbeckyfd89b072018-06-03 12:00:22 +0100520 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000521 // If we don't have a dex register map, then there are no live dex registers at
522 // this dex pc.
523 } else {
524 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100525 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000526 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000527 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000528 continue;
529 }
530
531 if (location == DexRegisterLocation::Kind::kConstant) {
532 // We skip constants because the compiled code knows how to handle them.
533 continue;
534 }
535
David Srbecky7dc11782016-02-25 13:23:56 +0000536 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000537
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000538 int32_t vreg_value = vregs[vreg];
David Srbeckye1402122018-06-13 18:20:45 +0100539 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000540 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
541 DCHECK_GT(slot_offset, 0);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000542 (reinterpret_cast<int32_t*>(osr_data->memory))[slot_offset / sizeof(int32_t)] = vreg_value;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000543 }
544 }
545
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000546 osr_data->native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000547 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000548 VLOG(jit) << "Jumping to "
549 << method_name
550 << "@"
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000551 << std::hex << reinterpret_cast<uintptr_t>(osr_data->native_pc);
552 }
553 return osr_data;
554}
555
556bool Jit::MaybeDoOnStackReplacement(Thread* thread,
557 ArtMethod* method,
558 uint32_t dex_pc,
559 int32_t dex_pc_offset,
560 JValue* result) {
561 Jit* jit = Runtime::Current()->GetJit();
562 if (jit == nullptr) {
563 return false;
564 }
565
566 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
567 // Don't attempt to do an OSR if we are close to the stack limit. Since
568 // the interpreter frames are still on stack, OSR has the potential
569 // to stack overflow even for a simple loop.
570 // b/27094810.
571 return false;
572 }
573
574 // Get the actual Java method if this method is from a proxy class. The compiler
575 // and the JIT code cache do not expect methods from proxy classes.
576 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
577
578 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
579 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
580 // disable OSR when single stepping, but that's currently hard to know at this point.
581 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
582 return false;
583 }
584
585 ShadowFrame* shadow_frame = thread->GetManagedStack()->GetTopShadowFrame();
586 OsrData* osr_data = jit->PrepareForOsr(method,
587 dex_pc + dex_pc_offset,
588 shadow_frame->GetVRegArgs(0));
589
590 if (osr_data == nullptr) {
591 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000592 }
593
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000594 {
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000595 thread->PopShadowFrame();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000596 ManagedStack fragment;
597 thread->PushManagedStackFragment(&fragment);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000598 (*art_quick_osr_stub)(osr_data->memory,
599 osr_data->frame_size,
600 osr_data->native_pc,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000601 result,
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000602 method->GetShorty(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000603 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000604
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000605 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
606 thread->DeoptimizeWithDeoptimizationException(result);
607 }
608 thread->PopManagedStackFragment(fragment);
609 }
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000610 free(osr_data);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000611 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffray57cacb72019-12-08 22:07:08 +0000612 VLOG(jit) << "Done running OSR code for " << method->PrettyMethod();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000613 return true;
614}
615
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000616void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
617 if (bytes > 4 * MB) {
618 LOG(INFO) << "Compiler allocated "
619 << PrettySize(bytes)
620 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700621 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000622 }
623 MutexLock mu(Thread::Current(), lock_);
624 memory_use_.AddValue(bytes);
625}
626
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000627void Jit::NotifyZygoteCompilationDone() {
628 if (fd_methods_ == -1) {
629 return;
630 }
631
632 size_t offset = 0;
633 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
634 const ImageHeader& header = space->GetImageHeader();
635 const ImageSection& section = header.GetMethodsSection();
636 // Because mremap works at page boundaries, we can only handle methods
637 // within a page range. For methods that falls above or below the range,
638 // the child processes will copy their contents to their private mapping
639 // in `child_mapping_methods`. See `MapBootImageMethods`.
640 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
641 uint8_t* page_end =
642 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
643 if (page_end > page_start) {
644 uint64_t capacity = page_end - page_start;
645 memcpy(zygote_mapping_methods_.Begin() + offset, page_start, capacity);
646 offset += capacity;
647 }
648 }
649
650 // Do an msync to ensure we are not affected by writes still being in caches.
651 if (msync(zygote_mapping_methods_.Begin(), fd_methods_size_, MS_SYNC) != 0) {
652 PLOG(WARNING) << "Failed to sync boot image methods memory";
653 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
654 return;
655 }
656
657 // We don't need the shared mapping anymore, and we need to drop it in case
658 // the file hasn't been sealed writable.
659 zygote_mapping_methods_ = MemMap::Invalid();
660
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000661 // Seal writes now. Zygote and children will map the memory private in order
662 // to write to it.
663 if (fcntl(fd_methods_, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_WRITE) == -1) {
664 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
665 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
666 return;
667 }
668
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000669 std::string error_str;
670 MemMap child_mapping_methods = MemMap::MapFile(
671 fd_methods_size_,
672 PROT_READ | PROT_WRITE,
673 MAP_PRIVATE,
674 fd_methods_,
675 /* start= */ 0,
676 /* low_4gb= */ false,
677 "boot-image-methods",
678 &error_str);
679
680 if (!child_mapping_methods.IsValid()) {
681 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
682 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedFailure);
683 return;
684 }
685
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000686 // Ensure the contents are the same as before: there was a window between
687 // the memcpy and the sealing where other processes could have changed the
688 // contents.
689 // Note this would not be needed if we could have used F_SEAL_FUTURE_WRITE,
690 // see b/143833776.
691 offset = 0;
692 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
693 const ImageHeader& header = space->GetImageHeader();
694 const ImageSection& section = header.GetMethodsSection();
695 // Because mremap works at page boundaries, we can only handle methods
696 // within a page range. For methods that falls above or below the range,
697 // the child processes will copy their contents to their private mapping
698 // in `child_mapping_methods`. See `MapBootImageMethods`.
699 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
700 uint8_t* page_end =
701 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
702 if (page_end > page_start) {
703 uint64_t capacity = page_end - page_start;
704 if (memcmp(child_mapping_methods.Begin() + offset, page_start, capacity) != 0) {
705 LOG(WARNING) << "Contents differ in boot image methods data";
706 code_cache_->GetZygoteMap()->SetCompilationState(
707 ZygoteCompilationState::kNotifiedFailure);
708 return;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000709 }
Nicolas Geoffray831f20f2019-11-03 20:54:28 +0000710 offset += capacity;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000711 }
712 }
713
714 // Future spawned processes don't need the fd anymore.
715 fd_methods_.reset();
716
717 // In order to have the zygote and children share the memory, we also remap
718 // the memory into the zygote process.
719 offset = 0;
720 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
721 const ImageHeader& header = space->GetImageHeader();
722 const ImageSection& section = header.GetMethodsSection();
723 // Because mremap works at page boundaries, we can only handle methods
724 // within a page range. For methods that falls above or below the range,
725 // the child processes will copy their contents to their private mapping
726 // in `child_mapping_methods`. See `MapBootImageMethods`.
727 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
728 uint8_t* page_end =
729 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
730 if (page_end > page_start) {
731 uint64_t capacity = page_end - page_start;
732 if (mremap(child_mapping_methods.Begin() + offset,
733 capacity,
734 capacity,
735 MREMAP_FIXED | MREMAP_MAYMOVE,
736 page_start) == MAP_FAILED) {
737 // Failing to remap is safe as the process will just use the old
738 // contents.
739 PLOG(WARNING) << "Failed mremap of boot image methods of " << space->GetImageFilename();
740 }
741 offset += capacity;
742 }
743 }
744
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000745 LOG(INFO) << "Successfully notified child processes on sharing boot image methods";
746
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000747 // Mark that compilation of boot classpath is done, and memory can now be
748 // shared. Other processes will pick up this information.
749 code_cache_->GetZygoteMap()->SetCompilationState(ZygoteCompilationState::kNotifiedOk);
750
751 // The private mapping created for this process has been mremaped. We can
752 // reset it.
753 child_mapping_methods.Reset();
754}
755
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100756class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100757 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000758 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100759 kAllocateProfile,
760 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000761 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000762 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100763 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100764 };
765
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000766 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100767 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000768 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
769 // until compilation is done.
770 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
771 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
772 CHECK(klass_ != nullptr);
773 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100774 }
775
776 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000777 if (klass_ != nullptr) {
778 ScopedObjectAccess soa(Thread::Current());
779 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
780 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100781 }
782
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100783 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700784 {
785 ScopedObjectAccess soa(self);
786 switch (kind_) {
787 case TaskKind::kPreCompile:
788 case TaskKind::kCompile:
789 case TaskKind::kCompileBaseline:
790 case TaskKind::kCompileOsr: {
791 Runtime::Current()->GetJit()->CompileMethod(
792 method_,
793 self,
794 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
795 /* osr= */ (kind_ == TaskKind::kCompileOsr),
796 /* prejit= */ (kind_ == TaskKind::kPreCompile));
797 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000798 }
Andreas Gampe4bd52342019-07-15 15:09:04 -0700799 case TaskKind::kAllocateProfile: {
800 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
801 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
802 }
803 break;
804 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100805 }
806 }
Calin Juravlea2638922016-04-29 16:44:11 +0100807 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100808 }
809
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100810 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100811 delete this;
812 }
813
814 private:
815 ArtMethod* const method_;
816 const TaskKind kind_;
817 jobject klass_;
818
819 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
820};
821
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100822static std::string GetProfileFile(const std::string& dex_location) {
823 // Hardcoded assumption where the profile file is.
824 // TODO(ngeoffray): this is brittle and we would need to change change if we
825 // wanted to do more eager JITting of methods in a profile. This is
826 // currently only for system server.
827 return dex_location + ".prof";
828}
829
830static std::string GetBootProfileFile(const std::string& profile) {
831 // The boot profile can be found next to the compilation profile, with a
832 // different extension.
833 return ReplaceFileExtension(profile, "bprof");
834}
835
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100836/**
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100837 * A JIT task to run after all profile compilation is done.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100838 */
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100839class JitDoneCompilingProfileTask final : public SelfDeletingTask {
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100840 public:
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100841 explicit JitDoneCompilingProfileTask(const std::vector<const DexFile*>& dex_files)
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100842 : dex_files_(dex_files) {}
843
844 void Run(Thread* self ATTRIBUTE_UNUSED) override {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100845 // Madvise DONTNEED dex files now that we're done compiling methods.
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100846 for (const DexFile* dex_file : dex_files_) {
847 if (IsAddressKnownBackedByFileOrShared(dex_file->Begin())) {
848 int result = madvise(const_cast<uint8_t*>(AlignDown(dex_file->Begin(), kPageSize)),
849 RoundUp(dex_file->Size(), kPageSize),
850 MADV_DONTNEED);
851 if (result == -1) {
852 PLOG(WARNING) << "Madvise failed";
853 }
854 }
855 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100856
857 if (Runtime::Current()->IsZygote()) {
Nicolas Geoffray8852e532019-10-30 09:43:35 +0000858 // Record that we are done compiling the profile.
859 Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteMap()->SetCompilationState(
860 ZygoteCompilationState::kDone);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100861 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100862 }
863
864 private:
865 std::vector<const DexFile*> dex_files_;
866
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100867 DISALLOW_COPY_AND_ASSIGN(JitDoneCompilingProfileTask);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100868};
869
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000870class ZygoteTask final : public Task {
871 public:
872 ZygoteTask() {}
873
874 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100875 Runtime* runtime = Runtime::Current();
876 std::string profile_file;
877 for (const std::string& option : runtime->GetImageCompilerOptions()) {
878 if (android::base::StartsWith(option, "--profile-file=")) {
879 profile_file = option.substr(strlen("--profile-file="));
880 break;
881 }
882 }
883
884 const std::vector<const DexFile*>& boot_class_path =
885 runtime->GetClassLinker()->GetBootClassPath();
886 ScopedNullHandle<mirror::ClassLoader> null_handle;
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100887 std::string boot_profile = GetBootProfileFile(profile_file);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100888 // We add to the queue for zygote so that we can fork processes in-between
889 // compilations.
Nicolas Geoffraya6f35832019-08-09 13:34:19 +0100890 uint32_t added_to_queue = 0;
891 if (Runtime::Current()->IsPrimaryZygote()) {
892 // We avoid doing compilation at boot for the secondary zygote, as apps
893 // forked from it are not critical for boot.
894 added_to_queue += runtime->GetJit()->CompileMethodsFromBootProfile(
895 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
896 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100897 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100898 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100899
900 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
901 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100902 }
903
904 void Finalize() override {
905 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000906 }
907
908 private:
909 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
910};
911
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100912class JitProfileTask final : public Task {
913 public:
914 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100915 jobject class_loader) {
916 ScopedObjectAccess soa(Thread::Current());
917 StackHandleScope<1> hs(soa.Self());
918 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
919 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100920 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
921 for (const auto& dex_file : dex_files) {
922 dex_files_.push_back(dex_file.get());
923 // Register the dex file so that we can guarantee it doesn't get deleted
924 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100925 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100926 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100927 // We also create our own global ref to use this class loader later.
928 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100929 }
930
931 void Run(Thread* self) override {
932 ScopedObjectAccess soa(self);
933 StackHandleScope<1> hs(self);
934 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
935 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100936
937 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
938 std::string boot_profile = GetBootProfileFile(profile);
939
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100940 Jit* jit = Runtime::Current()->GetJit();
941
942 jit->CompileMethodsFromBootProfile(
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100943 self,
944 dex_files_,
945 boot_profile,
946 loader,
947 /* add_to_queue= */ false);
948
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100949 jit->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100950 self,
951 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100952 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100953 loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +0100954 /* add_to_queue= */ true);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100955 }
956
957 void Finalize() override {
958 delete this;
959 }
960
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +0100961 ~JitProfileTask() {
962 ScopedObjectAccess soa(Thread::Current());
963 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
964 }
965
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100966 private:
967 std::vector<const DexFile*> dex_files_;
968 jobject class_loader_;
969
970 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
971};
972
Nicolas Geoffrayff258062019-10-09 15:33:48 +0100973static void CopyIfDifferent(void* s1, const void* s2, size_t n) {
974 if (memcmp(s1, s2, n) != 0) {
975 memcpy(s1, s2, n);
976 }
977}
978
Nicolas Geoffray623d4f12019-09-30 13:45:51 +0100979void Jit::MapBootImageMethods() {
Nicolas Geoffraye3884e32019-10-28 17:04:49 +0000980 CHECK_NE(fd_methods_.get(), -1);
981 if (!code_cache_->GetZygoteMap()->CanMapBootImageMethods()) {
982 LOG(WARNING) << "Not mapping boot image methods due to error from zygote";
983 return;
984 }
985
986 std::string error_str;
987 MemMap child_mapping_methods = MemMap::MapFile(
988 fd_methods_size_,
989 PROT_READ | PROT_WRITE,
990 MAP_PRIVATE,
991 fd_methods_,
992 /* start= */ 0,
993 /* low_4gb= */ false,
994 "boot-image-methods",
995 &error_str);
996
997 // We don't need the fd anymore.
998 fd_methods_.reset();
999
1000 if (!child_mapping_methods.IsValid()) {
1001 LOG(WARNING) << "Failed to create child mapping of boot image methods: " << error_str;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001002 return;
1003 }
1004 size_t offset = 0;
1005 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1006 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1007 const ImageHeader& header = space->GetImageHeader();
1008 const ImageSection& section = header.GetMethodsSection();
1009 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1010 uint8_t* page_end =
1011 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1012 if (page_end <= page_start) {
1013 // Section doesn't contain one aligned entire page.
1014 continue;
1015 }
1016 uint64_t capacity = page_end - page_start;
1017 // Walk over methods in the boot image, and check for ones whose class is
1018 // not initialized in the process, but are in the zygote process. For
1019 // such methods, we need their entrypoints to be stubs that do the
1020 // initialization check.
1021 header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray382df392019-10-31 11:57:15 +00001022 // Methods in the boot image should never have their single
1023 // implementation flag set (and therefore never have a `data_` pointing
1024 // to an ArtMethod for single implementation).
1025 CHECK(method.IsIntrinsic() || !method.HasSingleImplementationFlag());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001026 if (method.IsRuntimeMethod()) {
1027 return;
1028 }
1029 if (method.GetDeclaringClassUnchecked()->IsVisiblyInitialized() ||
1030 !method.IsStatic() ||
1031 method.IsConstructor()) {
1032 // Method does not need any stub.
1033 return;
1034 }
1035
1036 // We are going to mremap the child mapping into the image:
1037 //
1038 // ImageSection ChildMappingMethods
1039 //
1040 // section start --> -----------
1041 // | |
1042 // | |
1043 // page_start --> | | <----- -----------
1044 // | | | |
1045 // | | | |
1046 // | | | |
1047 // | | | |
1048 // | | | |
1049 // | | | |
1050 // | | | |
1051 // page_end --> | | <----- -----------
1052 // | |
1053 // section end --> -----------
1054
1055
1056 uint8_t* pointer = reinterpret_cast<uint8_t*>(&method);
Mathieu Chartier9bab2372019-12-09 08:52:33 -08001057 // Note: We could refactor this to only check if the ArtMethod entrypoint is inside the
1058 // page region. This would remove the need for the edge case handling below.
1059 if (pointer >= page_start && pointer + sizeof(ArtMethod) < page_end) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001060 // For all the methods in the mapping, put the entrypoint to the
1061 // resolution stub.
1062 ArtMethod* new_method = reinterpret_cast<ArtMethod*>(
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001063 child_mapping_methods.Begin() + offset + (pointer - page_start));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001064 const void* code = new_method->GetEntryPointFromQuickCompiledCode();
1065 if (!class_linker->IsQuickGenericJniStub(code) &&
1066 !class_linker->IsQuickToInterpreterBridge(code) &&
1067 !class_linker->IsQuickResolutionStub(code)) {
1068 LOG(INFO) << "Putting back the resolution stub to an ArtMethod";
1069 new_method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1070 }
1071 } else if (pointer < page_start && (pointer + sizeof(ArtMethod)) > page_start) {
1072 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_start";
1073 // If the method spans `page_start`, copy the contents of the child
1074 // into the pages we are going to remap into the image.
1075 //
1076 // section start --> -----------
1077 // | |
1078 // | |
1079 // page_start --> |/////////| -----------
1080 // |/////////| -> copy -> |/////////|
1081 // | | | |
1082 //
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001083 CopyIfDifferent(child_mapping_methods.Begin() + offset,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001084 page_start,
1085 pointer + sizeof(ArtMethod) - page_start);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001086 } else if (pointer < page_end && (pointer + sizeof(ArtMethod)) > page_end) {
1087 LOG(INFO) << "Copying parts of the contents of an ArtMethod spanning page_end";
1088 // If the method spans `page_end`, copy the contents of the child
1089 // into the pages we are going to remap into the image.
1090 //
1091 // | | | |
1092 // |/////////| -> copy -> |/////////|
1093 // page_end --> |/////////| -----------
1094 // | |
1095 // section end --> -----------
1096 //
1097 size_t bytes_to_copy = (page_end - pointer);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001098 CopyIfDifferent(child_mapping_methods.Begin() + offset + capacity - bytes_to_copy,
Nicolas Geoffrayff258062019-10-09 15:33:48 +01001099 page_end - bytes_to_copy,
1100 bytes_to_copy);
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001101 }
1102 }, space->Begin(), kRuntimePointerSize);
1103
1104 // Map the memory in the boot image range.
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001105 if (mremap(child_mapping_methods.Begin() + offset,
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001106 capacity,
1107 capacity,
1108 MREMAP_FIXED | MREMAP_MAYMOVE,
1109 page_start) == MAP_FAILED) {
1110 PLOG(WARNING) << "Fail to mremap boot image methods for " << space->GetImageFilename();
1111 }
1112 offset += capacity;
1113 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001114
1115 // The private mapping created for this process has been mremaped. We can
1116 // reset it.
1117 child_mapping_methods.Reset();
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001118 LOG(INFO) << "Successfully mapped boot image methods";
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001119}
1120
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001121void Jit::CreateThreadPool() {
1122 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
1123 // is not null when we instrument.
1124
1125 // We need peers as we may report the JIT thread, e.g., in the debugger.
1126 constexpr bool kJitPoolNeedsPeers = true;
1127 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
1128
1129 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
1130 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001131
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001132 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +01001133 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001134 // If we're not using the default boot image location, request a JIT task to
1135 // compile all methods in the boot image profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001136 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001137
1138 // And create mappings to share boot image methods memory from the zygote to
1139 // child processes.
1140
1141 // Compute the total capacity required for the boot image methods.
1142 uint64_t total_capacity = 0;
1143 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
1144 const ImageHeader& header = space->GetImageHeader();
1145 const ImageSection& section = header.GetMethodsSection();
1146 // Mappings need to be at the page level.
1147 uint8_t* page_start = AlignUp(header.GetImageBegin() + section.Offset(), kPageSize);
1148 uint8_t* page_end =
1149 AlignDown(header.GetImageBegin() + section.Offset() + section.Size(), kPageSize);
1150 if (page_end > page_start) {
1151 total_capacity += (page_end - page_start);
1152 }
1153 }
1154
1155 // Create the child and zygote mappings to the boot image methods.
1156 if (total_capacity > 0) {
1157 // Start with '/boot' and end with '.art' to match the pattern recognized
1158 // by android_os_Debug.cpp for boot images.
1159 const char* name = "/boot-image-methods.art";
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001160 unique_fd mem_fd = unique_fd(art::memfd_create(name, /* flags= */ MFD_ALLOW_SEALING));
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001161 if (mem_fd.get() == -1) {
1162 PLOG(WARNING) << "Could not create boot image methods file descriptor";
1163 return;
1164 }
1165 if (ftruncate(mem_fd.get(), total_capacity) != 0) {
1166 PLOG(WARNING) << "Failed to truncate boot image methods file to " << total_capacity;
1167 return;
1168 }
1169 std::string error_str;
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001170
1171 // Create the shared mapping eagerly, as this prevents other processes
1172 // from adding the writable seal.
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001173 zygote_mapping_methods_ = MemMap::MapFile(
1174 total_capacity,
1175 PROT_READ | PROT_WRITE,
1176 MAP_SHARED,
1177 mem_fd,
1178 /* start= */ 0,
1179 /* low_4gb= */ false,
1180 "boot-image-methods",
1181 &error_str);
1182
1183 if (!zygote_mapping_methods_.IsValid()) {
1184 LOG(WARNING) << "Failed to create zygote mapping of boot image methods: " << error_str;
1185 return;
1186 }
1187 if (zygote_mapping_methods_.MadviseDontFork() != 0) {
1188 LOG(WARNING) << "Failed to madvise dont fork boot image methods";
1189 zygote_mapping_methods_ = MemMap();
1190 return;
1191 }
1192
Nicolas Geoffray831f20f2019-11-03 20:54:28 +00001193 // We should use the F_SEAL_FUTURE_WRITE flag, but this has unexpected
1194 // behavior on private mappings after fork (the mapping becomes shared between
1195 // parent and children), see b/143833776.
1196 // We will seal the write once we are done writing to the shared mapping.
1197 if (fcntl(mem_fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW) == -1) {
1198 PLOG(WARNING) << "Failed to seal boot image methods file descriptor";
1199 zygote_mapping_methods_ = MemMap();
1200 return;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001201 }
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001202 fd_methods_ = unique_fd(mem_fd.release());
1203 fd_methods_size_ = total_capacity;
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001204 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001205 }
1206}
1207
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001208void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +01001209 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001210 if (dex_files.empty()) {
1211 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001212 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001213 Runtime* runtime = Runtime::Current();
1214 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
1215 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
1216 }
1217}
1218
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001219bool Jit::CompileMethodFromProfile(Thread* self,
1220 ClassLinker* class_linker,
1221 uint32_t method_idx,
1222 Handle<mirror::DexCache> dex_cache,
1223 Handle<mirror::ClassLoader> class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001224 bool add_to_queue,
1225 bool compile_after_boot) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001226 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
1227 method_idx, dex_cache, class_loader);
1228 if (method == nullptr) {
1229 self->ClearException();
1230 return false;
1231 }
1232 if (!method->IsCompilable() || !method->IsInvokable()) {
1233 return false;
1234 }
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001235 if (method->IsPreCompiled()) {
1236 // Already seen by another profile.
1237 return false;
1238 }
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001239 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1240 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
1241 class_linker->IsQuickGenericJniStub(entry_point) ||
1242 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001243 method->SetPreCompiled();
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001244 if (!add_to_queue) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001245 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
1246 } else {
David Srbeckybfcea3d2019-08-05 15:44:00 +01001247 Task* task = new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile);
1248 if (compile_after_boot) {
1249 MutexLock mu(Thread::Current(), boot_completed_lock_);
1250 if (!boot_completed_) {
1251 tasks_after_boot_.push_back(task);
1252 return true;
1253 }
1254 DCHECK(tasks_after_boot_.empty());
1255 }
1256 thread_pool_->AddTask(self, task);
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001257 return true;
1258 }
1259 }
1260 return false;
1261}
1262
1263uint32_t Jit::CompileMethodsFromBootProfile(
1264 Thread* self,
1265 const std::vector<const DexFile*>& dex_files,
1266 const std::string& profile_file,
1267 Handle<mirror::ClassLoader> class_loader,
1268 bool add_to_queue) {
1269 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
1270
1271 if (profile.Fd() == -1) {
1272 PLOG(WARNING) << "No boot profile: " << profile_file;
1273 return 0u;
1274 }
1275
1276 ProfileBootInfo profile_info;
1277 if (!profile_info.Load(profile.Fd(), dex_files)) {
1278 LOG(ERROR) << "Could not load profile file: " << profile_file;
1279 return 0u;
1280 }
1281
1282 ScopedObjectAccess soa(self);
1283 VariableSizedHandleScope handles(self);
1284 std::vector<Handle<mirror::DexCache>> dex_caches;
1285 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1286 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
1287 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
1288 }
1289
1290 uint32_t added_to_queue = 0;
1291 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
1292 if (CompileMethodFromProfile(self,
1293 class_linker,
1294 pair.second,
1295 dex_caches[pair.first],
1296 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001297 add_to_queue,
1298 /*compile_after_boot=*/false)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001299 ++added_to_queue;
1300 }
1301 }
1302 return added_to_queue;
1303}
1304
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001305uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001306 Thread* self,
1307 const std::vector<const DexFile*>& dex_files,
1308 const std::string& profile_file,
1309 Handle<mirror::ClassLoader> class_loader,
1310 bool add_to_queue) {
1311
1312 if (profile_file.empty()) {
1313 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001314 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001315 }
1316
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001317 // We don't generate boot profiles on device, therefore we don't
1318 // need to lock the file.
1319 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001320
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001321 if (profile.Fd() == -1) {
1322 PLOG(WARNING) << "No profile: " << profile_file;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001323 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001324 }
1325
1326 ProfileCompilationInfo profile_info;
Nicolas Geoffraya6f35832019-08-09 13:34:19 +01001327 if (!profile_info.Load(profile.Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001328 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001329 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001330 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001331 ScopedObjectAccess soa(self);
1332 StackHandleScope<1> hs(self);
1333 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001334 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001335 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001336 for (const DexFile* dex_file : dex_files) {
Martin Stjernholme58624f2019-09-20 15:53:40 +01001337 if (LocationIsOnArtModule(dex_file->GetLocation().c_str())) {
1338 // The ART module jars are already preopted.
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001339 continue;
1340 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001341 // To speed up class lookups, generate a type lookup table for
1342 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +01001343 if (dex_file->GetOatDexFile() == nullptr) {
1344 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
1345 type_lookup_tables_.push_back(
1346 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
1347 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
1348 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001349
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001350 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001351 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001352 if (!profile_info.GetClassesAndMethods(*dex_file,
1353 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001354 &all_methods,
1355 &all_methods,
1356 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +01001357 // This means the profile file did not reference the dex file, which is the case
1358 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001359 continue;
1360 }
1361 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
1362 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +00001363
1364 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001365 if (CompileMethodFromProfile(self,
1366 class_linker,
1367 method_idx,
1368 dex_cache,
1369 class_loader,
David Srbeckybfcea3d2019-08-05 15:44:00 +01001370 add_to_queue,
1371 /*compile_after_boot=*/true)) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +01001372 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +00001373 }
1374 }
1375 }
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001376
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001377 // Add a task to run when all compilation is done.
1378 JitDoneCompilingProfileTask* task = new JitDoneCompilingProfileTask(dex_files);
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +01001379 MutexLock mu(Thread::Current(), boot_completed_lock_);
1380 if (!boot_completed_) {
1381 tasks_after_boot_.push_back(task);
1382 } else {
1383 DCHECK(tasks_after_boot_.empty());
1384 thread_pool_->AddTask(self, task);
1385 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001386 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001387}
1388
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001389static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +01001390 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001391 // We do not want to compile such methods.
1392 return true;
1393 }
1394 if (method->IsNative()) {
1395 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001396 if (klass == GetClassRoot<mirror::MethodHandle>() ||
1397 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001398 // MethodHandle and VarHandle invocation methods are required to throw an
1399 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001400 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001401 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
1402 // stubs. Since these stubs have different stack representations we can then crash in stack
1403 // walking (b/78151261).
1404 return true;
1405 }
1406 }
1407 return false;
1408}
1409
David Srbeckye3fc2d12018-11-30 13:41:14 +00001410bool Jit::MaybeCompileMethod(Thread* self,
1411 ArtMethod* method,
1412 uint32_t old_count,
1413 uint32_t new_count,
1414 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001415 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001416 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001417 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001418 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
Vladimir Marko5115a4d2019-10-17 14:56:47 +01001419 if (!NeedsClinitCheckBeforeCall(method) ||
1420 method->GetDeclaringClass()->IsVisiblyInitialized()) {
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001421 const void* entry_point = code_cache_->GetSavedEntryPointOfPreCompiledMethod(method);
1422 if (entry_point != nullptr) {
1423 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, entry_point);
1424 return true;
1425 }
David Srbecky1fc4d422019-07-23 16:55:19 +01001426 }
1427 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01001428
Orion Hodson52f5a1f2018-05-02 11:05:44 +01001429 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001430 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001431 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001432 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +00001433 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +00001434 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +00001435 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +01001436 DCHECK_GT(WarmMethodThreshold(), 0);
1437 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
1438 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
1439 DCHECK_GE(PriorityThreadWeight(), 1);
1440 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001441
David Srbeckye3fc2d12018-11-30 13:41:14 +00001442 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
1443 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001444 if (!method->IsNative() &&
1445 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001446 code_cache_->CanAllocateProfilingInfo() &&
1447 !options_->UseTieredJitCompilation()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001448 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001449 if (success) {
1450 VLOG(jit) << "Start profiling " << method->PrettyMethod();
1451 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001452
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001453 if (thread_pool_ == nullptr) {
1454 // Calling ProfilingInfo::Create might put us in a suspended state, which could
1455 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001456 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001457 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001458
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001459 if (!success) {
1460 // We failed allocating. Instead of doing the collection on the Java thread, we push
1461 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001462 thread_pool_->AddTask(
1463 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +00001464 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001465 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001466 }
1467 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001468 if (old_count == 0 &&
1469 method->IsNative() &&
1470 Runtime::Current()->IsUsingApexBootImageLocation()) {
1471 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001472 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +01001473 return true;
1474 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001475 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1476 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001477 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001478 JitCompileTask::TaskKind kind =
1479 (options_->UseTieredJitCompilation() || options_->UseBaselineCompiler())
1480 ? JitCompileTask::TaskKind::kCompileBaseline
1481 : JitCompileTask::TaskKind::kCompile;
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001482 thread_pool_->AddTask(self, new JitCompileTask(method, kind));
Calin Juravleffc87072016-04-20 14:22:09 +01001483 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001484 }
1485 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001486 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001487 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001488 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001489 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001490 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001491 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001492 thread_pool_->AddTask(
1493 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001494 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001495 }
1496 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001497 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001498}
1499
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001500void Jit::EnqueueOptimizedCompilation(ArtMethod* method, Thread* self) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00001501 if (thread_pool_ == nullptr) {
1502 return;
1503 }
Nicolas Geoffrayb0a97472019-12-05 15:17:46 +00001504 // We arrive here after a baseline compiled code has reached its baseline
1505 // hotness threshold. If tiered compilation is enabled, enqueue a compilation
1506 // task that will compile optimize the method.
1507 if (options_->UseTieredJitCompilation()) {
1508 thread_pool_->AddTask(
1509 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
1510 }
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +00001511}
1512
Alex Light59b950f2018-10-08 10:43:06 -07001513class ScopedSetRuntimeThread {
1514 public:
1515 explicit ScopedSetRuntimeThread(Thread* self)
1516 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1517 self_->SetIsRuntimeThread(true);
1518 }
1519
1520 ~ScopedSetRuntimeThread() {
1521 self_->SetIsRuntimeThread(was_runtime_thread_);
1522 }
1523
1524 private:
1525 Thread* self_;
1526 bool was_runtime_thread_;
1527};
1528
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001529void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001530 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001531 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001532 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001533 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001534 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001535 // The compiler requires a ProfilingInfo object for non-native methods.
1536 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1537 }
1538 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1539 // conflicts with jitzygote optimizations.
1540 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001541 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1542 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001543 compile_task.Run(thread);
1544 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001545 return;
1546 }
1547
Andreas Gampe542451c2016-07-26 09:02:02 -07001548 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001549 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001550 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1551 // must remain the instrumentation entrypoint.
1552 if ((profiling_info != nullptr) &&
1553 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1554 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001555 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1556 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001557 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001558 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001559 }
1560}
1561
Mathieu Chartieref41db72016-10-25 15:08:01 -07001562void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001563 ArtMethod* caller,
1564 uint32_t dex_pc,
1565 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001566 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001567 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001568 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001569 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001570 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1571 }
1572}
1573
1574void Jit::WaitForCompilationToFinish(Thread* self) {
1575 if (thread_pool_ != nullptr) {
1576 thread_pool_->Wait(self, false, false);
1577 }
1578}
1579
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001580void Jit::Stop() {
1581 Thread* self = Thread::Current();
1582 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1583 WaitForCompilationToFinish(self);
1584 GetThreadPool()->StopWorkers(self);
1585 WaitForCompilationToFinish(self);
1586}
1587
1588void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001589 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001590}
1591
Andreas Gampef149b3f2016-11-16 14:58:24 -08001592ScopedJitSuspend::ScopedJitSuspend() {
1593 jit::Jit* jit = Runtime::Current()->GetJit();
1594 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1595 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001596 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001597 }
1598}
1599
1600ScopedJitSuspend::~ScopedJitSuspend() {
1601 if (was_on_) {
1602 DCHECK(Runtime::Current()->GetJit() != nullptr);
1603 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001604 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001605 }
1606}
1607
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001608static void* RunPollingThread(void* arg) {
1609 Jit* jit = reinterpret_cast<Jit*>(arg);
1610 do {
1611 sleep(10);
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001612 } while (!jit->GetCodeCache()->GetZygoteMap()->IsCompilationNotified());
Nicolas Geoffray8e23d382019-10-30 13:53:01 +00001613
1614 // We will suspend other threads: we can only do that if we're attached to the
1615 // runtime.
1616 Runtime* runtime = Runtime::Current();
1617 bool thread_attached = runtime->AttachCurrentThread(
1618 "BootImagePollingThread",
1619 /* as_daemon= */ true,
1620 /* thread_group= */ nullptr,
1621 /* create_peer= */ false);
1622 CHECK(thread_attached);
1623
1624 {
1625 // Prevent other threads from running while we are remapping the boot image
1626 // ArtMethod's. Native threads might still be running, but they cannot
1627 // change the contents of ArtMethod's.
1628 ScopedSuspendAll ssa(__FUNCTION__);
1629 runtime->GetJit()->MapBootImageMethods();
1630 }
1631
1632 Runtime::Current()->DetachCurrentThread();
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001633 return nullptr;
1634}
1635
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001636void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraye9455f62019-08-15 20:57:04 +01001637 // Clear the potential boot tasks inherited from the zygote.
1638 {
1639 MutexLock mu(Thread::Current(), boot_completed_lock_);
1640 tasks_after_boot_.clear();
1641 }
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001642
Nicolas Geoffraye3884e32019-10-28 17:04:49 +00001643 if (Runtime::Current()->IsUsingApexBootImageLocation() && fd_methods_ != -1) {
Nicolas Geoffray623d4f12019-09-30 13:45:51 +01001644 // Create a thread that will poll the status of zygote compilation, and map
1645 // the private mapping of boot image methods.
1646 zygote_mapping_methods_.ResetInForkedProcess();
1647 pthread_t polling_thread;
1648 pthread_attr_t attr;
1649 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
1650 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
1651 "PTHREAD_CREATE_DETACHED");
1652 CHECK_PTHREAD_CALL(
1653 pthread_create,
1654 (&polling_thread, &attr, RunPollingThread, reinterpret_cast<void*>(this)),
1655 "Methods maps thread");
1656 }
1657
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001658 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001659 // Delete the thread pool, we are not going to JIT.
1660 thread_pool_.reset(nullptr);
1661 return;
1662 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001663 // At this point, the compiler options have been adjusted to the particular configuration
1664 // of the forked child. Parse them again.
David Srbecky46b53532019-08-06 13:39:05 +01001665 jit_compiler_->ParseCompilerOptions();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001666
1667 // Adjust the status of code cache collection: the status from zygote was to not collect.
David Srbecky46b53532019-08-06 13:39:05 +01001668 code_cache_->SetGarbageCollectCode(!jit_compiler_->GenerateDebugInfo() &&
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001669 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001670
Nicolas Geoffraya67daeb2019-08-12 10:41:25 +01001671 if (is_system_server && Runtime::Current()->IsUsingApexBootImageLocation()) {
1672 // Disable garbage collection: we don't want it to delete methods we're compiling
1673 // through boot and system server profiles.
1674 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1675 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001676 }
Nicolas Geoffray371390f2019-09-27 09:57:38 +01001677
1678 // We do this here instead of PostZygoteFork, as NativeDebugInfoPostFork only
1679 // applies to a child.
1680 NativeDebugInfoPostFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001681}
1682
1683void Jit::PreZygoteFork() {
1684 if (thread_pool_ == nullptr) {
1685 return;
1686 }
1687 thread_pool_->DeleteThreads();
David Srbecky1550a662019-08-14 17:16:46 +01001688
1689 NativeDebugInfoPreFork();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001690}
1691
1692void Jit::PostZygoteFork() {
1693 if (thread_pool_ == nullptr) {
1694 return;
1695 }
Nicolas Geoffray8852e532019-10-30 09:43:35 +00001696 if (Runtime::Current()->IsZygote() &&
1697 code_cache_->GetZygoteMap()->IsCompilationDoneButNotNotified()) {
1698 // Copy the boot image methods data to the mappings we created to share
1699 // with the children. We do this here as we are the only thread running and
1700 // we don't risk other threads concurrently updating the ArtMethod's.
1701 CHECK_EQ(GetTaskCount(), 1);
1702 NotifyZygoteCompilationDone();
1703 CHECK(code_cache_->GetZygoteMap()->IsCompilationNotified());
1704 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001705 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001706}
1707
David Srbeckybfcea3d2019-08-05 15:44:00 +01001708void Jit::BootCompleted() {
1709 Thread* self = Thread::Current();
1710 std::deque<Task*> tasks;
1711 {
1712 MutexLock mu(self, boot_completed_lock_);
1713 tasks = std::move(tasks_after_boot_);
1714 boot_completed_ = true;
1715 }
1716 for (Task* task : tasks) {
1717 thread_pool_->AddTask(self, task);
1718 }
1719}
1720
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001721bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1722 return !is_for_shared_region ||
1723 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001724}
1725
1726bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001727 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001728}
1729
1730bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001731 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001732}
1733
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001734bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1735 if (!is_for_shared_region) {
1736 return cls->IsInitialized();
1737 } else {
1738 // Look up the class status in the oat file.
1739 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1740 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1741 // In case we run without an image there won't be a backing oat file.
1742 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1743 return false;
1744 }
1745 uint16_t class_def_index = cls->GetDexClassDefIndex();
1746 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1747 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001748}
1749
Nicolas Geoffray00391822019-12-10 10:17:23 +00001750void Jit::EnqueueCompilationFromNterp(ArtMethod* method, Thread* self) {
1751 if (thread_pool_ == nullptr) {
1752 return;
1753 }
1754 if (GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
1755 // If we already have compiled code for it, nterp may be stuck in a loop.
1756 // Compile OSR.
1757 thread_pool_->AddTask(
1758 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
1759 return;
1760 }
1761 ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
1762 thread_pool_->AddTask(
1763 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileBaseline));
1764}
1765
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001766} // namespace jit
1767} // namespace art