blob: cbfc3a19bd79739e4de043a77ab5cd880d04058a [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"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080031#include "entrypoints/runtime_asm_entrypoints.h"
32#include "interpreter/interpreter.h"
David Srbeckye3fc2d12018-11-30 13:41:14 +000033#include "jit-inl.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010035#include "jni/java_vm_ext.h"
Orion Hodson52f5a1f2018-05-02 11:05:44 +010036#include "mirror/method_handle_impl.h"
37#include "mirror/var_handle.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010038#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000039#include "oat_quick_method_header.h"
David Sehr82d046e2018-04-23 08:14:19 -070040#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000041#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080042#include "runtime.h"
43#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070044#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000045#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070046#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010047#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080048
49namespace art {
50namespace jit {
51
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000052static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000053
Andreas Gampe7897cec2017-07-19 16:28:59 -070054// Different compilation threshold constants. These can be overridden on the command line.
55static constexpr size_t kJitDefaultCompileThreshold = 10000; // Non-debug default.
56static constexpr size_t kJitStressDefaultCompileThreshold = 100; // Fast-debug build.
57static constexpr size_t kJitSlowStressDefaultCompileThreshold = 2; // Slow-debug build.
58
Mathieu Chartier72918ea2016-03-24 11:07:06 -070059// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080060void* Jit::jit_library_handle_ = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070061void* Jit::jit_compiler_handle_ = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000062void* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070063void (*Jit::jit_unload_)(void*) = nullptr;
Nicolas Geoffray075456e2018-12-14 08:54:21 +000064bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool, bool) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070065void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000066bool (*Jit::jit_generate_debug_info_)(void*) = nullptr;
67void (*Jit::jit_update_options_)(void*) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070068
Andreas Gampe7897cec2017-07-19 16:28:59 -070069struct StressModeHelper {
70 DECLARE_RUNTIME_DEBUG_FLAG(kSlowMode);
71};
72DEFINE_RUNTIME_DEBUG_FLAG(StressModeHelper, kSlowMode);
73
David Srbeckye3fc2d12018-11-30 13:41:14 +000074uint32_t JitOptions::RoundUpThreshold(uint32_t threshold) {
75 if (threshold > kJitSamplesBatchSize) {
76 threshold = RoundUp(threshold, kJitSamplesBatchSize);
77 }
78 CHECK_LE(threshold, std::numeric_limits<uint16_t>::max());
79 return threshold;
80}
81
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080082JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080083 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010084 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000085
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000086 jit_options->code_cache_initial_capacity_ =
87 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
88 jit_options->code_cache_max_capacity_ =
89 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070090 jit_options->dump_info_on_shutdown_ =
91 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010092 jit_options->profile_saver_options_ =
93 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +010094 jit_options->thread_pool_pthread_priority_ =
95 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000096
Andreas Gampe7897cec2017-07-19 16:28:59 -070097 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
98 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
99 } else {
100 jit_options->compile_threshold_ =
101 kIsDebugBuild
102 ? (StressModeHelper::kSlowMode
103 ? kJitSlowStressDefaultCompileThreshold
104 : kJitStressDefaultCompileThreshold)
105 : kJitDefaultCompileThreshold;
106 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000107 jit_options->compile_threshold_ = RoundUpThreshold(jit_options->compile_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000108
109 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
110 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000111 } else {
112 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
113 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000114 jit_options->warmup_threshold_ = RoundUpThreshold(jit_options->warmup_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000115
116 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
117 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000118 } else {
119 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
120 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000121 jit_options->osr_threshold_ =
122 RoundDown(std::numeric_limits<uint16_t>::max(), kJitSamplesBatchSize);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000123 }
124 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000125 jit_options->osr_threshold_ = RoundUpThreshold(jit_options->osr_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000126
Calin Juravleb2771b42016-04-07 17:09:25 +0100127 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
128 jit_options->priority_thread_weight_ =
129 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
130 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
131 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
132 } else if (jit_options->priority_thread_weight_ == 0) {
133 LOG(FATAL) << "Priority thread weight cannot be 0.";
134 }
135 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100136 jit_options->priority_thread_weight_ = std::max(
137 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
138 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100139 }
140
Calin Juravle155ff3d2016-04-27 14:14:58 +0100141 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100142 jit_options->invoke_transition_weight_ =
143 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100144 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
145 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
146 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100147 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100148 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100149 } else {
150 jit_options->invoke_transition_weight_ = std::max(
151 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800152 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100153 }
154
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800155 return jit_options;
156}
157
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700158void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000159 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700160 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000161 MutexLock mu(Thread::Current(), lock_);
162 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700163}
164
Calin Juravleb8e69992016-03-09 15:37:48 +0000165void Jit::DumpForSigQuit(std::ostream& os) {
166 DumpInfo(os);
167 ProfileSaver::DumpInstanceInfo(os);
168}
169
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700170void Jit::AddTimingLogger(const TimingLogger& logger) {
171 cumulative_timings_.AddLogger(logger);
172}
173
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100174Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
175 : code_cache_(code_cache),
176 options_(options),
177 cumulative_timings_("JIT timings"),
178 memory_use_("Memory used for compilation", 16),
179 lock_("JIT memory use lock") {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800180
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100181Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000182 if (jit_load_ == nullptr) {
183 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800184 return nullptr;
185 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000186 jit_compiler_handle_ = (jit_load_)();
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000187 if (jit_compiler_handle_ == nullptr) {
188 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
189 return nullptr;
190 }
191 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000192
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000193 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000194 // With 'perf', we want a 1-1 mapping between an address and a method.
195 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
196 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000197 if (code_cache->GetGarbageCollectCode()) {
198 code_cache->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
199 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
200 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100201
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000202 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000203 << PrettySize(options->GetCodeCacheInitialCapacity())
204 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000205 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100206 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100207
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100208 // Notify native debugger about the classes already loaded before the creation of the jit.
209 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800210 return jit.release();
211}
212
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000213template <typename T>
214bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
215 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
216 if (*address == nullptr) {
217 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
218 return false;
219 }
220 return true;
221}
222
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000223bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800224 jit_library_handle_ = dlopen(
225 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
226 if (jit_library_handle_ == nullptr) {
227 std::ostringstream oss;
228 oss << "JIT could not load libart-compiler.so: " << dlerror();
229 *error_msg = oss.str();
230 return false;
231 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000232 bool all_resolved = true;
233 all_resolved = all_resolved && LoadSymbol(&jit_load_, "jit_load", error_msg);
234 all_resolved = all_resolved && LoadSymbol(&jit_unload_, "jit_unload", error_msg);
235 all_resolved = all_resolved && LoadSymbol(&jit_compile_method_, "jit_compile_method", error_msg);
236 all_resolved = all_resolved && LoadSymbol(&jit_types_loaded_, "jit_types_loaded", error_msg);
237 all_resolved = all_resolved && LoadSymbol(&jit_update_options_, "jit_update_options", error_msg);
238 all_resolved = all_resolved &&
239 LoadSymbol(&jit_generate_debug_info_, "jit_generate_debug_info", error_msg);
240 if (!all_resolved) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800241 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000242 return false;
243 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700244 return true;
245}
246
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000247bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr) {
Calin Juravleffc87072016-04-20 14:22:09 +0100248 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800249 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000250
Alex Light0fa17862017-10-24 13:43:05 -0700251 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100252 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700253 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
254 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
255 << " due to not being safe to jit according to runtime-callbacks. For example, there"
256 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700257 return false;
258 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100259
260 // Don't compile the method if we are supposed to be deoptimized.
261 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
262 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700263 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100264 return false;
265 }
266
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000267 // If we get a request to compile a proxy method, we pass the actual Java method
268 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700269 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000270 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100271 return false;
272 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100273
274 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700275 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100276 << " osr=" << std::boolalpha << osr;
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000277 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700278 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100279 if (!success) {
280 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700281 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100282 << " osr=" << std::boolalpha << osr;
283 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800284 if (kIsDebugBuild) {
285 if (self->IsExceptionPending()) {
286 mirror::Throwable* exception = self->GetException();
287 LOG(FATAL) << "No pending exception expected after compiling "
288 << ArtMethod::PrettyMethod(method)
289 << ": "
290 << exception->Dump();
291 }
292 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100293 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800294}
295
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800296void Jit::WaitForWorkersToBeCreated() {
297 if (thread_pool_ != nullptr) {
298 thread_pool_->WaitForWorkersToBeCreated();
299 }
300}
301
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800302void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100303 Thread* self = Thread::Current();
304 DCHECK(Runtime::Current()->IsShuttingDown(self));
305 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700306 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100307 {
308 ScopedSuspendAll ssa(__FUNCTION__);
309 // Clear thread_pool_ field while the threads are suspended.
310 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700311 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100312 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700313
314 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000315 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700316 pool->StopWorkers(self);
317 pool->RemoveAllTasks(self);
318 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100319 // We could just suspend all threads, but we know those threads
320 // will finish in a short period, so it's not worth adding a suspend logic
321 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700322 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800323 }
324}
325
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000326void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800327 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100328 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100329 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100330 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000331}
332
333void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100334 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
335 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100336 }
337}
338
Siva Chandra05d24152016-01-05 17:43:17 -0800339bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100340 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800341}
342
Nicolas Geoffray35122442016-03-02 12:05:30 +0000343bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
344 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
345}
346
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800347Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100348 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
349 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700350 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100351 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700352 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800353 DeleteThreadPool();
354 if (jit_compiler_handle_ != nullptr) {
355 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700356 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800357 }
358 if (jit_library_handle_ != nullptr) {
359 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700360 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800361 }
362}
363
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000364void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100365 if (!Runtime::Current()->UseJitCompilation()) {
366 // No need to notify if we only use the JIT to save profiles.
367 return;
368 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000369 jit::Jit* jit = Runtime::Current()->GetJit();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000370 if (jit_generate_debug_info_(jit->jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000371 DCHECK(jit->jit_types_loaded_ != nullptr);
372 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
373 }
374}
375
376void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
377 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100378 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700379 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000380 return true;
381 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800382 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000383 };
384
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000385 if (jit_generate_debug_info_(jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000386 ScopedObjectAccess so(Thread::Current());
387
388 CollectClasses visitor;
389 linker->VisitClasses(&visitor);
390 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000391 }
392}
393
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000394extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700395 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000396 const uint8_t* native_pc,
397 JValue* result,
398 const char* shorty,
399 Thread* self);
400
401bool Jit::MaybeDoOnStackReplacement(Thread* thread,
402 ArtMethod* method,
403 uint32_t dex_pc,
404 int32_t dex_pc_offset,
405 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000406 if (!kEnableOnStackReplacement) {
407 return false;
408 }
409
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000410 Jit* jit = Runtime::Current()->GetJit();
411 if (jit == nullptr) {
412 return false;
413 }
414
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000415 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
416 // Don't attempt to do an OSR if we are close to the stack limit. Since
417 // the interpreter frames are still on stack, OSR has the potential
418 // to stack overflow even for a simple loop.
419 // b/27094810.
420 return false;
421 }
422
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000423 // Get the actual Java method if this method is from a proxy class. The compiler
424 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700425 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000426
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000427 // Cheap check if the method has been compiled already. That's an indicator that we should
428 // osr into it.
429 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
430 return false;
431 }
432
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000433 // Fetch some data before looking up for an OSR method. We don't want thread
434 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
435 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000436 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800437 const size_t number_of_vregs = accessor.RegistersSize();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000438 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700439 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000440 void** memory = nullptr;
441 size_t frame_size = 0;
442 ShadowFrame* shadow_frame = nullptr;
443 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000444
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000445 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700446 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000447 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
448 if (osr_method == nullptr) {
449 // No osr method yet, just return to the interpreter.
450 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000451 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000452
David Srbecky052f8ca2018-04-26 15:42:54 +0100453 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000454
455 // Find stack map starting at the target dex_pc.
David Srbecky052f8ca2018-04-26 15:42:54 +0100456 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000457 if (!stack_map.IsValid()) {
458 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
459 // hope that the next branch has one.
460 return false;
461 }
462
Alex Light21611932017-09-26 13:07:39 -0700463 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
464 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
465 // disable OSR when single stepping, but that's currently hard to know at this point.
466 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
Aart Bik29bdaee2016-05-18 15:44:07 -0700467 return false;
468 }
469
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000470 // We found a stack map, now fill the frame with dex register values from the interpreter's
471 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100472 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000473
474 frame_size = osr_method->GetFrameSizeInBytes();
475
476 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
477 // stack.
478 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
479 // but that is engineering complexity not worth the effort for something like OSR.
480 memory = reinterpret_cast<void**>(malloc(frame_size));
481 CHECK(memory != nullptr);
482 memset(memory, 0, frame_size);
483
484 // Art ABI: ArtMethod is at the bottom of the stack.
485 memory[0] = method;
486
487 shadow_frame = thread->PopShadowFrame();
David Srbeckyfd89b072018-06-03 12:00:22 +0100488 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000489 // If we don't have a dex register map, then there are no live dex registers at
490 // this dex pc.
491 } else {
David Srbeckyfd89b072018-06-03 12:00:22 +0100492 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000493 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100494 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000495 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000496 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000497 continue;
498 }
499
500 if (location == DexRegisterLocation::Kind::kConstant) {
501 // We skip constants because the compiled code knows how to handle them.
502 continue;
503 }
504
David Srbecky7dc11782016-02-25 13:23:56 +0000505 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000506
507 int32_t vreg_value = shadow_frame->GetVReg(vreg);
David Srbeckye1402122018-06-13 18:20:45 +0100508 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000509 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
510 DCHECK_GT(slot_offset, 0);
511 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
512 }
513 }
514
David Srbecky052f8ca2018-04-26 15:42:54 +0100515 native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000516 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000517 VLOG(jit) << "Jumping to "
518 << method_name
519 << "@"
520 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000521 }
522
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000523 {
524 ManagedStack fragment;
525 thread->PushManagedStackFragment(&fragment);
526 (*art_quick_osr_stub)(memory,
527 frame_size,
528 native_pc,
529 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000530 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000531 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000532
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000533 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
534 thread->DeoptimizeWithDeoptimizationException(result);
535 }
536 thread->PopManagedStackFragment(fragment);
537 }
538 free(memory);
539 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000540 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000541 return true;
542}
543
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000544void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
545 if (bytes > 4 * MB) {
546 LOG(INFO) << "Compiler allocated "
547 << PrettySize(bytes)
548 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700549 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000550 }
551 MutexLock mu(Thread::Current(), lock_);
552 memory_use_.AddValue(bytes);
553}
554
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100555class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100556 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000557 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100558 kAllocateProfile,
559 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000560 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000561 kCompileOsr,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100562 };
563
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000564 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100565 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000566 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
567 // until compilation is done.
568 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
569 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
570 CHECK(klass_ != nullptr);
571 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100572 }
573
574 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000575 if (klass_ != nullptr) {
576 ScopedObjectAccess soa(Thread::Current());
577 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
578 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100579 }
580
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100581 void Run(Thread* self) override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100582 ScopedObjectAccess soa(self);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000583 switch (kind_) {
584 case TaskKind::kCompile:
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000585 case TaskKind::kCompileBaseline:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000586 case TaskKind::kCompileOsr: {
587 Runtime::Current()->GetJit()->CompileMethod(
588 method_,
589 self,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000590 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000591 /* osr= */ (kind_ == TaskKind::kCompileOsr));
592 break;
593 }
594 case TaskKind::kAllocateProfile: {
595 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
596 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
597 }
598 break;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100599 }
600 }
Calin Juravlea2638922016-04-29 16:44:11 +0100601 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100602 }
603
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100604 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100605 delete this;
606 }
607
608 private:
609 ArtMethod* const method_;
610 const TaskKind kind_;
611 jobject klass_;
612
613 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
614};
615
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000616class ZygoteTask final : public Task {
617 public:
618 ZygoteTask() {}
619
620 void Run(Thread* self) override {
621 Runtime::Current()->GetJit()->AddNonAotBootMethodsToQueue(self);
622 }
623
624 private:
625 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
626};
627
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000628void Jit::CreateThreadPool() {
629 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
630 // is not null when we instrument.
631
632 // We need peers as we may report the JIT thread, e.g., in the debugger.
633 constexpr bool kJitPoolNeedsPeers = true;
634 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
635
636 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
637 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000638
639 // If we're not using the default boot image location, request a JIT task to
640 // compile all methods in the boot image profile.
641 Runtime* runtime = Runtime::Current();
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100642 if (runtime->IsZygote() && !runtime->IsUsingDefaultBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000643 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
644 }
645}
646
647void Jit::AddNonAotBootMethodsToQueue(Thread* self) {
648 Runtime* runtime = Runtime::Current();
649 std::string profile_location;
650 for (const std::string& option : runtime->GetImageCompilerOptions()) {
651 if (android::base::StartsWith(option, "--profile-file=")) {
652 profile_location = option.substr(strlen("--profile-file="));
653 break;
654 }
655 }
656 if (profile_location.empty()) {
657 LOG(WARNING) << "Expected a profile location in JIT zygote mode";
658 return;
659 }
660
661 std::string error_msg;
662 ScopedFlock profile_file = LockedFile::Open(
663 profile_location.c_str(), O_RDONLY, true, &error_msg);
664
665 // Return early if we're unable to obtain a lock on the profile.
666 if (profile_file.get() == nullptr) {
667 LOG(ERROR) << "Cannot lock profile: " << error_msg;
668 return;
669 }
670
671 ProfileCompilationInfo profile_info;
672 if (!profile_info.Load(profile_file->Fd())) {
673 LOG(ERROR) << "Could not load profile file";
674 return;
675 }
676
677 const std::vector<const DexFile*>& boot_class_path =
678 runtime->GetClassLinker()->GetBootClassPath();
679 ScopedObjectAccess soa(self);
680 StackHandleScope<1> hs(self);
681 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
682 ScopedNullHandle<mirror::ClassLoader> null_handle;
683 ClassLinker* class_linker = runtime->GetClassLinker();
684
685 for (const DexFile* dex_file : boot_class_path) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100686 if (LocationIsOnRuntimeModule(dex_file->GetLocation().c_str())) {
687 // The runtime module jars are already preopted.
688 continue;
689 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000690 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000691 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000692 if (!profile_info.GetClassesAndMethods(*dex_file,
693 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000694 &all_methods,
695 &all_methods,
696 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100697 // This means the profile file did not reference the dex file, which is the case
698 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000699 continue;
700 }
701 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
702 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000703
704 for (uint16_t method_idx : all_methods) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000705 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
706 method_idx, dex_cache, null_handle);
707 if (method == nullptr) {
708 self->ClearException();
709 continue;
710 }
711 if (!method->IsCompilable() || !method->IsInvokable()) {
712 continue;
713 }
714 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
715 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100716 class_linker->IsQuickGenericJniStub(entry_point) ||
717 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000718 if (!method->IsNative()) {
719 // The compiler requires a ProfilingInfo object for non-native methods.
720 ProfilingInfo::Create(self, method, /* retry_allocation= */ true);
721 }
722 thread_pool_->AddTask(self,
723 new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
724 }
725 }
726 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000727}
728
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100729static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
730 if (method->IsClassInitializer() || !method->IsCompilable()) {
731 // We do not want to compile such methods.
732 return true;
733 }
734 if (method->IsNative()) {
735 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100736 if (klass == GetClassRoot<mirror::MethodHandle>() ||
737 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100738 // MethodHandle and VarHandle invocation methods are required to throw an
739 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
740 // implementations that arise the exception. We need to disable JIT compilation of these JNI
741 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
742 // stubs. Since these stubs have different stack representations we can then crash in stack
743 // walking (b/78151261).
744 return true;
745 }
746 }
747 return false;
748}
749
David Srbeckye3fc2d12018-11-30 13:41:14 +0000750bool Jit::MaybeCompileMethod(Thread* self,
751 ArtMethod* method,
752 uint32_t old_count,
753 uint32_t new_count,
754 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100755 if (thread_pool_ == nullptr) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000756 // Should only see this when shutting down, starting up, or in safe mode.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000757 DCHECK(Runtime::Current()->IsShuttingDown(self) ||
758 !Runtime::Current()->IsFinishedStarting() ||
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000759 Runtime::Current()->IsSafeMode());
David Srbeckye3fc2d12018-11-30 13:41:14 +0000760 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100761 }
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100762 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000763 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100764 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100765 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +0000766 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +0000767 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +0000768 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100769 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100770 DCHECK_GT(WarmMethodThreshold(), 0);
771 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
772 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
773 DCHECK_GE(PriorityThreadWeight(), 1);
774 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100775
David Srbeckye3fc2d12018-11-30 13:41:14 +0000776 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
777 // Note: Native method have no "warm" state or profiling info.
778 if (!method->IsNative() && method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700779 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000780 if (success) {
781 VLOG(jit) << "Start profiling " << method->PrettyMethod();
782 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100783
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000784 if (thread_pool_ == nullptr) {
785 // Calling ProfilingInfo::Create might put us in a suspended state, which could
786 // lead to the thread pool being deleted when we are shutting down.
787 DCHECK(Runtime::Current()->IsShuttingDown(self));
David Srbeckye3fc2d12018-11-30 13:41:14 +0000788 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000789 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100790
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000791 if (!success) {
792 // We failed allocating. Instead of doing the collection on the Java thread, we push
793 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000794 thread_pool_->AddTask(
795 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000796 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100797 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000798 }
799 if (UseJitCompilation()) {
800 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
801 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +0100802 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000803 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +0100804 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000805 }
806 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +0100807 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000808 return false;
Calin Juravleffc87072016-04-20 14:22:09 +0100809 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000810 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +0000811 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +0100812 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000813 thread_pool_->AddTask(
814 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +0100815 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100816 }
817 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000818 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100819}
820
Alex Light59b950f2018-10-08 10:43:06 -0700821class ScopedSetRuntimeThread {
822 public:
823 explicit ScopedSetRuntimeThread(Thread* self)
824 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
825 self_->SetIsRuntimeThread(true);
826 }
827
828 ~ScopedSetRuntimeThread() {
829 self_->SetIsRuntimeThread(was_runtime_thread_);
830 }
831
832 private:
833 Thread* self_;
834 bool was_runtime_thread_;
835};
836
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100837void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +0100838 Runtime* runtime = Runtime::Current();
839 if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000840 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000841 if (np_method->IsCompilable()) {
Vladimir Markof8655b32018-03-21 17:53:56 +0000842 if (!np_method->IsNative()) {
843 // The compiler requires a ProfilingInfo object for non-native methods.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700844 ProfilingInfo::Create(thread, np_method, /* retry_allocation= */ true);
Vladimir Markof8655b32018-03-21 17:53:56 +0000845 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000846 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kCompile);
Alex Light59b950f2018-10-08 10:43:06 -0700847 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
848 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000849 compile_task.Run(thread);
850 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100851 return;
852 }
853
Andreas Gampe542451c2016-07-26 09:02:02 -0700854 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100855 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -0700856 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
857 // must remain the instrumentation entrypoint.
858 if ((profiling_info != nullptr) &&
859 (profiling_info->GetSavedEntryPoint() != nullptr) &&
860 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100861 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
862 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100863 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700864 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100865 }
866}
867
Mathieu Chartieref41db72016-10-25 15:08:01 -0700868void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100869 ArtMethod* caller,
870 uint32_t dex_pc,
871 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700872 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100873 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -0700874 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100875 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100876 info->AddInvokeInfo(dex_pc, this_object->GetClass());
877 }
878}
879
880void Jit::WaitForCompilationToFinish(Thread* self) {
881 if (thread_pool_ != nullptr) {
882 thread_pool_->Wait(self, false, false);
883 }
884}
885
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000886void Jit::Stop() {
887 Thread* self = Thread::Current();
888 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
889 WaitForCompilationToFinish(self);
890 GetThreadPool()->StopWorkers(self);
891 WaitForCompilationToFinish(self);
892}
893
894void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +0000895 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000896}
897
Andreas Gampef149b3f2016-11-16 14:58:24 -0800898ScopedJitSuspend::ScopedJitSuspend() {
899 jit::Jit* jit = Runtime::Current()->GetJit();
900 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
901 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000902 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800903 }
904}
905
906ScopedJitSuspend::~ScopedJitSuspend() {
907 if (was_on_) {
908 DCHECK(Runtime::Current()->GetJit() != nullptr);
909 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000910 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800911 }
912}
913
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000914void Jit::PostForkChildAction(bool is_zygote) {
915 if (is_zygote) {
Nicolas Geoffray953da542019-03-04 10:09:11 +0000916 // Remove potential tasks that have been inherited from the zygote. Child zygotes
917 // currently don't need the whole boot image compiled (ie webview_zygote).
918 thread_pool_->RemoveAllTasks(Thread::Current());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000919 // Don't transition if this is for a child zygote.
920 return;
921 }
922 if (Runtime::Current()->IsSafeMode()) {
923 // Delete the thread pool, we are not going to JIT.
924 thread_pool_.reset(nullptr);
925 return;
926 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000927 // At this point, the compiler options have been adjusted to the particular configuration
928 // of the forked child. Parse them again.
929 jit_update_options_(jit_compiler_handle_);
930
931 // Adjust the status of code cache collection: the status from zygote was to not collect.
932 code_cache_->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
933 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000934
935 if (thread_pool_ != nullptr) {
936 // Remove potential tasks that have been inherited from the zygote.
937 thread_pool_->RemoveAllTasks(Thread::Current());
938
939 // Resume JIT compilation.
940 thread_pool_->CreateThreads();
941 }
942}
943
944void Jit::PreZygoteFork() {
945 if (thread_pool_ == nullptr) {
946 return;
947 }
948 thread_pool_->DeleteThreads();
949}
950
951void Jit::PostZygoteFork() {
952 if (thread_pool_ == nullptr) {
953 return;
954 }
955 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000956}
957
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800958} // namespace jit
959} // namespace art