blob: 68bdf53d1267746fd80d653aaaea7a89dabb2abe [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"
David Sehr82d046e2018-04-23 08:14:19 -070042#include "profile/profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000043#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080044#include "runtime.h"
45#include "runtime_options.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070046#include "stack.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000047#include "stack_map.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070048#include "thread-inl.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010049#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080050
51namespace art {
52namespace jit {
53
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000054static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000055
Andreas Gampe7897cec2017-07-19 16:28:59 -070056// Different compilation threshold constants. These can be overridden on the command line.
57static constexpr size_t kJitDefaultCompileThreshold = 10000; // Non-debug default.
58static constexpr size_t kJitStressDefaultCompileThreshold = 100; // Fast-debug build.
59static constexpr size_t kJitSlowStressDefaultCompileThreshold = 2; // Slow-debug build.
60
Mathieu Chartier72918ea2016-03-24 11:07:06 -070061// JIT compiler
Igor Murashkin2ffb7032017-11-08 13:35:21 -080062void* Jit::jit_library_handle_ = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070063void* Jit::jit_compiler_handle_ = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000064void* (*Jit::jit_load_)(void) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070065void (*Jit::jit_unload_)(void*) = nullptr;
Nicolas Geoffray075456e2018-12-14 08:54:21 +000066bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool, bool) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070067void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +000068bool (*Jit::jit_generate_debug_info_)(void*) = nullptr;
69void (*Jit::jit_update_options_)(void*) = nullptr;
Mathieu Chartier72918ea2016-03-24 11:07:06 -070070
Andreas Gampe7897cec2017-07-19 16:28:59 -070071struct StressModeHelper {
72 DECLARE_RUNTIME_DEBUG_FLAG(kSlowMode);
73};
74DEFINE_RUNTIME_DEBUG_FLAG(StressModeHelper, kSlowMode);
75
David Srbeckye3fc2d12018-11-30 13:41:14 +000076uint32_t JitOptions::RoundUpThreshold(uint32_t threshold) {
77 if (threshold > kJitSamplesBatchSize) {
78 threshold = RoundUp(threshold, kJitSamplesBatchSize);
79 }
80 CHECK_LE(threshold, std::numeric_limits<uint16_t>::max());
81 return threshold;
82}
83
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080084JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080085 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010086 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000087
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000088 jit_options->code_cache_initial_capacity_ =
89 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
90 jit_options->code_cache_max_capacity_ =
91 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070092 jit_options->dump_info_on_shutdown_ =
93 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010094 jit_options->profile_saver_options_ =
95 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray47b95802018-05-16 15:42:17 +010096 jit_options->thread_pool_pthread_priority_ =
97 options.GetOrDefault(RuntimeArgumentMap::JITPoolThreadPthreadPriority);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000098
Andreas Gampe7897cec2017-07-19 16:28:59 -070099 if (options.Exists(RuntimeArgumentMap::JITCompileThreshold)) {
100 jit_options->compile_threshold_ = *options.Get(RuntimeArgumentMap::JITCompileThreshold);
101 } else {
102 jit_options->compile_threshold_ =
103 kIsDebugBuild
104 ? (StressModeHelper::kSlowMode
105 ? kJitSlowStressDefaultCompileThreshold
106 : kJitStressDefaultCompileThreshold)
107 : kJitDefaultCompileThreshold;
108 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000109 jit_options->compile_threshold_ = RoundUpThreshold(jit_options->compile_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000110
111 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
112 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000113 } else {
114 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
115 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000116 jit_options->warmup_threshold_ = RoundUpThreshold(jit_options->warmup_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000117
118 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
119 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000120 } else {
121 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
122 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000123 jit_options->osr_threshold_ =
124 RoundDown(std::numeric_limits<uint16_t>::max(), kJitSamplesBatchSize);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000125 }
126 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000127 jit_options->osr_threshold_ = RoundUpThreshold(jit_options->osr_threshold_);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +0000128
Calin Juravleb2771b42016-04-07 17:09:25 +0100129 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
130 jit_options->priority_thread_weight_ =
131 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
132 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
133 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
134 } else if (jit_options->priority_thread_weight_ == 0) {
135 LOG(FATAL) << "Priority thread weight cannot be 0.";
136 }
137 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100138 jit_options->priority_thread_weight_ = std::max(
139 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
140 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100141 }
142
Calin Juravle155ff3d2016-04-27 14:14:58 +0100143 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100144 jit_options->invoke_transition_weight_ =
145 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100146 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
147 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
148 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100149 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100150 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100151 } else {
152 jit_options->invoke_transition_weight_ = std::max(
153 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800154 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100155 }
156
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800157 return jit_options;
158}
159
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700160void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000161 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700162 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000163 MutexLock mu(Thread::Current(), lock_);
164 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700165}
166
Calin Juravleb8e69992016-03-09 15:37:48 +0000167void Jit::DumpForSigQuit(std::ostream& os) {
168 DumpInfo(os);
169 ProfileSaver::DumpInstanceInfo(os);
170}
171
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700172void Jit::AddTimingLogger(const TimingLogger& logger) {
173 cumulative_timings_.AddLogger(logger);
174}
175
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100176Jit::Jit(JitCodeCache* code_cache, JitOptions* options)
177 : code_cache_(code_cache),
178 options_(options),
179 cumulative_timings_("JIT timings"),
180 memory_use_("Memory used for compilation", 16),
181 lock_("JIT memory use lock") {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800182
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100183Jit* Jit::Create(JitCodeCache* code_cache, JitOptions* options) {
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000184 if (jit_load_ == nullptr) {
185 LOG(WARNING) << "Not creating JIT: library not loaded";
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800186 return nullptr;
187 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000188 jit_compiler_handle_ = (jit_load_)();
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000189 if (jit_compiler_handle_ == nullptr) {
190 LOG(WARNING) << "Not creating JIT: failed to allocate a compiler";
191 return nullptr;
192 }
193 std::unique_ptr<Jit> jit(new Jit(code_cache, options));
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000194
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000195 // If the code collector is enabled, check if that still holds:
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000196 // With 'perf', we want a 1-1 mapping between an address and a method.
197 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
198 // so we will just disable jit-gc if we are doing that.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000199 if (code_cache->GetGarbageCollectCode()) {
200 code_cache->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
201 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
202 }
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100203
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000204 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000205 << PrettySize(options->GetCodeCacheInitialCapacity())
206 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000207 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100208 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100209
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100210 // Notify native debugger about the classes already loaded before the creation of the jit.
211 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800212 return jit.release();
213}
214
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000215template <typename T>
216bool Jit::LoadSymbol(T* address, const char* name, std::string* error_msg) {
217 *address = reinterpret_cast<T>(dlsym(jit_library_handle_, name));
218 if (*address == nullptr) {
219 *error_msg = std::string("JIT couldn't find ") + name + std::string(" entry point");
220 return false;
221 }
222 return true;
223}
224
Nicolas Geoffraya7edd0d2018-11-07 03:18:16 +0000225bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800226 jit_library_handle_ = dlopen(
227 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
228 if (jit_library_handle_ == nullptr) {
229 std::ostringstream oss;
230 oss << "JIT could not load libart-compiler.so: " << dlerror();
231 *error_msg = oss.str();
232 return false;
233 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000234 bool all_resolved = true;
235 all_resolved = all_resolved && LoadSymbol(&jit_load_, "jit_load", error_msg);
236 all_resolved = all_resolved && LoadSymbol(&jit_unload_, "jit_unload", error_msg);
237 all_resolved = all_resolved && LoadSymbol(&jit_compile_method_, "jit_compile_method", error_msg);
238 all_resolved = all_resolved && LoadSymbol(&jit_types_loaded_, "jit_types_loaded", error_msg);
239 all_resolved = all_resolved && LoadSymbol(&jit_update_options_, "jit_update_options", error_msg);
240 all_resolved = all_resolved &&
241 LoadSymbol(&jit_generate_debug_info_, "jit_generate_debug_info", error_msg);
242 if (!all_resolved) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800243 dlclose(jit_library_handle_);
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000244 return false;
245 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700246 return true;
247}
248
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100249bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool baseline, bool osr, bool prejit) {
Calin Juravleffc87072016-04-20 14:22:09 +0100250 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800251 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000252
Alex Light0fa17862017-10-24 13:43:05 -0700253 RuntimeCallbacks* cb = Runtime::Current()->GetRuntimeCallbacks();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100254 // Don't compile the method if it has breakpoints.
Alex Light0fa17862017-10-24 13:43:05 -0700255 if (cb->IsMethodBeingInspected(method) && !cb->IsMethodSafeToJit(method)) {
256 VLOG(jit) << "JIT not compiling " << method->PrettyMethod()
257 << " due to not being safe to jit according to runtime-callbacks. For example, there"
258 << " could be breakpoints in this method.";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700259 return false;
260 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100261
262 // Don't compile the method if we are supposed to be deoptimized.
263 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
264 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700265 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100266 return false;
267 }
268
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000269 // If we get a request to compile a proxy method, we pass the actual Java method
270 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700271 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100272 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr, prejit)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100273 return false;
274 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100275
276 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700277 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100278 << " osr=" << std::boolalpha << osr;
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000279 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, baseline, osr);
buzbee454b3b62016-04-07 14:42:47 -0700280 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100281 if (!success) {
282 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700283 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100284 << " osr=" << std::boolalpha << osr;
285 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800286 if (kIsDebugBuild) {
287 if (self->IsExceptionPending()) {
288 mirror::Throwable* exception = self->GetException();
289 LOG(FATAL) << "No pending exception expected after compiling "
290 << ArtMethod::PrettyMethod(method)
291 << ": "
292 << exception->Dump();
293 }
294 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100295 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800296}
297
Mathieu Chartier93c21ba2018-12-10 13:08:30 -0800298void Jit::WaitForWorkersToBeCreated() {
299 if (thread_pool_ != nullptr) {
300 thread_pool_->WaitForWorkersToBeCreated();
301 }
302}
303
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800304void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100305 Thread* self = Thread::Current();
306 DCHECK(Runtime::Current()->IsShuttingDown(self));
307 if (thread_pool_ != nullptr) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700308 std::unique_ptr<ThreadPool> pool;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100309 {
310 ScopedSuspendAll ssa(__FUNCTION__);
311 // Clear thread_pool_ field while the threads are suspended.
312 // A mutator in the 'AddSamples' method will check against it.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700313 pool = std::move(thread_pool_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100314 }
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700315
316 // When running sanitized, let all tasks finish to not leak. Otherwise just clear the queue.
Roland Levillain05e34f42018-05-24 13:19:05 +0000317 if (!kRunningOnMemoryTool) {
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700318 pool->StopWorkers(self);
319 pool->RemoveAllTasks(self);
320 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100321 // We could just suspend all threads, but we know those threads
322 // will finish in a short period, so it's not worth adding a suspend logic
323 // here. Besides, this is only done for shutdown.
Andreas Gampe0897e1c2017-05-16 08:36:56 -0700324 pool->Wait(self, false, false);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800325 }
326}
327
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000328void Jit::StartProfileSaver(const std::string& filename,
Calin Juravle77651c42017-03-03 18:04:02 -0800329 const std::vector<std::string>& code_paths) {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100330 if (options_->GetSaveProfilingInfo()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100331 ProfileSaver::Start(options_->GetProfileSaverOptions(), filename, code_cache_, code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100332 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000333}
334
335void Jit::StopProfileSaver() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100336 if (options_->GetSaveProfilingInfo() && ProfileSaver::IsStarted()) {
337 ProfileSaver::Stop(options_->DumpJitInfoOnShutdown());
Calin Juravle31f2c152015-10-23 17:56:15 +0100338 }
339}
340
Siva Chandra05d24152016-01-05 17:43:17 -0800341bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100342 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800343}
344
Nicolas Geoffray35122442016-03-02 12:05:30 +0000345bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
346 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
347}
348
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800349Jit::~Jit() {
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100350 DCHECK(!options_->GetSaveProfilingInfo() || !ProfileSaver::IsStarted());
351 if (options_->DumpJitInfoOnShutdown()) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700352 DumpInfo(LOG_STREAM(INFO));
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100353 Runtime::Current()->DumpDeoptimizations(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700354 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800355 DeleteThreadPool();
356 if (jit_compiler_handle_ != nullptr) {
357 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700358 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800359 }
360 if (jit_library_handle_ != nullptr) {
361 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700362 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800363 }
364}
365
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000366void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100367 if (!Runtime::Current()->UseJitCompilation()) {
368 // No need to notify if we only use the JIT to save profiles.
369 return;
370 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000371 jit::Jit* jit = Runtime::Current()->GetJit();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000372 if (jit_generate_debug_info_(jit->jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000373 DCHECK(jit->jit_types_loaded_ != nullptr);
374 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
375 }
376}
377
378void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
379 struct CollectClasses : public ClassVisitor {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100380 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700381 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000382 return true;
383 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800384 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000385 };
386
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000387 if (jit_generate_debug_info_(jit_compiler_handle_)) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000388 ScopedObjectAccess so(Thread::Current());
389
390 CollectClasses visitor;
391 linker->VisitClasses(&visitor);
392 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000393 }
394}
395
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000396extern "C" void art_quick_osr_stub(void** stack,
Evgenii Stepanov6d90fde2018-09-04 17:50:38 -0700397 size_t stack_size_in_bytes,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000398 const uint8_t* native_pc,
399 JValue* result,
400 const char* shorty,
401 Thread* self);
402
403bool Jit::MaybeDoOnStackReplacement(Thread* thread,
404 ArtMethod* method,
405 uint32_t dex_pc,
406 int32_t dex_pc_offset,
407 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000408 if (!kEnableOnStackReplacement) {
409 return false;
410 }
411
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000412 Jit* jit = Runtime::Current()->GetJit();
413 if (jit == nullptr) {
414 return false;
415 }
416
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000417 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
418 // Don't attempt to do an OSR if we are close to the stack limit. Since
419 // the interpreter frames are still on stack, OSR has the potential
420 // to stack overflow even for a simple loop.
421 // b/27094810.
422 return false;
423 }
424
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000425 // Get the actual Java method if this method is from a proxy class. The compiler
426 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700427 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000428
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000429 // Cheap check if the method has been compiled already. That's an indicator that we should
430 // osr into it.
431 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
432 return false;
433 }
434
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000435 // Fetch some data before looking up for an OSR method. We don't want thread
436 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
437 // method while we are being suspended.
David Sehr0225f8e2018-01-31 08:52:24 +0000438 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800439 const size_t number_of_vregs = accessor.RegistersSize();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000440 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700441 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000442 void** memory = nullptr;
443 size_t frame_size = 0;
444 ShadowFrame* shadow_frame = nullptr;
445 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000446
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000447 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700448 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000449 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
450 if (osr_method == nullptr) {
451 // No osr method yet, just return to the interpreter.
452 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000453 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000454
David Srbecky052f8ca2018-04-26 15:42:54 +0100455 CodeInfo code_info(osr_method);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000456
457 // Find stack map starting at the target dex_pc.
David Srbecky052f8ca2018-04-26 15:42:54 +0100458 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000459 if (!stack_map.IsValid()) {
460 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
461 // hope that the next branch has one.
462 return false;
463 }
464
Alex Light21611932017-09-26 13:07:39 -0700465 // Before allowing the jump, make sure no code is actively inspecting the method to avoid
466 // jumping from interpreter to OSR while e.g. single stepping. Note that we could selectively
467 // disable OSR when single stepping, but that's currently hard to know at this point.
468 if (Runtime::Current()->GetRuntimeCallbacks()->IsMethodBeingInspected(method)) {
Aart Bik29bdaee2016-05-18 15:44:07 -0700469 return false;
470 }
471
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000472 // We found a stack map, now fill the frame with dex register values from the interpreter's
473 // shadow frame.
David Srbeckyfd89b072018-06-03 12:00:22 +0100474 DexRegisterMap vreg_map = code_info.GetDexRegisterMapOf(stack_map);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000475
476 frame_size = osr_method->GetFrameSizeInBytes();
477
478 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
479 // stack.
480 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
481 // but that is engineering complexity not worth the effort for something like OSR.
482 memory = reinterpret_cast<void**>(malloc(frame_size));
483 CHECK(memory != nullptr);
484 memset(memory, 0, frame_size);
485
486 // Art ABI: ArtMethod is at the bottom of the stack.
487 memory[0] = method;
488
489 shadow_frame = thread->PopShadowFrame();
David Srbeckyfd89b072018-06-03 12:00:22 +0100490 if (vreg_map.empty()) {
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000491 // If we don't have a dex register map, then there are no live dex registers at
492 // this dex pc.
493 } else {
David Srbeckyfd89b072018-06-03 12:00:22 +0100494 DCHECK_EQ(vreg_map.size(), number_of_vregs);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000495 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
David Srbeckye1402122018-06-13 18:20:45 +0100496 DexRegisterLocation::Kind location = vreg_map[vreg].GetKind();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000497 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000498 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000499 continue;
500 }
501
502 if (location == DexRegisterLocation::Kind::kConstant) {
503 // We skip constants because the compiled code knows how to handle them.
504 continue;
505 }
506
David Srbecky7dc11782016-02-25 13:23:56 +0000507 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000508
509 int32_t vreg_value = shadow_frame->GetVReg(vreg);
David Srbeckye1402122018-06-13 18:20:45 +0100510 int32_t slot_offset = vreg_map[vreg].GetStackOffsetInBytes();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000511 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
512 DCHECK_GT(slot_offset, 0);
513 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
514 }
515 }
516
David Srbecky052f8ca2018-04-26 15:42:54 +0100517 native_pc = stack_map.GetNativePcOffset(kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000518 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000519 VLOG(jit) << "Jumping to "
520 << method_name
521 << "@"
522 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000523 }
524
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000525 {
526 ManagedStack fragment;
527 thread->PushManagedStackFragment(&fragment);
528 (*art_quick_osr_stub)(memory,
529 frame_size,
530 native_pc,
531 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000532 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000533 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000534
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000535 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
536 thread->DeoptimizeWithDeoptimizationException(result);
537 }
538 thread->PopManagedStackFragment(fragment);
539 }
540 free(memory);
541 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000542 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000543 return true;
544}
545
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000546void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
547 if (bytes > 4 * MB) {
548 LOG(INFO) << "Compiler allocated "
549 << PrettySize(bytes)
550 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700551 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000552 }
553 MutexLock mu(Thread::Current(), lock_);
554 memory_use_.AddValue(bytes);
555}
556
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100557class JitCompileTask final : public Task {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100558 public:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000559 enum class TaskKind {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100560 kAllocateProfile,
561 kCompile,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000562 kCompileBaseline,
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000563 kCompileOsr,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100564 kPreCompile,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100565 };
566
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000567 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind), klass_(nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100568 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000569 // For a non-bootclasspath class, add a global ref to the class to prevent class unloading
570 // until compilation is done.
571 if (method->GetDeclaringClass()->GetClassLoader() != nullptr) {
572 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
573 CHECK(klass_ != nullptr);
574 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100575 }
576
577 ~JitCompileTask() {
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000578 if (klass_ != nullptr) {
579 ScopedObjectAccess soa(Thread::Current());
580 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
581 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100582 }
583
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100584 void Run(Thread* self) override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100585 ScopedObjectAccess soa(self);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000586 switch (kind_) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100587 case TaskKind::kPreCompile:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000588 case TaskKind::kCompile:
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000589 case TaskKind::kCompileBaseline:
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000590 case TaskKind::kCompileOsr: {
591 Runtime::Current()->GetJit()->CompileMethod(
592 method_,
593 self,
Nicolas Geoffray075456e2018-12-14 08:54:21 +0000594 /* baseline= */ (kind_ == TaskKind::kCompileBaseline),
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100595 /* osr= */ (kind_ == TaskKind::kCompileOsr),
596 /* prejit= */ (kind_ == TaskKind::kPreCompile));
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000597 break;
598 }
599 case TaskKind::kAllocateProfile: {
600 if (ProfilingInfo::Create(self, method_, /* retry_allocation= */ true)) {
601 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
602 }
603 break;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100604 }
605 }
Calin Juravlea2638922016-04-29 16:44:11 +0100606 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100607 }
608
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100609 void Finalize() override {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100610 delete this;
611 }
612
613 private:
614 ArtMethod* const method_;
615 const TaskKind kind_;
616 jobject klass_;
617
618 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
619};
620
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000621class ZygoteTask final : public Task {
622 public:
623 ZygoteTask() {}
624
625 void Run(Thread* self) override {
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100626 Runtime* runtime = Runtime::Current();
627 std::string profile_file;
628 for (const std::string& option : runtime->GetImageCompilerOptions()) {
629 if (android::base::StartsWith(option, "--profile-file=")) {
630 profile_file = option.substr(strlen("--profile-file="));
631 break;
632 }
633 }
634
635 const std::vector<const DexFile*>& boot_class_path =
636 runtime->GetClassLinker()->GetBootClassPath();
637 ScopedNullHandle<mirror::ClassLoader> null_handle;
638 // We add to the queue for zygote so that we can fork processes in-between
639 // compilations.
640 runtime->GetJit()->CompileMethodsFromProfile(
641 self, boot_class_path, profile_file, null_handle, /* add_to_queue= */ true);
642 }
643
644 void Finalize() override {
645 delete this;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000646 }
647
648 private:
649 DISALLOW_COPY_AND_ASSIGN(ZygoteTask);
650};
651
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100652static std::string GetProfileFile(const std::string& dex_location) {
653 // Hardcoded assumption where the profile file is.
654 // TODO(ngeoffray): this is brittle and we would need to change change if we
655 // wanted to do more eager JITting of methods in a profile. This is
656 // currently only for system server.
657 return dex_location + ".prof";
658}
659
660class JitProfileTask final : public Task {
661 public:
662 JitProfileTask(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
663 ObjPtr<mirror::ClassLoader> class_loader) {
664 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
665 for (const auto& dex_file : dex_files) {
666 dex_files_.push_back(dex_file.get());
667 // Register the dex file so that we can guarantee it doesn't get deleted
668 // while reading it during the task.
669 class_linker->RegisterDexFile(*dex_file.get(), class_loader);
670 }
671 ScopedObjectAccess soa(Thread::Current());
672 class_loader_ = soa.Vm()->AddGlobalRef(soa.Self(), class_loader.Ptr());
673 }
674
675 void Run(Thread* self) override {
676 ScopedObjectAccess soa(self);
677 StackHandleScope<1> hs(self);
678 Handle<mirror::ClassLoader> loader = hs.NewHandle<mirror::ClassLoader>(
679 soa.Decode<mirror::ClassLoader>(class_loader_));
680 Runtime::Current()->GetJit()->CompileMethodsFromProfile(
681 self,
682 dex_files_,
683 GetProfileFile(dex_files_[0]->GetLocation()),
684 loader,
685 /* add_to_queue= */ false);
686 }
687
688 void Finalize() override {
689 delete this;
690 }
691
692 private:
693 std::vector<const DexFile*> dex_files_;
694 jobject class_loader_;
695
696 DISALLOW_COPY_AND_ASSIGN(JitProfileTask);
697};
698
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000699void Jit::CreateThreadPool() {
700 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
701 // is not null when we instrument.
702
703 // We need peers as we may report the JIT thread, e.g., in the debugger.
704 constexpr bool kJitPoolNeedsPeers = true;
705 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
706
707 thread_pool_->SetPthreadPriority(options_->GetThreadPoolPthreadPriority());
708 Start();
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000709
710 // If we're not using the default boot image location, request a JIT task to
711 // compile all methods in the boot image profile.
712 Runtime* runtime = Runtime::Current();
David Srbecky3db3d372019-04-17 18:19:17 +0100713 if (runtime->IsZygote() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000714 thread_pool_->AddTask(Thread::Current(), new ZygoteTask());
715 }
716}
717
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100718void Jit::RegisterDexFiles(const std::vector<std::unique_ptr<const DexFile>>& dex_files,
719 ObjPtr<mirror::ClassLoader> class_loader) {
720 if (dex_files.empty()) {
721 return;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000722 }
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100723 Runtime* runtime = Runtime::Current();
724 if (runtime->IsSystemServer() && runtime->IsUsingApexBootImageLocation() && UseJitCompilation()) {
725 thread_pool_->AddTask(Thread::Current(), new JitProfileTask(dex_files, class_loader));
726 }
727}
728
729void Jit::CompileMethodsFromProfile(
730 Thread* self,
731 const std::vector<const DexFile*>& dex_files,
732 const std::string& profile_file,
733 Handle<mirror::ClassLoader> class_loader,
734 bool add_to_queue) {
735
736 if (profile_file.empty()) {
737 LOG(WARNING) << "Expected a profile file in JIT zygote mode";
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000738 return;
739 }
740
741 std::string error_msg;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100742 ScopedFlock profile = LockedFile::Open(
743 profile_file.c_str(), O_RDONLY, /* block= */ false, &error_msg);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000744
745 // Return early if we're unable to obtain a lock on the profile.
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100746 if (profile.get() == nullptr) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000747 LOG(ERROR) << "Cannot lock profile: " << error_msg;
748 return;
749 }
750
751 ProfileCompilationInfo profile_info;
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100752 if (!profile_info.Load(profile->Fd())) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000753 LOG(ERROR) << "Could not load profile file";
754 return;
755 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000756 ScopedObjectAccess soa(self);
757 StackHandleScope<1> hs(self);
758 MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100759 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
760 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100761 if (LocationIsOnRuntimeModule(dex_file->GetLocation().c_str())) {
762 // The runtime module jars are already preopted.
763 continue;
764 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100765 // To speed up class lookups, generate a type lookup table for
766 // the dex file.
Nicolas Geoffrayc5e3a522019-04-30 09:47:55 +0100767 if (dex_file->GetOatDexFile() == nullptr) {
768 TypeLookupTable type_lookup_table = TypeLookupTable::Create(*dex_file);
769 type_lookup_tables_.push_back(
770 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
771 dex_file->SetOatDexFile(type_lookup_tables_.back().get());
772 }
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +0100773
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000774 std::set<dex::TypeIndex> class_types;
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000775 std::set<uint16_t> all_methods;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000776 if (!profile_info.GetClassesAndMethods(*dex_file,
777 &class_types,
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000778 &all_methods,
779 &all_methods,
780 &all_methods)) {
Nicolas Geoffrayf59bc112019-04-03 10:29:29 +0100781 // This means the profile file did not reference the dex file, which is the case
782 // if there's no classes and methods of that dex file in the profile.
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000783 continue;
784 }
785 dex_cache.Assign(class_linker->FindDexCache(self, *dex_file));
786 CHECK(dex_cache != nullptr) << "Could not find dex cache for " << dex_file->GetLocation();
Nicolas Geoffray1d077ac2019-02-27 15:53:28 +0000787
788 for (uint16_t method_idx : all_methods) {
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000789 ArtMethod* method = class_linker->ResolveMethodWithoutInvokeType(
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100790 method_idx, dex_cache, class_loader);
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000791 if (method == nullptr) {
792 self->ClearException();
793 continue;
794 }
795 if (!method->IsCompilable() || !method->IsInvokable()) {
796 continue;
797 }
798 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
799 if (class_linker->IsQuickToInterpreterBridge(entry_point) ||
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100800 class_linker->IsQuickGenericJniStub(entry_point) ||
801 class_linker->IsQuickResolutionStub(entry_point)) {
Nicolas Geoffrayb10f0282019-04-12 17:30:52 +0100802 // Special case ZygoteServer class so that it gets compiled before the
803 // zygote enters it. This avoids needing to do OSR during app startup.
804 // TODO: have a profile instead.
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100805 if (!add_to_queue || method->GetDeclaringClass()->DescriptorEquals(
Nicolas Geoffrayb10f0282019-04-12 17:30:52 +0100806 "Lcom/android/internal/os/ZygoteServer;")) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100807 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ true);
Nicolas Geoffrayb10f0282019-04-12 17:30:52 +0100808 } else {
809 thread_pool_->AddTask(self,
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100810 new JitCompileTask(method, JitCompileTask::TaskKind::kPreCompile));
Nicolas Geoffrayb10f0282019-04-12 17:30:52 +0100811 }
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000812 }
813 }
814 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000815}
816
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100817static bool IgnoreSamplesForMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
818 if (method->IsClassInitializer() || !method->IsCompilable()) {
819 // We do not want to compile such methods.
820 return true;
821 }
822 if (method->IsNative()) {
823 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100824 if (klass == GetClassRoot<mirror::MethodHandle>() ||
825 klass == GetClassRoot<mirror::VarHandle>()) {
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100826 // MethodHandle and VarHandle invocation methods are required to throw an
827 // UnsupportedOperationException if invoked reflectively. We achieve this by having native
828 // implementations that arise the exception. We need to disable JIT compilation of these JNI
829 // methods as it can lead to transitioning between JIT compiled JNI stubs and generic JNI
830 // stubs. Since these stubs have different stack representations we can then crash in stack
831 // walking (b/78151261).
832 return true;
833 }
834 }
835 return false;
836}
837
David Srbeckye3fc2d12018-11-30 13:41:14 +0000838bool Jit::MaybeCompileMethod(Thread* self,
839 ArtMethod* method,
840 uint32_t old_count,
841 uint32_t new_count,
842 bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100843 if (thread_pool_ == nullptr) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000844 // Should only see this when shutting down, starting up, or in safe mode.
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +0000845 DCHECK(Runtime::Current()->IsShuttingDown(self) ||
846 !Runtime::Current()->IsFinishedStarting() ||
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000847 Runtime::Current()->IsSafeMode());
David Srbeckye3fc2d12018-11-30 13:41:14 +0000848 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100849 }
Orion Hodson52f5a1f2018-05-02 11:05:44 +0100850 if (IgnoreSamplesForMethod(method)) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000851 return false;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100852 }
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100853 if (HotMethodThreshold() == 0) {
David Srbeckyf4886df2017-12-11 16:06:29 +0000854 // Tests might request JIT on first use (compiled synchronously in the interpreter).
David Srbeckye3fc2d12018-11-30 13:41:14 +0000855 return false;
David Srbeckyf4886df2017-12-11 16:06:29 +0000856 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100857 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffray47b95802018-05-16 15:42:17 +0100858 DCHECK_GT(WarmMethodThreshold(), 0);
859 DCHECK_GT(HotMethodThreshold(), WarmMethodThreshold());
860 DCHECK_GT(OSRMethodThreshold(), HotMethodThreshold());
861 DCHECK_GE(PriorityThreadWeight(), 1);
862 DCHECK_LE(PriorityThreadWeight(), HotMethodThreshold());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100863
David Srbeckye3fc2d12018-11-30 13:41:14 +0000864 if (old_count < WarmMethodThreshold() && new_count >= WarmMethodThreshold()) {
865 // Note: Native method have no "warm" state or profiling info.
866 if (!method->IsNative() && method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700867 bool success = ProfilingInfo::Create(self, method, /* retry_allocation= */ false);
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000868 if (success) {
869 VLOG(jit) << "Start profiling " << method->PrettyMethod();
870 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100871
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000872 if (thread_pool_ == nullptr) {
873 // Calling ProfilingInfo::Create might put us in a suspended state, which could
874 // lead to the thread pool being deleted when we are shutting down.
875 DCHECK(Runtime::Current()->IsShuttingDown(self));
David Srbeckye3fc2d12018-11-30 13:41:14 +0000876 return false;
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000877 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100878
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000879 if (!success) {
880 // We failed allocating. Instead of doing the collection on the Java thread, we push
881 // an allocation to a compiler thread, that will do the collection.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000882 thread_pool_->AddTask(
883 self, new JitCompileTask(method, JitCompileTask::TaskKind::kAllocateProfile));
Nicolas Geoffray941c6ec2017-06-09 11:53:23 +0000884 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100885 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000886 }
887 if (UseJitCompilation()) {
David Srbeckyc45b5892019-04-24 10:32:04 +0100888 if (old_count == 0 &&
889 method->IsNative() &&
890 Runtime::Current()->IsUsingApexBootImageLocation()) {
891 // jitzygote: Compile JNI stub on first use to avoid the expensive generic stub.
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100892 CompileMethod(method, self, /* baseline= */ false, /* osr= */ false, /* prejit= */ false);
David Srbeckyc45b5892019-04-24 10:32:04 +0100893 return true;
894 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000895 if (old_count < HotMethodThreshold() && new_count >= HotMethodThreshold()) {
896 if (!code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Calin Juravleffc87072016-04-20 14:22:09 +0100897 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000898 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompile));
Calin Juravleffc87072016-04-20 14:22:09 +0100899 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000900 }
901 if (old_count < OSRMethodThreshold() && new_count >= OSRMethodThreshold()) {
Calin Juravleffc87072016-04-20 14:22:09 +0100902 if (!with_backedges) {
David Srbeckye3fc2d12018-11-30 13:41:14 +0000903 return false;
Calin Juravleffc87072016-04-20 14:22:09 +0100904 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000905 DCHECK(!method->IsNative()); // No back edges reported for native methods.
David Srbeckye3fc2d12018-11-30 13:41:14 +0000906 if (!code_cache_->IsOsrCompiled(method)) {
Calin Juravleffc87072016-04-20 14:22:09 +0100907 DCHECK(thread_pool_ != nullptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000908 thread_pool_->AddTask(
909 self, new JitCompileTask(method, JitCompileTask::TaskKind::kCompileOsr));
Calin Juravleffc87072016-04-20 14:22:09 +0100910 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100911 }
912 }
David Srbeckye3fc2d12018-11-30 13:41:14 +0000913 return true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100914}
915
Alex Light59b950f2018-10-08 10:43:06 -0700916class ScopedSetRuntimeThread {
917 public:
918 explicit ScopedSetRuntimeThread(Thread* self)
919 : self_(self), was_runtime_thread_(self_->IsRuntimeThread()) {
920 self_->SetIsRuntimeThread(true);
921 }
922
923 ~ScopedSetRuntimeThread() {
924 self_->SetIsRuntimeThread(was_runtime_thread_);
925 }
926
927 private:
928 Thread* self_;
929 bool was_runtime_thread_;
930};
931
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100932void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +0100933 Runtime* runtime = Runtime::Current();
934 if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000935 ArtMethod* np_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000936 if (np_method->IsCompilable()) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100937 JitCompileTask compile_task(method, JitCompileTask::TaskKind::kPreCompile);
Alex Light59b950f2018-10-08 10:43:06 -0700938 // Fake being in a runtime thread so that class-load behavior will be the same as normal jit.
939 ScopedSetRuntimeThread ssrt(thread);
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000940 compile_task.Run(thread);
941 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100942 return;
943 }
944
Andreas Gampe542451c2016-07-26 09:02:02 -0700945 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100946 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
Alex Light2d441b12018-06-08 15:33:21 -0700947 // instead of interpreting the method. We don't update it for instrumentation as the entrypoint
948 // must remain the instrumentation entrypoint.
949 if ((profiling_info != nullptr) &&
950 (profiling_info->GetSavedEntryPoint() != nullptr) &&
951 (method->GetEntryPointFromQuickCompiledCode() != GetQuickInstrumentationEntryPoint())) {
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100952 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
953 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100954 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700955 AddSamples(thread, method, 1, /* with_backedges= */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100956 }
957}
958
Mathieu Chartieref41db72016-10-25 15:08:01 -0700959void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100960 ArtMethod* caller,
961 uint32_t dex_pc,
962 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700963 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100964 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -0700965 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100966 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100967 info->AddInvokeInfo(dex_pc, this_object->GetClass());
968 }
969}
970
971void Jit::WaitForCompilationToFinish(Thread* self) {
972 if (thread_pool_ != nullptr) {
973 thread_pool_->Wait(self, false, false);
974 }
975}
976
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000977void Jit::Stop() {
978 Thread* self = Thread::Current();
979 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
980 WaitForCompilationToFinish(self);
981 GetThreadPool()->StopWorkers(self);
982 WaitForCompilationToFinish(self);
983}
984
985void Jit::Start() {
David Srbeckyd25eb2c2018-07-19 12:17:04 +0000986 GetThreadPool()->StartWorkers(Thread::Current());
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000987}
988
Andreas Gampef149b3f2016-11-16 14:58:24 -0800989ScopedJitSuspend::ScopedJitSuspend() {
990 jit::Jit* jit = Runtime::Current()->GetJit();
991 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
992 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000993 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800994 }
995}
996
997ScopedJitSuspend::~ScopedJitSuspend() {
998 if (was_on_) {
999 DCHECK(Runtime::Current()->GetJit() != nullptr);
1000 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +00001001 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -08001002 }
1003}
1004
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001005void Jit::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001006 if (is_zygote) {
Nicolas Geoffray953da542019-03-04 10:09:11 +00001007 // Remove potential tasks that have been inherited from the zygote. Child zygotes
1008 // currently don't need the whole boot image compiled (ie webview_zygote).
1009 thread_pool_->RemoveAllTasks(Thread::Current());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001010 // Don't transition if this is for a child zygote.
1011 return;
1012 }
1013 if (Runtime::Current()->IsSafeMode()) {
1014 // Delete the thread pool, we are not going to JIT.
1015 thread_pool_.reset(nullptr);
1016 return;
1017 }
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001018 // At this point, the compiler options have been adjusted to the particular configuration
1019 // of the forked child. Parse them again.
1020 jit_update_options_(jit_compiler_handle_);
1021
1022 // Adjust the status of code cache collection: the status from zygote was to not collect.
1023 code_cache_->SetGarbageCollectCode(!jit_generate_debug_info_(jit_compiler_handle_) &&
1024 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled());
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001025
1026 if (thread_pool_ != nullptr) {
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001027 if (!is_system_server) {
1028 // Remove potential tasks that have been inherited from the zygote.
1029 // We keep the queue for system server, as not having those methods compiled
1030 // impacts app startup.
1031 thread_pool_->RemoveAllTasks(Thread::Current());
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +01001032 } else if (Runtime::Current()->IsUsingApexBootImageLocation() && UseJitCompilation()) {
1033 // Disable garbage collection: we don't want it to delete methods we're compiling
1034 // through boot and system server profiles.
1035 // TODO(ngeoffray): Fix this so we still collect deoptimized and unused code.
1036 code_cache_->SetGarbageCollectCode(false);
Nicolas Geoffray0d54cfb2019-05-03 09:13:52 +01001037 }
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001038
1039 // Resume JIT compilation.
1040 thread_pool_->CreateThreads();
1041 }
1042}
1043
1044void Jit::PreZygoteFork() {
1045 if (thread_pool_ == nullptr) {
1046 return;
1047 }
1048 thread_pool_->DeleteThreads();
1049}
1050
1051void Jit::PostZygoteFork() {
1052 if (thread_pool_ == nullptr) {
1053 return;
1054 }
1055 thread_pool_->CreateThreads();
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00001056}
1057
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001058} // namespace jit
1059} // namespace art