blob: 902d92494ceeb32e2c91c8eb02b3751d3da4ea85 [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.
Andreas Gampe0897e1c2017-05-16 08:36:56 -070025#include "base/memory_tool.h"
Andreas Gampedcc528d2017-12-07 13:37:10 -080026#include "base/runtime_debug.h"
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +000027#include "base/scoped_flock.h"
David Sehrc431b9d2018-03-02 12:01:51 -080028#include "base/utils.h"
Vladimir Markoc7aa87e2018-05-24 15:19:52 +010029#include "class_root.h"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070030#include "debugger.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010031#include "dex/type_lookup_table.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032#include "entrypoints/runtime_asm_entrypoints.h"
33#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000034#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010036#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010037#include "mirror/method_handle_impl.h"
38#include "mirror/var_handle.h"
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +010039#include "oat_file.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010040#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000041#include "oat_quick_method_header.h"
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +010042#include "profile/profile_boot_info.h"
David Sehr82d046e2018-04-23 08:14:19 -070043#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000044#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080045#include "runtime.h"
46#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070047#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000048#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070049#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010050#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051
52namespace art {
53namespace jit {
54
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000055static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000056
Andreas Gampe7897cec2017-07-19 16:28:59 -070057// Different compilation threshold constants. These can be overridden on the command line.
58static constexpr size_t kJitDefaultCompileThreshold = 10000; // Non-debug default.
59static constexpr size_t kJitStressDefaultCompileThreshold = 100; // Fast-debug build.
60static constexpr size_t kJitSlowStressDefaultCompileThreshold = 2; // Slow-debug build.
61
David Srbecky21821472019-07-29 15:10:31 +010062DEFINE_RUNTIME_DEBUG_FLAG(Jit, kSlowMode);
63
Mathieu Chartier72918ea2016-03-24 11:07:06 -070064// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080065void* Jit::jit_library_handle_ = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070066void* Jit::jit_compiler_handle_ = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000067void* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070068void (*Jit::jit_unload_)(void*) = nullptr;
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +010069bool (*Jit::jit_compile_method_)(void*, JitMemoryRegion*, ArtMethod*, Thread*, bool, bool)
70 = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070071void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000072bool (*Jit::jit_generate_debug_info_)(void*) = nullptr;
73void (*Jit::jit_update_options_)(void*) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070074
David Srbeckye3fc2d12018-11-30 13:41:14 +000075uint32_t JitOptions::RoundUpThreshold(uint32_t threshold) {
David Srbecky21821472019-07-29 15:10:31 +010076 if (!Jit::kSlowMode) {
David Srbeckye3fc2d12018-11-30 13:41:14 +000077 threshold = RoundUp(threshold, kJitSamplesBatchSize);
78 }
79 CHECK_LE(threshold, std::numeric_limits<uint16_t>::max());
80 return threshold;
81}
82
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080083JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080084 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010085 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000086
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000087 jit_options->code_cache_initial_capacity_ =
88 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
89 jit_options->code_cache_max_capacity_ =
90 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070091 jit_options->dump_info_on_shutdown_ =
92 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010093 jit_options->profile_saver_options_ =
94 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +010095 jit_options->thread_pool_pthread_priority_ =
96 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000097
Andreas Gampe7897cec2017-07-19 16:28:59 -070098 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
99 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
100 } else {
101 jit_options->compile_threshold_ =
102 kIsDebugBuild
David Srbecky21821472019-07-29 15:10:31 +0100103 ? (Jit::kSlowMode
Andreas Gampe7897cec2017-07-19 16:28:59 -0700104 ? kJitSlowStressDefaultCompileThreshold
105 : kJitStressDefaultCompileThreshold)
106 : kJitDefaultCompileThreshold;
107 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000108 jit_options->compile_threshold_ = RoundUpThreshold(jit_options->compile_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000109
110 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
111 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000112 } else {
113 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
114 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000115 jit_options->warmup_threshold_ = RoundUpThreshold(jit_options->warmup_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000116
117 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
118 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000119 } else {
120 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
121 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000122 jit_options->osr_threshold_ =
123 RoundDown(std::numeric_limits<uint16_t>::max(), kJitSamplesBatchSize);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000124 }
125 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000126 jit_options->osr_threshold_ = RoundUpThreshold(jit_options->osr_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000127
Calin Juravleb2771b42016-04-07 17:09:25 +0100128 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
129 jit_options->priority_thread_weight_ =
130 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
131 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
132 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
133 } else if (jit_options->priority_thread_weight_ == 0) {
134 LOG(FATAL) << "Priority thread weight cannot be 0.";
135 }
136 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100137 jit_options->priority_thread_weight_ = std::max(
138 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
139 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100140 }
141
Calin Juravle155ff3d2016-04-27 14:14:58 +0100142 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100143 jit_options->invoke_transition_weight_ =
144 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100145 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
146 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
147 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100148 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100149 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100150 } else {
151 jit_options->invoke_transition_weight_ = std::max(
152 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800153 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100154 }
155
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800156 return jit_options;
157}
158
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700159void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000160 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700161 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000162 MutexLock mu(Thread::Current(), lock_);
163 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700164}
165
Calin Juravleb8e69992016-03-09 15:37:48 +0000166void Jit::DumpForSigQuit(std::ostream& os) {
167 DumpInfo(os);
168 ProfileSaver::DumpInstanceInfo(os);
169}
170
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700171void Jit::AddTimingLogger(const TimingLogger& logger) {
172 cumulative_timings_.AddLogger(logger);
173}
174
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100175Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
176 : code_cache_(code_cache),
177 options_(options),
178 cumulative_timings_("JIT timings"),
179 memory_use_("Memory used for compilation", 16),
180 lock_("JIT memory use lock") {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800181
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100182Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000183 if (jit_load_ == nullptr) {
184 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800185 return nullptr;
186 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000187 jit_compiler_handle_ = (jit_load_)();
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000188 if (jit_compiler_handle_ == nullptr) {
189 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
190 return nullptr;
191 }
192 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000193
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000194 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000195 // With 'perf', we want a 1-1 mapping between an address and a method.
196 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
197 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000198 if (code_cache->GetGarbageCollectCode()) {
199 code_cache->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
200 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
201 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100202
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000203 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000204 << PrettySize(options->GetCodeCacheInitialCapacity())
205 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000206 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100207 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100208
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100209 // Notify native debugger about the classes already loaded before the creation of the jit.
210 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800211 return jit.release();
212}
213
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000214template <typename T>
215bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
216 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
217 if (*address == nullptr) {
218 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
219 return false;
220 }
221 return true;
222}
223
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000224bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800225 jit_library_handle_ = dlopen(
226 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
227 if (jit_library_handle_ == nullptr) {
228 std::ostringstream oss;
229 oss << "JIT could not load libart-compiler.so: " << dlerror();
230 *error_msg = oss.str();
231 return false;
232 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000233 bool all_resolved = true;
234 all_resolved = all_resolved && LoadSymbol(&jit_load_, "jit_load", error_msg);
235 all_resolved = all_resolved && LoadSymbol(&jit_unload_, "jit_unload", error_msg);
236 all_resolved = all_resolved && LoadSymbol(&jit_compile_method_, "jit_compile_method", error_msg);
237 all_resolved = all_resolved && LoadSymbol(&jit_types_loaded_, "jit_types_loaded", error_msg);
238 all_resolved = all_resolved && LoadSymbol(&jit_update_options_, "jit_update_options", error_msg);
239 all_resolved = all_resolved &&
240 LoadSymbol(&jit_generate_debug_info_, "jit_generate_debug_info", error_msg);
241 if (!all_resolved) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800242 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000243 return false;
244 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700245 return true;
246}
247
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100248bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr, bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100249 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800250 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000251
Alex Light0fa17862017-10-24 13:43:05 -0700252 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100253 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700254 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
255 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
256 << " due to not being safe to jit according to runtime-callbacks. For example, there"
257 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700258 return false;
259 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100260
261 // Don't compile the method if we are supposed to be deoptimized.
262 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
263 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700264 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100265 return false;
266 }
267
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000268 JitMemoryRegion* region = GetCodeCache()->GetCurrentRegion();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100269 if (osr && GetCodeCache()->IsSharedRegion(*region)) {
270 VLOG(jit) << "JIT not osr compiling "
271 << method->PrettyMethod()
272 << " due to using shared region";
273 return false;
274 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000275
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000276 // If we get a request to compile a proxy method, we pass the actual Java method
277 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700278 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000279 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr, prejit, region)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100280 return false;
281 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100282
283 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700284 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100285 << " osr=" << std::boolalpha << osr;
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100286 bool success = jit_compile_method_(
287 jit_compiler_handle_, region, method_to_compile, self, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700288 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100289 if (!success) {
290 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700291 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100292 << " osr=" << std::boolalpha << osr;
293 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800294 if (kIsDebugBuild) {
295 if (self->IsExceptionPending()) {
296 mirror::Throwable* exception = self->GetException();
297 LOG(FATAL) << "No pending exception expected after compiling "
298 << ArtMethod::PrettyMethod(method)
299 << ": "
300 << exception->Dump();
301 }
302 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800304}
305
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800306void Jit::WaitForWorkersToBeCreated() {
307 if (thread_pool_ != nullptr) {
308 thread_pool_->WaitForWorkersToBeCreated();
309 }
310}
311
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800312void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100313 Thread* self = Thread::Current();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100314 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700315 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100316 {
317 ScopedSuspendAll ssa(__FUNCTION__);
318 // Clear thread_pool_ field while the threads are suspended.
319 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700320 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100321 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700322
323 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000324 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700325 pool->StopWorkers(self);
326 pool->RemoveAllTasks(self);
327 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100328 // We could just suspend all threads, but we know those threads
329 // will finish in a short period, so it's not worth adding a suspend logic
330 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700331 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800332 }
333}
334
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000335void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800336 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100337 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100338 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100339 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000340}
341
342void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100343 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
344 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100345 }
346}
347
Siva Chandra05d24152016-01-05 17:43:17 -0800348bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100349 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800350}
351
Nicolas Geoffray35122442016-03-02 12:05:30 +0000352bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
353 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
354}
355
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800356Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100357 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
358 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700359 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100360 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700361 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800362 DeleteThreadPool();
363 if (jit_compiler_handle_ != nullptr) {
364 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700365 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800366 }
367 if (jit_library_handle_ != nullptr) {
368 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700369 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800370 }
371}
372
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000373void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100374 if (!Runtime::Current()->UseJitCompilation()) {
375 // No need to notify if we only use the JIT to save profiles.
376 return;
377 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000378 jit::Jit* jit = Runtime::Current()->GetJit();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000379 if (jit_generate_debug_info_(jit->jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000380 DCHECK(jit->jit_types_loaded_ != nullptr);
381 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
382 }
383}
384
385void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
386 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100387 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700388 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000389 return true;
390 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800391 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000392 };
393
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000394 if (jit_generate_debug_info_(jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000395 ScopedObjectAccess so(Thread::Current());
396
397 CollectClasses visitor;
398 linker->VisitClasses(&visitor);
399 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000400 }
401}
402
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000403extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700404 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000405 const uint8_t* native_pc,
406 JValue* result,
407 const char* shorty,
408 Thread* self);
409
410bool Jit::MaybeDoOnStackReplacement(Thread* thread,
411 ArtMethod* method,
412 uint32_t dex_pc,
413 int32_t dex_pc_offset,
414 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000415 if (!kEnableOnStackReplacement) {
416 return false;
417 }
418
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000419 Jit* jit = Runtime::Current()->GetJit();
420 if (jit == nullptr) {
421 return false;
422 }
423
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000424 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
425 // Don't attempt to do an OSR if we are close to the stack limit. Since
426 // the interpreter frames are still on stack, OSR has the potential
427 // to stack overflow even for a simple loop.
428 // b/27094810.
429 return false;
430 }
431
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000432 // Get the actual Java method if this method is from a proxy class. The compiler
433 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000435
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000436 // Cheap check if the method has been compiled already. That's an indicator that we should
437 // osr into it.
438 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
439 return false;
440 }
441
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000442 // Fetch some data before looking up for an OSR method. We don't want thread
443 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
444 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000445 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800446 const size_t number_of_vregs = accessor.RegistersSize();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000447 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700448 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000449 void** memory = nullptr;
450 size_t frame_size = 0;
451 ShadowFrame* shadow_frame = nullptr;
452 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000453
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000454 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700455 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000456 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
457 if (osr_method == nullptr) {
458 // No osr method yet, just return to the interpreter.
459 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000460 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000461
David Srbecky052f8ca2018-04-26 15:42:54 +0100462 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000463
464 // Find stack map starting at the target dex_pc.
David Srbecky052f8ca2018-04-26 15:42:54 +0100465 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000466 if (!stack_map.IsValid()) {
467 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
468 // hope that the next branch has one.
469 return false;
470 }
471
Alex Light21611932017-09-26 13:07:39 -0700472 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
473 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
474 // disable OSR when single stepping, but that's currently hard to know at this point.
475 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
Aart Bik29bdaee2016-05-18 15:44:07 -0700476 return false;
477 }
478
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000479 // We found a stack map, now fill the frame with dex register values from the interpreter's
480 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100481 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Artem Serov2808be82018-12-20 19:15:11 +0000482 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000483
484 frame_size = osr_method->GetFrameSizeInBytes();
485
486 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
487 // stack.
488 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
489 // but that is engineering complexity not worth the effort for something like OSR.
490 memory = reinterpret_cast<void**>(malloc(frame_size));
491 CHECK(memory != nullptr);
492 memset(memory, 0, frame_size);
493
494 // Art ABI: ArtMethod is at the bottom of the stack.
495 memory[0] = method;
496
497 shadow_frame = thread->PopShadowFrame();
David Srbeckyfd89b072018-06-03 12:00:22 +0100498 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000499 // If we don't have a dex register map, then there are no live dex registers at
500 // this dex pc.
501 } else {
502 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100503 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000504 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000505 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000506 continue;
507 }
508
509 if (location == DexRegisterLocation::Kind::kConstant) {
510 // We skip constants because the compiled code knows how to handle them.
511 continue;
512 }
513
David Srbecky7dc11782016-02-25 13:23:56 +0000514 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000515
516 int32_t vreg_value = shadow_frame->GetVReg(vreg);
David Srbeckye1402122018-06-13 18:20:45 +0100517 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000518 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
519 DCHECK_GT(slot_offset, 0);
520 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
521 }
522 }
523
David Srbecky052f8ca2018-04-26 15:42:54 +0100524 native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000525 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000526 VLOG(jit) << "Jumping to "
527 << method_name
528 << "@"
529 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000530 }
531
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000532 {
533 ManagedStack fragment;
534 thread->PushManagedStackFragment(&fragment);
535 (*art_quick_osr_stub)(memory,
536 frame_size,
537 native_pc,
538 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000539 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000540 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000541
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000542 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
543 thread->DeoptimizeWithDeoptimizationException(result);
544 }
545 thread->PopManagedStackFragment(fragment);
546 }
547 free(memory);
548 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000549 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000550 return true;
551}
552
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000553void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
554 if (bytes > 4 * MB) {
555 LOG(INFO) << "Compiler allocated "
556 << PrettySize(bytes)
557 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700558 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000559 }
560 MutexLock mu(Thread::Current(), lock_);
561 memory_use_.AddValue(bytes);
562}
563
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100564class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100565 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000566 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100567 kAllocateProfile,
568 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000569 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000570 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100571 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100572 };
573
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000574 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100575 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000576 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
577 // until compilation is done.
578 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
579 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
580 CHECK(klass_ != nullptr);
581 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100582 }
583
584 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000585 if (klass_ != nullptr) {
586 ScopedObjectAccess soa(Thread::Current());
587 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
588 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100589 }
590
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100591 void Run(Thread* self) override {
Andreas Gampe4bd52342019-07-15 15:09:04 -0700592 {
593 ScopedObjectAccess soa(self);
594 switch (kind_) {
595 case TaskKind::kPreCompile:
596 case TaskKind::kCompile:
597 case TaskKind::kCompileBaseline:
598 case TaskKind::kCompileOsr: {
599 Runtime::Current()->GetJit()->CompileMethod(
600 method_,
601 self,
602 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
603 /* osr= */ (kind_ == TaskKind::kCompileOsr),
604 /* prejit= */ (kind_ == TaskKind::kPreCompile));
605 break;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000606 }
Andreas Gampe4bd52342019-07-15 15:09:04 -0700607 case TaskKind::kAllocateProfile: {
608 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
609 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
610 }
611 break;
612 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100613 }
614 }
Calin Juravlea2638922016-04-29 16:44:11 +0100615 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100616 }
617
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100618 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100619 delete this;
620 }
621
622 private:
623 ArtMethod* const method_;
624 const TaskKind kind_;
625 jobject klass_;
626
627 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
628};
629
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100630static std::string GetProfileFile(const std::string& dex_location) {
631 // Hardcoded assumption where the profile file is.
632 // TODO(ngeoffray): this is brittle and we would need to change change if we
633 // wanted to do more eager JITting of methods in a profile. This is
634 // currently only for system server.
635 return dex_location + ".prof";
636}
637
638static std::string GetBootProfileFile(const std::string& profile) {
639 // The boot profile can be found next to the compilation profile, with a
640 // different extension.
641 return ReplaceFileExtension(profile, "bprof");
642}
643
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000644class ZygoteTask final : public Task {
645 public:
646 ZygoteTask() {}
647
648 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100649 Runtime* runtime = Runtime::Current();
650 std::string profile_file;
651 for (const std::string& option : runtime->GetImageCompilerOptions()) {
652 if (android::base::StartsWith(option, "--profile-file=")) {
653 profile_file = option.substr(strlen("--profile-file="));
654 break;
655 }
656 }
657
658 const std::vector<const DexFile*>& boot_class_path =
659 runtime->GetClassLinker()->GetBootClassPath();
660 ScopedNullHandle<mirror::ClassLoader> null_handle;
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100661 std::string boot_profile = GetBootProfileFile(profile_file);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100662 // We add to the queue for zygote so that we can fork processes in-between
663 // compilations.
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100664 uint32_t added_to_queue = runtime->GetJit()->CompileMethodsFromBootProfile(
665 self, boot_class_path, boot_profile, null_handle, /* add_to_queue= */ true);
666 added_to_queue += runtime->GetJit()->CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100667 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100668
669 JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
670 code_cache->GetZygoteMap()->Initialize(added_to_queue);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100671 }
672
673 void Finalize() override {
674 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000675 }
676
677 private:
678 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
679};
680
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100681class JitProfileTask final : public Task {
682 public:
683 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100684 jobject class_loader) {
685 ScopedObjectAccess soa(Thread::Current());
686 StackHandleScope<1> hs(soa.Self());
687 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
688 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100689 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
690 for (const auto& dex_file : dex_files) {
691 dex_files_.push_back(dex_file.get());
692 // Register the dex file so that we can guarantee it doesn't get deleted
693 // while reading it during the task.
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100694 class_linker->RegisterDexFile(*dex_file.get(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100695 }
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100696 // We also create our own global ref to use this class loader later.
697 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), h_loader.Get());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100698 }
699
700 void Run(Thread* self) override {
701 ScopedObjectAccess soa(self);
702 StackHandleScope<1> hs(self);
703 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
704 soa.Decode<mirror::ClassLoader>(class_loader_));
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100705
706 std::string profile = GetProfileFile(dex_files_[0]->GetLocation());
707 std::string boot_profile = GetBootProfileFile(profile);
708
709 Runtime::Current()->GetJit()->CompileMethodsFromBootProfile(
710 self,
711 dex_files_,
712 boot_profile,
713 loader,
714 /* add_to_queue= */ false);
715
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100716 Runtime::Current()->GetJit()->CompileMethodsFromProfile(
717 self,
718 dex_files_,
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100719 profile,
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100720 loader,
721 /* add_to_queue= */ false);
722 }
723
724 void Finalize() override {
725 delete this;
726 }
727
Nicolas Geoffrayf5a07ae2019-06-20 14:59:07 +0100728 ~JitProfileTask() {
729 ScopedObjectAccess soa(Thread::Current());
730 soa.Vm()->DeleteGlobalRef(soa.Self(), class_loader_);
731 }
732
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100733 private:
734 std::vector<const DexFile*> dex_files_;
735 jobject class_loader_;
736
737 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
738};
739
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000740void Jit::CreateThreadPool() {
741 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
742 // is not null when we instrument.
743
744 // We need peers as we may report the JIT thread, e.g., in the debugger.
745 constexpr bool kJitPoolNeedsPeers = true;
746 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
747
748 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
749 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000750
751 // If we're not using the default boot image location, request a JIT task to
752 // compile all methods in the boot image profile.
753 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +0100754 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000755 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
756 }
757}
758
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100759void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100760 jobject class_loader) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100761 if (dex_files.empty()) {
762 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000763 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100764 Runtime* runtime = Runtime::Current();
765 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
766 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
767 }
768}
769
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100770bool Jit::CompileMethodFromProfile(Thread* self,
771 ClassLinker* class_linker,
772 uint32_t method_idx,
773 Handle<mirror::DexCache> dex_cache,
774 Handle<mirror::ClassLoader> class_loader,
775 bool add_to_queue) {
776 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
777 method_idx, dex_cache, class_loader);
778 if (method == nullptr) {
779 self->ClearException();
780 return false;
781 }
782 if (!method->IsCompilable() || !method->IsInvokable()) {
783 return false;
784 }
785 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
786 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
787 class_linker->IsQuickGenericJniStub(entry_point) ||
788 class_linker->IsQuickResolutionStub(entry_point)) {
789 // Special case ZygoteServer class so that it gets compiled before the
790 // zygote enters it. This avoids needing to do OSR during app startup.
791 // TODO: have a profile instead.
792 method->SetPreCompiled();
793 if (!add_to_queue || method->GetDeclaringClass()->DescriptorEquals(
794 "Lcom/android/internal/os/ZygoteServer;")) {
795 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
796 } else {
797 thread_pool_->AddTask(self,
798 new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile));
799 return true;
800 }
801 }
802 return false;
803}
804
805uint32_t Jit::CompileMethodsFromBootProfile(
806 Thread* self,
807 const std::vector<const DexFile*>& dex_files,
808 const std::string& profile_file,
809 Handle<mirror::ClassLoader> class_loader,
810 bool add_to_queue) {
811 unix_file::FdFile profile(profile_file.c_str(), O_RDONLY, true);
812
813 if (profile.Fd() == -1) {
814 PLOG(WARNING) << "No boot profile: " << profile_file;
815 return 0u;
816 }
817
818 ProfileBootInfo profile_info;
819 if (!profile_info.Load(profile.Fd(), dex_files)) {
820 LOG(ERROR) << "Could not load profile file: " << profile_file;
821 return 0u;
822 }
823
824 ScopedObjectAccess soa(self);
825 VariableSizedHandleScope handles(self);
826 std::vector<Handle<mirror::DexCache>> dex_caches;
827 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
828 for (const DexFile* dex_file : profile_info.GetDexFiles()) {
829 dex_caches.push_back(handles.NewHandle(class_linker->FindDexCache(self, *dex_file)));
830 }
831
832 uint32_t added_to_queue = 0;
833 for (const std::pair<uint32_t, uint32_t>& pair : profile_info.GetMethods()) {
834 if (CompileMethodFromProfile(self,
835 class_linker,
836 pair.second,
837 dex_caches[pair.first],
838 class_loader,
839 add_to_queue)) {
840 ++added_to_queue;
841 }
842 }
843 return added_to_queue;
844}
845
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100846uint32_t Jit::CompileMethodsFromProfile(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100847 Thread* self,
848 const std::vector<const DexFile*>& dex_files,
849 const std::string& profile_file,
850 Handle<mirror::ClassLoader> class_loader,
851 bool add_to_queue) {
852
853 if (profile_file.empty()) {
854 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100855 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000856 }
857
858 std::string error_msg;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100859 ScopedFlock profile = LockedFile::Open(
860 profile_file.c_str(), O_RDONLY, /* block= */ false, &error_msg);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000861
862 // Return early if we're unable to obtain a lock on the profile.
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100863 if (profile.get() == nullptr) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000864 LOG(ERROR) << "Cannot lock profile: " << error_msg;
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100865 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000866 }
867
868 ProfileCompilationInfo profile_info;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100869 if (!profile_info.Load(profile->Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000870 LOG(ERROR) << "Could not load profile file";
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100871 return 0u;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000872 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000873 ScopedObjectAccess soa(self);
874 StackHandleScope<1> hs(self);
875 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100876 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100877 uint32_t added_to_queue = 0u;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100878 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100879 if (LocationIsOnRuntimeModule(dex_file->GetLocation().c_str())) {
880 // The runtime module jars are already preopted.
881 continue;
882 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100883 // To speed up class lookups, generate a type lookup table for
884 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +0100885 if (dex_file->GetOatDexFile() == nullptr) {
886 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
887 type_lookup_tables_.push_back(
888 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
889 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
890 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100891
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000892 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000893 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000894 if (!profile_info.GetClassesAndMethods(*dex_file,
895 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000896 &all_methods,
897 &all_methods,
898 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100899 // This means the profile file did not reference the dex file, which is the case
900 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000901 continue;
902 }
903 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
904 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000905
906 for (uint16_t method_idx : all_methods) {
Nicolas Geoffray0f8950a2019-07-24 13:22:11 +0100907 if (CompileMethodFromProfile(self,
908 class_linker,
909 method_idx,
910 dex_cache,
911 class_loader,
912 add_to_queue)) {
913 ++added_to_queue;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000914 }
915 }
916 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100917 return added_to_queue;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000918}
919
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100920static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100921 if (method->IsClassInitializer() || !method->IsCompilable() || method->IsPreCompiled()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100922 // We do not want to compile such methods.
923 return true;
924 }
925 if (method->IsNative()) {
926 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100927 if (klass == GetClassRoot<mirror::MethodHandle>() ||
928 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100929 // MethodHandle and VarHandle invocation methods are required to throw an
930 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000931 // implementations that raise the exception. We need to disable JIT compilation of these JNI
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100932 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
933 // stubs. Since these stubs have different stack representations we can then crash in stack
934 // walking (b/78151261).
935 return true;
936 }
937 }
938 return false;
939}
940
David Srbeckye3fc2d12018-11-30 13:41:14 +0000941bool Jit::MaybeCompileMethod(Thread* self,
942 ArtMethod* method,
943 uint32_t old_count,
944 uint32_t new_count,
945 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100946 if (thread_pool_ == nullptr) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000947 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100948 }
David Srbecky1fc4d422019-07-23 16:55:19 +0100949 if (UNLIKELY(method->IsPreCompiled()) && !with_backedges /* don't check for OSR */) {
950 const void* code_ptr = code_cache_->GetZygoteMap()->GetCodeFor(method);
951 if (code_ptr != nullptr) {
952 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(method, code_ptr);
953 return true;
954 }
955 }
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100956 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000957 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100958 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100959 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +0000960 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +0000961 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +0000962 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100963 DCHECK_GT(WarmMethodThreshold(), 0);
964 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
965 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
966 DCHECK_GE(PriorityThreadWeight(), 1);
967 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100968
David Srbeckye3fc2d12018-11-30 13:41:14 +0000969 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
970 // Note: Native method have no "warm" state or profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000971 if (!method->IsNative() &&
972 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) &&
973 code_cache_->CanAllocateProfilingInfo()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700974 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000975 if (success) {
976 VLOG(jit) << "Start profiling " << method->PrettyMethod();
977 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100978
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000979 if (thread_pool_ == nullptr) {
980 // Calling ProfilingInfo::Create might put us in a suspended state, which could
981 // lead to the thread pool being deleted when we are shutting down.
David Srbeckye3fc2d12018-11-30 13:41:14 +0000982 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000983 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100984
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000985 if (!success) {
986 // We failed allocating. Instead of doing the collection on the Java thread, we push
987 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000988 thread_pool_->AddTask(
989 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000990 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100991 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000992 }
993 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +0100994 if (old_count == 0 &&
995 method->IsNative() &&
996 Runtime::Current()->IsUsingApexBootImageLocation()) {
997 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100998 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +0100999 return true;
1000 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001001 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
1002 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +01001003 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001004 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +01001005 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001006 }
1007 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001008 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +00001009 return false;
Calin Juravleffc87072016-04-20 14:22:09 +01001010 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001011 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +00001012 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +01001013 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001014 thread_pool_->AddTask(
1015 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +01001016 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001017 }
1018 }
David Srbeckye3fc2d12018-11-30 13:41:14 +00001019 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001020}
1021
Alex Light59b950f2018-10-08 10:43:06 -07001022class ScopedSetRuntimeThread {
1023 public:
1024 explicit ScopedSetRuntimeThread(Thread* self)
1025 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
1026 self_->SetIsRuntimeThread(true);
1027 }
1028
1029 ~ScopedSetRuntimeThread() {
1030 self_->SetIsRuntimeThread(was_runtime_thread_);
1031 }
1032
1033 private:
1034 Thread* self_;
1035 bool was_runtime_thread_;
1036};
1037
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001038void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +01001039 Runtime* runtime = Runtime::Current();
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001040 if (UNLIKELY(runtime->UseJitCompilation() && JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001041 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001042 if (np_method->IsCompilable()) {
Nicolas Geoffray5e33ccd2019-07-03 10:53:08 +01001043 if (!np_method->IsNative() && GetCodeCache()->CanAllocateProfilingInfo()) {
Nicolas Geoffray29bb8032019-06-06 10:32:24 +01001044 // The compiler requires a ProfilingInfo object for non-native methods.
1045 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
1046 }
1047 // TODO(ngeoffray): For JIT at first use, use kPreCompile. Currently we don't due to
1048 // conflicts with jitzygote optimizations.
1049 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -07001050 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
1051 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +00001052 compile_task.Run(thread);
1053 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001054 return;
1055 }
1056
Andreas Gampe542451c2016-07-26 09:02:02 -07001057 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001058 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -07001059 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
1060 // must remain the instrumentation entrypoint.
1061 if ((profiling_info != nullptr) &&
1062 (profiling_info->GetSavedEntryPoint() != nullptr) &&
1063 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001064 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1065 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001066 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001067 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001068 }
1069}
1070
Mathieu Chartieref41db72016-10-25 15:08:01 -07001071void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001072 ArtMethod* caller,
1073 uint32_t dex_pc,
1074 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001075 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001076 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -07001077 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001078 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +01001079 info->AddInvokeInfo(dex_pc, this_object->GetClass());
1080 }
1081}
1082
1083void Jit::WaitForCompilationToFinish(Thread* self) {
1084 if (thread_pool_ != nullptr) {
1085 thread_pool_->Wait(self, false, false);
1086 }
1087}
1088
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001089void Jit::Stop() {
1090 Thread* self = Thread::Current();
1091 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
1092 WaitForCompilationToFinish(self);
1093 GetThreadPool()->StopWorkers(self);
1094 WaitForCompilationToFinish(self);
1095}
1096
1097void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +00001098 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001099}
1100
Andreas Gampef149b3f2016-11-16 14:58:24 -08001101ScopedJitSuspend::ScopedJitSuspend() {
1102 jit::Jit* jit = Runtime::Current()->GetJit();
1103 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
1104 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001105 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001106 }
1107}
1108
1109ScopedJitSuspend::~ScopedJitSuspend() {
1110 if (was_on_) {
1111 DCHECK(Runtime::Current()->GetJit() != nullptr);
1112 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001113 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001114 }
1115}
1116
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001117void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001118 if (is_zygote || Runtime::Current()->IsSafeMode()) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001119 // Delete the thread pool, we are not going to JIT.
1120 thread_pool_.reset(nullptr);
1121 return;
1122 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001123 // At this point, the compiler options have been adjusted to the particular configuration
1124 // of the forked child. Parse them again.
1125 jit_update_options_(jit_compiler_handle_);
1126
1127 // Adjust the status of code cache collection: the status from zygote was to not collect.
1128 code_cache_->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
1129 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001130
1131 if (thread_pool_ != nullptr) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001132 if (is_system_server &&
1133 Runtime::Current()->IsUsingApexBootImageLocation() &&
1134 UseJitCompilation()) {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001135 // Disable garbage collection: we don't want it to delete methods we're compiling
1136 // through boot and system server profiles.
1137 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1138 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001139 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001140
1141 // Resume JIT compilation.
1142 thread_pool_->CreateThreads();
1143 }
1144}
1145
1146void Jit::PreZygoteFork() {
1147 if (thread_pool_ == nullptr) {
1148 return;
1149 }
1150 thread_pool_->DeleteThreads();
1151}
1152
1153void Jit::PostZygoteFork() {
1154 if (thread_pool_ == nullptr) {
1155 return;
1156 }
1157 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001158}
1159
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001160bool Jit::CanEncodeMethod(ArtMethod* method, bool is_for_shared_region) const {
1161 return !is_for_shared_region ||
1162 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(method->GetDeclaringClass());
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001163}
1164
1165bool Jit::CanEncodeClass(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001166 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(cls);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001167}
1168
1169bool Jit::CanEncodeString(ObjPtr<mirror::String> string, bool is_for_shared_region) const {
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001170 return !is_for_shared_region || Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string);
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001171}
1172
Nicolas Geoffray05b41c42019-06-28 12:46:33 +01001173bool Jit::CanAssumeInitialized(ObjPtr<mirror::Class> cls, bool is_for_shared_region) const {
1174 if (!is_for_shared_region) {
1175 return cls->IsInitialized();
1176 } else {
1177 // Look up the class status in the oat file.
1178 const DexFile& dex_file = *cls->GetDexCache()->GetDexFile();
1179 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1180 // In case we run without an image there won't be a backing oat file.
1181 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
1182 return false;
1183 }
1184 uint16_t class_def_index = cls->GetDexClassDefIndex();
1185 return oat_dex_file->GetOatClass(class_def_index).GetStatus() >= ClassStatus::kInitialized;
1186 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001187}
1188
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001189} // namespace jit
1190} // namespace art