blob: b32b272a313d1aac851952f50a88442aeb7d3a29 [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"
Andreas Gampe2a5c4682015-08-14 08:22:54 -070023#include "debugger.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080024#include "entrypoints/runtime_asm_entrypoints.h"
25#include "interpreter/interpreter.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070026#include "java_vm_ext.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080027#include "jit_code_cache.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010028#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000029#include "oat_quick_method_header.h"
Calin Juravle33083d62017-01-18 15:29:12 -080030#include "profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000031#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032#include "runtime.h"
33#include "runtime_options.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000034#include "stack_map.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010035#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "utils.h"
37
38namespace art {
39namespace jit {
40
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000041static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010042// At what priority to schedule jit threads. 9 is the lowest foreground priority on device.
43static constexpr int kJitPoolThreadPthreadPriority = 9;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000044
Mathieu Chartier72918ea2016-03-24 11:07:06 -070045// JIT compiler
46void* Jit::jit_library_handle_= nullptr;
47void* Jit::jit_compiler_handle_ = nullptr;
48void* (*Jit::jit_load_)(bool*) = nullptr;
49void (*Jit::jit_unload_)(void*) = nullptr;
50bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool) = nullptr;
51void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
52bool Jit::generate_debug_info_ = false;
53
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080054JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080055 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010056 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000057
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000058 jit_options->code_cache_initial_capacity_ =
59 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
60 jit_options->code_cache_max_capacity_ =
61 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070062 jit_options->dump_info_on_shutdown_ =
63 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010064 jit_options->profile_saver_options_ =
65 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000066
67 jit_options->compile_threshold_ = options.GetOrDefault(RuntimeArgumentMap::JITCompileThreshold);
68 if (jit_options->compile_threshold_ > std::numeric_limits<uint16_t>::max()) {
69 LOG(FATAL) << "Method compilation threshold is above its internal limit.";
70 }
71
72 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
73 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
74 if (jit_options->warmup_threshold_ > std::numeric_limits<uint16_t>::max()) {
75 LOG(FATAL) << "Method warmup threshold is above its internal limit.";
76 }
77 } else {
78 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
79 }
80
81 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
82 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
83 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
84 LOG(FATAL) << "Method on stack replacement threshold is above its internal limit.";
85 }
86 } else {
87 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
88 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
89 jit_options->osr_threshold_ = std::numeric_limits<uint16_t>::max();
90 }
91 }
92
Calin Juravleb2771b42016-04-07 17:09:25 +010093 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
94 jit_options->priority_thread_weight_ =
95 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
96 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
97 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
98 } else if (jit_options->priority_thread_weight_ == 0) {
99 LOG(FATAL) << "Priority thread weight cannot be 0.";
100 }
101 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100102 jit_options->priority_thread_weight_ = std::max(
103 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
104 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100105 }
106
Calin Juravle155ff3d2016-04-27 14:14:58 +0100107 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100108 jit_options->invoke_transition_weight_ =
109 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100110 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
111 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
112 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100113 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100114 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100115 } else {
116 jit_options->invoke_transition_weight_ = std::max(
117 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800118 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100119 }
120
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800121 return jit_options;
122}
123
Calin Juravleb2771b42016-04-07 17:09:25 +0100124bool Jit::ShouldUsePriorityThreadWeight() {
Calin Juravle97cbc922016-04-15 16:16:35 +0100125 return Runtime::Current()->InJankPerceptibleProcessState()
126 && Thread::Current()->IsJitSensitiveThread();
Calin Juravleb2771b42016-04-07 17:09:25 +0100127}
128
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700129void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000130 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700131 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000132 MutexLock mu(Thread::Current(), lock_);
133 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700134}
135
Calin Juravleb8e69992016-03-09 15:37:48 +0000136void Jit::DumpForSigQuit(std::ostream& os) {
137 DumpInfo(os);
138 ProfileSaver::DumpInstanceInfo(os);
139}
140
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700141void Jit::AddTimingLogger(const TimingLogger& logger) {
142 cumulative_timings_.AddLogger(logger);
143}
144
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700145Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000146 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000147 memory_use_("Memory used for compilation", 16),
148 lock_("JIT memory use lock"),
Andreas Gampe4471e4f2017-01-30 16:40:49 +0000149 use_jit_compilation_(true),
150 hot_method_threshold_(0),
151 warm_method_threshold_(0),
152 osr_method_threshold_(0),
153 priority_thread_weight_(0),
154 invoke_transition_weight_(0) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800155
156Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100157 DCHECK(options->UseJitCompilation() || options->GetProfileSaverOptions().IsEnabled());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800158 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700159 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700160 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800161 return nullptr;
162 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000163 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000164 options->GetCodeCacheInitialCapacity(),
165 options->GetCodeCacheMaxCapacity(),
166 jit->generate_debug_info_,
167 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800168 if (jit->GetCodeCache() == nullptr) {
169 return nullptr;
170 }
Calin Juravleffc87072016-04-20 14:22:09 +0100171 jit->use_jit_compilation_ = options->UseJitCompilation();
Calin Juravle138dbff2016-06-28 19:36:58 +0100172 jit->profile_saver_options_ = options->GetProfileSaverOptions();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000173 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000174 << PrettySize(options->GetCodeCacheInitialCapacity())
175 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000176 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100177 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100178
179
180 jit->hot_method_threshold_ = options->GetCompileThreshold();
181 jit->warm_method_threshold_ = options->GetWarmupThreshold();
182 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100183 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Calin Juravle155ff3d2016-04-27 14:14:58 +0100184 jit->invoke_transition_weight_ = options->GetInvokeTransitionWeight();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100185
186 jit->CreateThreadPool();
187
188 // Notify native debugger about the classes already loaded before the creation of the jit.
189 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800190 return jit.release();
191}
192
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700193bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800194 jit_library_handle_ = dlopen(
195 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
196 if (jit_library_handle_ == nullptr) {
197 std::ostringstream oss;
198 oss << "JIT could not load libart-compiler.so: " << dlerror();
199 *error_msg = oss.str();
200 return false;
201 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000202 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800203 if (jit_load_ == nullptr) {
204 dlclose(jit_library_handle_);
205 *error_msg = "JIT couldn't find jit_load entry point";
206 return false;
207 }
208 jit_unload_ = reinterpret_cast<void (*)(void*)>(
209 dlsym(jit_library_handle_, "jit_unload"));
210 if (jit_unload_ == nullptr) {
211 dlclose(jit_library_handle_);
212 *error_msg = "JIT couldn't find jit_unload entry point";
213 return false;
214 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000215 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800216 dlsym(jit_library_handle_, "jit_compile_method"));
217 if (jit_compile_method_ == nullptr) {
218 dlclose(jit_library_handle_);
219 *error_msg = "JIT couldn't find jit_compile_method entry point";
220 return false;
221 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000222 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
223 dlsym(jit_library_handle_, "jit_types_loaded"));
224 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000225 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000226 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000227 return false;
228 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700229 return true;
230}
231
232bool Jit::LoadCompiler(std::string* error_msg) {
233 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
234 return false;
235 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000236 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800237 VLOG(jit) << "Calling JitLoad interpreter_only="
238 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000239 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240 if (jit_compiler_handle_ == nullptr) {
241 dlclose(jit_library_handle_);
242 *error_msg = "JIT couldn't load compiler";
243 return false;
244 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000245 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800246 return true;
247}
248
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000249bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
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
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100253 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700254 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700255 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to breakpoint";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700256 return false;
257 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100258
259 // Don't compile the method if we are supposed to be deoptimized.
260 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
261 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700262 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100263 return false;
264 }
265
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000266 // If we get a request to compile a proxy method, we pass the actual Java method
267 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700268 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000269 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270 return false;
271 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100272
273 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700274 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100275 << " osr=" << std::boolalpha << osr;
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000276 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700277 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100278 if (!success) {
279 VLOG(jit) << "Failed to compile method "
David Sehr709b0702016-10-13 09:12:37 -0700280 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100281 << " osr=" << std::boolalpha << osr;
282 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800283 if (kIsDebugBuild) {
284 if (self->IsExceptionPending()) {
285 mirror::Throwable* exception = self->GetException();
286 LOG(FATAL) << "No pending exception expected after compiling "
287 << ArtMethod::PrettyMethod(method)
288 << ": "
289 << exception->Dump();
290 }
291 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100292 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800293}
294
295void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100296 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
297 // is not null when we instrument.
Andreas Gampe4471e4f2017-01-30 16:40:49 +0000298
299 // We need peers as we may report the JIT thread, e.g., in the debugger.
300 constexpr bool kJitPoolNeedsPeers = true;
301 thread_pool_.reset(new ThreadPool("Jit thread pool", 1, kJitPoolNeedsPeers));
302
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100303 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000304 Start();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800305}
306
307void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100308 Thread* self = Thread::Current();
309 DCHECK(Runtime::Current()->IsShuttingDown(self));
310 if (thread_pool_ != nullptr) {
311 ThreadPool* cache = nullptr;
312 {
313 ScopedSuspendAll ssa(__FUNCTION__);
314 // Clear thread_pool_ field while the threads are suspended.
315 // A mutator in the 'AddSamples' method will check against it.
316 cache = thread_pool_.release();
317 }
318 cache->StopWorkers(self);
319 cache->RemoveAllTasks(self);
320 // We could just suspend all threads, but we know those threads
321 // will finish in a short period, so it's not worth adding a suspend logic
322 // here. Besides, this is only done for shutdown.
323 cache->Wait(self, false, false);
324 delete cache;
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) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100330 if (profile_saver_options_.IsEnabled()) {
331 ProfileSaver::Start(profile_saver_options_,
332 filename,
333 code_cache_.get(),
Calin Juravle77651c42017-03-03 18:04:02 -0800334 code_paths);
Calin Juravle31f2c152015-10-23 17:56:15 +0100335 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000336}
337
338void Jit::StopProfileSaver() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100339 if (profile_saver_options_.IsEnabled() && ProfileSaver::IsStarted()) {
Calin Juravleb8e69992016-03-09 15:37:48 +0000340 ProfileSaver::Stop(dump_info_on_shutdown_);
Calin Juravle31f2c152015-10-23 17:56:15 +0100341 }
342}
343
Siva Chandra05d24152016-01-05 17:43:17 -0800344bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100345 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800346}
347
Nicolas Geoffray35122442016-03-02 12:05:30 +0000348bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
349 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
350}
351
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800352Jit::~Jit() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100353 DCHECK(!profile_saver_options_.IsEnabled() || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700354 if (dump_info_on_shutdown_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700355 DumpInfo(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700356 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800357 DeleteThreadPool();
358 if (jit_compiler_handle_ != nullptr) {
359 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700360 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800361 }
362 if (jit_library_handle_ != nullptr) {
363 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700364 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800365 }
366}
367
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000368void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100369 if (!Runtime::Current()->UseJitCompilation()) {
370 // No need to notify if we only use the JIT to save profiles.
371 return;
372 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000373 jit::Jit* jit = Runtime::Current()->GetJit();
Calin Juravleffc87072016-04-20 14:22:09 +0100374 if (jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000375 DCHECK(jit->jit_types_loaded_ != nullptr);
376 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
377 }
378}
379
380void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
381 struct CollectClasses : public ClassVisitor {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700382 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
383 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000384 return true;
385 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800386 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000387 };
388
389 if (generate_debug_info_) {
390 ScopedObjectAccess so(Thread::Current());
391
392 CollectClasses visitor;
393 linker->VisitClasses(&visitor);
394 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000395 }
396}
397
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000398extern "C" void art_quick_osr_stub(void** stack,
399 uint32_t stack_size_in_bytes,
400 const uint8_t* native_pc,
401 JValue* result,
402 const char* shorty,
403 Thread* self);
404
405bool Jit::MaybeDoOnStackReplacement(Thread* thread,
406 ArtMethod* method,
407 uint32_t dex_pc,
408 int32_t dex_pc_offset,
409 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000410 if (!kEnableOnStackReplacement) {
411 return false;
412 }
413
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000414 Jit* jit = Runtime::Current()->GetJit();
415 if (jit == nullptr) {
416 return false;
417 }
418
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000419 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
420 // Don't attempt to do an OSR if we are close to the stack limit. Since
421 // the interpreter frames are still on stack, OSR has the potential
422 // to stack overflow even for a simple loop.
423 // b/27094810.
424 return false;
425 }
426
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000427 // Get the actual Java method if this method is from a proxy class. The compiler
428 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700429 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000430
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000431 // Cheap check if the method has been compiled already. That's an indicator that we should
432 // osr into it.
433 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
434 return false;
435 }
436
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000437 // Fetch some data before looking up for an OSR method. We don't want thread
438 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
439 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000440 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000441 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700442 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000443 void** memory = nullptr;
444 size_t frame_size = 0;
445 ShadowFrame* shadow_frame = nullptr;
446 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000447
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000448 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700449 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000450 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
451 if (osr_method == nullptr) {
452 // No osr method yet, just return to the interpreter.
453 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000454 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000455
456 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000457 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000458
459 // Find stack map starting at the target dex_pc.
460 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
461 if (!stack_map.IsValid()) {
462 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
463 // hope that the next branch has one.
464 return false;
465 }
466
Aart Bik29bdaee2016-05-18 15:44:07 -0700467 // Before allowing the jump, make sure the debugger is not active to avoid jumping from
468 // interpreter to OSR while e.g. single stepping. Note that we could selectively disable
469 // OSR when single stepping, but that's currently hard to know at this point.
470 if (Dbg::IsDebuggerActive()) {
471 return false;
472 }
473
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000474 // We found a stack map, now fill the frame with dex register values from the interpreter's
475 // shadow frame.
476 DexRegisterMap vreg_map =
477 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
478
479 frame_size = osr_method->GetFrameSizeInBytes();
480
481 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
482 // stack.
483 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
484 // but that is engineering complexity not worth the effort for something like OSR.
485 memory = reinterpret_cast<void**>(malloc(frame_size));
486 CHECK(memory != nullptr);
487 memset(memory, 0, frame_size);
488
489 // Art ABI: ArtMethod is at the bottom of the stack.
490 memory[0] = method;
491
492 shadow_frame = thread->PopShadowFrame();
493 if (!vreg_map.IsValid()) {
494 // If we don't have a dex register map, then there are no live dex registers at
495 // this dex pc.
496 } else {
497 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
498 DexRegisterLocation::Kind location =
499 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
500 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000501 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000502 continue;
503 }
504
505 if (location == DexRegisterLocation::Kind::kConstant) {
506 // We skip constants because the compiled code knows how to handle them.
507 continue;
508 }
509
David Srbecky7dc11782016-02-25 13:23:56 +0000510 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000511
512 int32_t vreg_value = shadow_frame->GetVReg(vreg);
513 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
514 number_of_vregs,
515 code_info,
516 encoding);
517 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
518 DCHECK_GT(slot_offset, 0);
519 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
520 }
521 }
522
Mathieu Chartier575d3e62017-02-06 11:00:40 -0800523 native_pc = stack_map.GetNativePcOffset(encoding.stack_map.encoding, kRuntimeISA) +
David Srbecky09ed0982016-02-12 21:58:43 +0000524 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000525 VLOG(jit) << "Jumping to "
526 << method_name
527 << "@"
528 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000529 }
530
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000531 {
532 ManagedStack fragment;
533 thread->PushManagedStackFragment(&fragment);
534 (*art_quick_osr_stub)(memory,
535 frame_size,
536 native_pc,
537 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000538 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000539 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000540
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000541 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
542 thread->DeoptimizeWithDeoptimizationException(result);
543 }
544 thread->PopManagedStackFragment(fragment);
545 }
546 free(memory);
547 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000548 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000549 return true;
550}
551
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000552void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
553 if (bytes > 4 * MB) {
554 LOG(INFO) << "Compiler allocated "
555 << PrettySize(bytes)
556 << " to compile "
David Sehr709b0702016-10-13 09:12:37 -0700557 << ArtMethod::PrettyMethod(method);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000558 }
559 MutexLock mu(Thread::Current(), lock_);
560 memory_use_.AddValue(bytes);
561}
562
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100563class JitCompileTask FINAL : public Task {
564 public:
565 enum TaskKind {
566 kAllocateProfile,
567 kCompile,
568 kCompileOsr
569 };
570
571 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
572 ScopedObjectAccess soa(Thread::Current());
573 // Add a global ref to the class to prevent class unloading until compilation is done.
574 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
575 CHECK(klass_ != nullptr);
576 }
577
578 ~JitCompileTask() {
579 ScopedObjectAccess soa(Thread::Current());
580 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
581 }
582
583 void Run(Thread* self) OVERRIDE {
584 ScopedObjectAccess soa(self);
585 if (kind_ == kCompile) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100586 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100587 } else if (kind_ == kCompileOsr) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100588 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100589 } else {
590 DCHECK(kind_ == kAllocateProfile);
591 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
David Sehr709b0702016-10-13 09:12:37 -0700592 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100593 }
594 }
Calin Juravlea2638922016-04-29 16:44:11 +0100595 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100596 }
597
598 void Finalize() OVERRIDE {
599 delete this;
600 }
601
602 private:
603 ArtMethod* const method_;
604 const TaskKind kind_;
605 jobject klass_;
606
607 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
608};
609
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100610void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100611 if (thread_pool_ == nullptr) {
612 // Should only see this when shutting down.
613 DCHECK(Runtime::Current()->IsShuttingDown(self));
614 return;
615 }
616
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100617 if (method->IsClassInitializer() || method->IsNative() || !method->IsCompilable()) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100618 // We do not want to compile such methods.
619 return;
620 }
621 DCHECK(thread_pool_ != nullptr);
622 DCHECK_GT(warm_method_threshold_, 0);
623 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
624 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
625 DCHECK_GE(priority_thread_weight_, 1);
626 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
627
628 int32_t starting_count = method->GetCounter();
629 if (Jit::ShouldUsePriorityThreadWeight()) {
630 count *= priority_thread_weight_;
631 }
632 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
633 if (starting_count < warm_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100634 if ((new_count >= warm_method_threshold_) &&
Andreas Gampe542451c2016-07-26 09:02:02 -0700635 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100636 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
637 if (success) {
David Sehr709b0702016-10-13 09:12:37 -0700638 VLOG(jit) << "Start profiling " << method->PrettyMethod();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100639 }
640
641 if (thread_pool_ == nullptr) {
642 // Calling ProfilingInfo::Create might put us in a suspended state, which could
643 // lead to the thread pool being deleted when we are shutting down.
644 DCHECK(Runtime::Current()->IsShuttingDown(self));
645 return;
646 }
647
648 if (!success) {
649 // We failed allocating. Instead of doing the collection on the Java thread, we push
650 // an allocation to a compiler thread, that will do the collection.
651 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
652 }
653 }
654 // Avoid jumping more than one state at a time.
655 new_count = std::min(new_count, hot_method_threshold_ - 1);
Calin Juravleffc87072016-04-20 14:22:09 +0100656 } else if (use_jit_compilation_) {
657 if (starting_count < hot_method_threshold_) {
658 if ((new_count >= hot_method_threshold_) &&
659 !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
660 DCHECK(thread_pool_ != nullptr);
661 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
662 }
663 // Avoid jumping more than one state at a time.
664 new_count = std::min(new_count, osr_method_threshold_ - 1);
665 } else if (starting_count < osr_method_threshold_) {
666 if (!with_backedges) {
667 // If the samples don't contain any back edge, we don't increment the hotness.
668 return;
669 }
670 if ((new_count >= osr_method_threshold_) && !code_cache_->IsOsrCompiled(method)) {
671 DCHECK(thread_pool_ != nullptr);
672 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
673 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100674 }
675 }
676 // Update hotness counter
677 method->SetCounter(new_count);
678}
679
680void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +0100681 Runtime* runtime = Runtime::Current();
682 if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100683 // The compiler requires a ProfilingInfo object.
684 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
685 JitCompileTask compile_task(method, JitCompileTask::kCompile);
686 compile_task.Run(thread);
687 return;
688 }
689
Andreas Gampe542451c2016-07-26 09:02:02 -0700690 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100691 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
692 // instead of interpreting the method.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100693 if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
694 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
695 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100696 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100697 AddSamples(thread, method, 1, /* with_backedges */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100698 }
699}
700
Mathieu Chartieref41db72016-10-25 15:08:01 -0700701void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100702 ArtMethod* caller,
703 uint32_t dex_pc,
704 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700705 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100706 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -0700707 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100708 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100709 info->AddInvokeInfo(dex_pc, this_object->GetClass());
710 }
711}
712
713void Jit::WaitForCompilationToFinish(Thread* self) {
714 if (thread_pool_ != nullptr) {
715 thread_pool_->Wait(self, false, false);
716 }
717}
718
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000719void Jit::Stop() {
720 Thread* self = Thread::Current();
721 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
722 WaitForCompilationToFinish(self);
723 GetThreadPool()->StopWorkers(self);
724 WaitForCompilationToFinish(self);
725}
726
727void Jit::Start() {
728 GetThreadPool()->StartWorkers(Thread::Current());
729}
730
Andreas Gampef149b3f2016-11-16 14:58:24 -0800731ScopedJitSuspend::ScopedJitSuspend() {
732 jit::Jit* jit = Runtime::Current()->GetJit();
733 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
734 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000735 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800736 }
737}
738
739ScopedJitSuspend::~ScopedJitSuspend() {
740 if (was_on_) {
741 DCHECK(Runtime::Current()->GetJit() != nullptr);
742 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000743 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800744 }
745}
746
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800747} // namespace jit
748} // namespace art