blob: cfe6cd1856b99f909ce680412cf6558a03ae2f4f [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 Gampe2a5c4682015-08-14 08:22:54 -070022#include "debugger.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080023#include "entrypoints/runtime_asm_entrypoints.h"
24#include "interpreter/interpreter.h"
25#include "jit_code_cache.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000027#include "oat_quick_method_header.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010028#include "offline_profiling_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000029#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080030#include "runtime.h"
31#include "runtime_options.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000032#include "stack_map.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010033#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "utils.h"
35
36namespace art {
37namespace jit {
38
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000039static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010040// At what priority to schedule jit threads. 9 is the lowest foreground priority on device.
41static constexpr int kJitPoolThreadPthreadPriority = 9;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000042
Mathieu Chartier72918ea2016-03-24 11:07:06 -070043// JIT compiler
44void* Jit::jit_library_handle_= nullptr;
45void* Jit::jit_compiler_handle_ = nullptr;
46void* (*Jit::jit_load_)(bool*) = nullptr;
47void (*Jit::jit_unload_)(void*) = nullptr;
48bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool) = nullptr;
49void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
50bool Jit::generate_debug_info_ = false;
51
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080052JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080053 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010054 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000055
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000056 jit_options->code_cache_initial_capacity_ =
57 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
58 jit_options->code_cache_max_capacity_ =
59 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070060 jit_options->dump_info_on_shutdown_ =
61 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010062 jit_options->profile_saver_options_ =
63 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000064
65 jit_options->compile_threshold_ = options.GetOrDefault(RuntimeArgumentMap::JITCompileThreshold);
66 if (jit_options->compile_threshold_ > std::numeric_limits<uint16_t>::max()) {
67 LOG(FATAL) << "Method compilation threshold is above its internal limit.";
68 }
69
70 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
71 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
72 if (jit_options->warmup_threshold_ > std::numeric_limits<uint16_t>::max()) {
73 LOG(FATAL) << "Method warmup threshold is above its internal limit.";
74 }
75 } else {
76 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
77 }
78
79 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
80 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
81 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
82 LOG(FATAL) << "Method on stack replacement threshold is above its internal limit.";
83 }
84 } else {
85 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
86 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
87 jit_options->osr_threshold_ = std::numeric_limits<uint16_t>::max();
88 }
89 }
90
Calin Juravleb2771b42016-04-07 17:09:25 +010091 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
92 jit_options->priority_thread_weight_ =
93 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
94 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
95 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
96 } else if (jit_options->priority_thread_weight_ == 0) {
97 LOG(FATAL) << "Priority thread weight cannot be 0.";
98 }
99 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100100 jit_options->priority_thread_weight_ = std::max(
101 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
102 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100103 }
104
Calin Juravle155ff3d2016-04-27 14:14:58 +0100105 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100106 jit_options->invoke_transition_weight_ =
107 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100108 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
109 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
110 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100111 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100112 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100113 } else {
114 jit_options->invoke_transition_weight_ = std::max(
115 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
116 static_cast<size_t>(1));;
117 }
118
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800119 return jit_options;
120}
121
Calin Juravleb2771b42016-04-07 17:09:25 +0100122bool Jit::ShouldUsePriorityThreadWeight() {
Calin Juravle97cbc922016-04-15 16:16:35 +0100123 return Runtime::Current()->InJankPerceptibleProcessState()
124 && Thread::Current()->IsJitSensitiveThread();
Calin Juravleb2771b42016-04-07 17:09:25 +0100125}
126
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700127void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000128 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700129 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000130 MutexLock mu(Thread::Current(), lock_);
131 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700132}
133
Calin Juravleb8e69992016-03-09 15:37:48 +0000134void Jit::DumpForSigQuit(std::ostream& os) {
135 DumpInfo(os);
136 ProfileSaver::DumpInstanceInfo(os);
137}
138
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700139void Jit::AddTimingLogger(const TimingLogger& logger) {
140 cumulative_timings_.AddLogger(logger);
141}
142
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700143Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000144 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000145 memory_use_("Memory used for compilation", 16),
146 lock_("JIT memory use lock"),
Calin Juravle138dbff2016-06-28 19:36:58 +0100147 use_jit_compilation_(true) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800148
149Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100150 DCHECK(options->UseJitCompilation() || options->GetProfileSaverOptions().IsEnabled());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800151 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700152 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700153 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800154 return nullptr;
155 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000156 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000157 options->GetCodeCacheInitialCapacity(),
158 options->GetCodeCacheMaxCapacity(),
159 jit->generate_debug_info_,
160 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800161 if (jit->GetCodeCache() == nullptr) {
162 return nullptr;
163 }
Calin Juravleffc87072016-04-20 14:22:09 +0100164 jit->use_jit_compilation_ = options->UseJitCompilation();
Calin Juravle138dbff2016-06-28 19:36:58 +0100165 jit->profile_saver_options_ = options->GetProfileSaverOptions();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000166 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000167 << PrettySize(options->GetCodeCacheInitialCapacity())
168 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000169 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100170 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100171
172
173 jit->hot_method_threshold_ = options->GetCompileThreshold();
174 jit->warm_method_threshold_ = options->GetWarmupThreshold();
175 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100176 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Calin Juravle155ff3d2016-04-27 14:14:58 +0100177 jit->invoke_transition_weight_ = options->GetInvokeTransitionWeight();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100178
179 jit->CreateThreadPool();
180
181 // Notify native debugger about the classes already loaded before the creation of the jit.
182 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800183 return jit.release();
184}
185
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700186bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800187 jit_library_handle_ = dlopen(
188 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
189 if (jit_library_handle_ == nullptr) {
190 std::ostringstream oss;
191 oss << "JIT could not load libart-compiler.so: " << dlerror();
192 *error_msg = oss.str();
193 return false;
194 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000195 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800196 if (jit_load_ == nullptr) {
197 dlclose(jit_library_handle_);
198 *error_msg = "JIT couldn't find jit_load entry point";
199 return false;
200 }
201 jit_unload_ = reinterpret_cast<void (*)(void*)>(
202 dlsym(jit_library_handle_, "jit_unload"));
203 if (jit_unload_ == nullptr) {
204 dlclose(jit_library_handle_);
205 *error_msg = "JIT couldn't find jit_unload entry point";
206 return false;
207 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000208 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800209 dlsym(jit_library_handle_, "jit_compile_method"));
210 if (jit_compile_method_ == nullptr) {
211 dlclose(jit_library_handle_);
212 *error_msg = "JIT couldn't find jit_compile_method entry point";
213 return false;
214 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000215 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
216 dlsym(jit_library_handle_, "jit_types_loaded"));
217 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000218 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000219 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000220 return false;
221 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700222 return true;
223}
224
225bool Jit::LoadCompiler(std::string* error_msg) {
226 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
227 return false;
228 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000229 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800230 VLOG(jit) << "Calling JitLoad interpreter_only="
231 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000232 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800233 if (jit_compiler_handle_ == nullptr) {
234 dlclose(jit_library_handle_);
235 *error_msg = "JIT couldn't load compiler";
236 return false;
237 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000238 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800239 return true;
240}
241
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000242bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
Calin Juravleffc87072016-04-20 14:22:09 +0100243 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800244 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000245
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100246 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700247 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
248 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to breakpoint";
249 return false;
250 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100251
252 // Don't compile the method if we are supposed to be deoptimized.
253 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
254 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000255 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100256 return false;
257 }
258
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000259 // If we get a request to compile a proxy method, we pass the actual Java method
260 // of that proxy method, as the compiler does not expect a proxy method.
261 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(sizeof(void*));
262 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100263 return false;
264 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100265
266 VLOG(jit) << "Compiling method "
267 << PrettyMethod(method_to_compile)
268 << " osr=" << std::boolalpha << osr;
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000269 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700270 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100271 if (!success) {
272 VLOG(jit) << "Failed to compile method "
273 << PrettyMethod(method_to_compile)
274 << " osr=" << std::boolalpha << osr;
275 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800277}
278
279void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100280 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
281 // is not null when we instrument.
282 thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
283 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
284 thread_pool_->StartWorkers(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800285}
286
287void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100288 Thread* self = Thread::Current();
289 DCHECK(Runtime::Current()->IsShuttingDown(self));
290 if (thread_pool_ != nullptr) {
291 ThreadPool* cache = nullptr;
292 {
293 ScopedSuspendAll ssa(__FUNCTION__);
294 // Clear thread_pool_ field while the threads are suspended.
295 // A mutator in the 'AddSamples' method will check against it.
296 cache = thread_pool_.release();
297 }
298 cache->StopWorkers(self);
299 cache->RemoveAllTasks(self);
300 // We could just suspend all threads, but we know those threads
301 // will finish in a short period, so it's not worth adding a suspend logic
302 // here. Besides, this is only done for shutdown.
303 cache->Wait(self, false, false);
304 delete cache;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800305 }
306}
307
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000308void Jit::StartProfileSaver(const std::string& filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000309 const std::vector<std::string>& code_paths,
310 const std::string& foreign_dex_profile_path,
311 const std::string& app_dir) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100312 if (profile_saver_options_.IsEnabled()) {
313 ProfileSaver::Start(profile_saver_options_,
314 filename,
315 code_cache_.get(),
316 code_paths,
317 foreign_dex_profile_path,
318 app_dir);
Calin Juravle31f2c152015-10-23 17:56:15 +0100319 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000320}
321
322void Jit::StopProfileSaver() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100323 if (profile_saver_options_.IsEnabled() && ProfileSaver::IsStarted()) {
Calin Juravleb8e69992016-03-09 15:37:48 +0000324 ProfileSaver::Stop(dump_info_on_shutdown_);
Calin Juravle31f2c152015-10-23 17:56:15 +0100325 }
326}
327
Siva Chandra05d24152016-01-05 17:43:17 -0800328bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100329 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800330}
331
Nicolas Geoffray35122442016-03-02 12:05:30 +0000332bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
333 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
334}
335
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800336Jit::~Jit() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100337 DCHECK(!profile_saver_options_.IsEnabled() || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700338 if (dump_info_on_shutdown_) {
339 DumpInfo(LOG(INFO));
340 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800341 DeleteThreadPool();
342 if (jit_compiler_handle_ != nullptr) {
343 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700344 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800345 }
346 if (jit_library_handle_ != nullptr) {
347 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700348 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800349 }
350}
351
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000352void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100353 if (!Runtime::Current()->UseJitCompilation()) {
354 // No need to notify if we only use the JIT to save profiles.
355 return;
356 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000357 jit::Jit* jit = Runtime::Current()->GetJit();
Calin Juravleffc87072016-04-20 14:22:09 +0100358 if (jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000359 DCHECK(jit->jit_types_loaded_ != nullptr);
360 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
361 }
362}
363
364void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
365 struct CollectClasses : public ClassVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800366 bool operator()(mirror::Class* klass) override {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000367 classes_.push_back(klass);
368 return true;
369 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800370 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000371 };
372
373 if (generate_debug_info_) {
374 ScopedObjectAccess so(Thread::Current());
375
376 CollectClasses visitor;
377 linker->VisitClasses(&visitor);
378 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000379 }
380}
381
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000382extern "C" void art_quick_osr_stub(void** stack,
383 uint32_t stack_size_in_bytes,
384 const uint8_t* native_pc,
385 JValue* result,
386 const char* shorty,
387 Thread* self);
388
389bool Jit::MaybeDoOnStackReplacement(Thread* thread,
390 ArtMethod* method,
391 uint32_t dex_pc,
392 int32_t dex_pc_offset,
393 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000394 if (!kEnableOnStackReplacement) {
395 return false;
396 }
397
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000398 Jit* jit = Runtime::Current()->GetJit();
399 if (jit == nullptr) {
400 return false;
401 }
402
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000403 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
404 // Don't attempt to do an OSR if we are close to the stack limit. Since
405 // the interpreter frames are still on stack, OSR has the potential
406 // to stack overflow even for a simple loop.
407 // b/27094810.
408 return false;
409 }
410
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000411 // Get the actual Java method if this method is from a proxy class. The compiler
412 // and the JIT code cache do not expect methods from proxy classes.
413 method = method->GetInterfaceMethodIfProxy(sizeof(void*));
414
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000415 // Cheap check if the method has been compiled already. That's an indicator that we should
416 // osr into it.
417 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
418 return false;
419 }
420
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000421 // Fetch some data before looking up for an OSR method. We don't want thread
422 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
423 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000424 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000425 const char* shorty = method->GetShorty();
426 std::string method_name(VLOG_IS_ON(jit) ? PrettyMethod(method) : "");
427 void** memory = nullptr;
428 size_t frame_size = 0;
429 ShadowFrame* shadow_frame = nullptr;
430 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000431
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000432 {
433 ScopedAssertNoThreadSuspension sts(thread, "Holding OSR method");
434 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
435 if (osr_method == nullptr) {
436 // No osr method yet, just return to the interpreter.
437 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000438 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000439
440 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000441 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000442
443 // Find stack map starting at the target dex_pc.
444 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
445 if (!stack_map.IsValid()) {
446 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
447 // hope that the next branch has one.
448 return false;
449 }
450
Aart Bik29bdaee2016-05-18 15:44:07 -0700451 // Before allowing the jump, make sure the debugger is not active to avoid jumping from
452 // interpreter to OSR while e.g. single stepping. Note that we could selectively disable
453 // OSR when single stepping, but that's currently hard to know at this point.
454 if (Dbg::IsDebuggerActive()) {
455 return false;
456 }
457
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000458 // We found a stack map, now fill the frame with dex register values from the interpreter's
459 // shadow frame.
460 DexRegisterMap vreg_map =
461 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
462
463 frame_size = osr_method->GetFrameSizeInBytes();
464
465 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
466 // stack.
467 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
468 // but that is engineering complexity not worth the effort for something like OSR.
469 memory = reinterpret_cast<void**>(malloc(frame_size));
470 CHECK(memory != nullptr);
471 memset(memory, 0, frame_size);
472
473 // Art ABI: ArtMethod is at the bottom of the stack.
474 memory[0] = method;
475
476 shadow_frame = thread->PopShadowFrame();
477 if (!vreg_map.IsValid()) {
478 // If we don't have a dex register map, then there are no live dex registers at
479 // this dex pc.
480 } else {
481 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
482 DexRegisterLocation::Kind location =
483 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
484 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000485 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000486 continue;
487 }
488
489 if (location == DexRegisterLocation::Kind::kConstant) {
490 // We skip constants because the compiled code knows how to handle them.
491 continue;
492 }
493
David Srbecky7dc11782016-02-25 13:23:56 +0000494 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000495
496 int32_t vreg_value = shadow_frame->GetVReg(vreg);
497 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
498 number_of_vregs,
499 code_info,
500 encoding);
501 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
502 DCHECK_GT(slot_offset, 0);
503 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
504 }
505 }
506
David Srbecky09ed0982016-02-12 21:58:43 +0000507 native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
508 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000509 VLOG(jit) << "Jumping to "
510 << method_name
511 << "@"
512 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000513 }
514
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000515 {
516 ManagedStack fragment;
517 thread->PushManagedStackFragment(&fragment);
518 (*art_quick_osr_stub)(memory,
519 frame_size,
520 native_pc,
521 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000522 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000523 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000524
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000525 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
526 thread->DeoptimizeWithDeoptimizationException(result);
527 }
528 thread->PopManagedStackFragment(fragment);
529 }
530 free(memory);
531 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000532 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000533 return true;
534}
535
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000536void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
537 if (bytes > 4 * MB) {
538 LOG(INFO) << "Compiler allocated "
539 << PrettySize(bytes)
540 << " to compile "
541 << PrettyMethod(method);
542 }
543 MutexLock mu(Thread::Current(), lock_);
544 memory_use_.AddValue(bytes);
545}
546
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100547class JitCompileTask FINAL : public Task {
548 public:
549 enum TaskKind {
550 kAllocateProfile,
551 kCompile,
552 kCompileOsr
553 };
554
555 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
556 ScopedObjectAccess soa(Thread::Current());
557 // Add a global ref to the class to prevent class unloading until compilation is done.
558 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
559 CHECK(klass_ != nullptr);
560 }
561
562 ~JitCompileTask() {
563 ScopedObjectAccess soa(Thread::Current());
564 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
565 }
566
567 void Run(Thread* self) OVERRIDE {
568 ScopedObjectAccess soa(self);
569 if (kind_ == kCompile) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100570 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100571 } else if (kind_ == kCompileOsr) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100572 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100573 } else {
574 DCHECK(kind_ == kAllocateProfile);
575 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
576 VLOG(jit) << "Start profiling " << PrettyMethod(method_);
577 }
578 }
Calin Juravlea2638922016-04-29 16:44:11 +0100579 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100580 }
581
582 void Finalize() OVERRIDE {
583 delete this;
584 }
585
586 private:
587 ArtMethod* const method_;
588 const TaskKind kind_;
589 jobject klass_;
590
591 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
592};
593
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100594void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100595 if (thread_pool_ == nullptr) {
596 // Should only see this when shutting down.
597 DCHECK(Runtime::Current()->IsShuttingDown(self));
598 return;
599 }
600
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100601 if (method->IsClassInitializer() || method->IsNative() || !method->IsCompilable()) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100602 // We do not want to compile such methods.
603 return;
604 }
605 DCHECK(thread_pool_ != nullptr);
606 DCHECK_GT(warm_method_threshold_, 0);
607 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
608 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
609 DCHECK_GE(priority_thread_weight_, 1);
610 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
611
612 int32_t starting_count = method->GetCounter();
613 if (Jit::ShouldUsePriorityThreadWeight()) {
614 count *= priority_thread_weight_;
615 }
616 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
617 if (starting_count < warm_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100618 if ((new_count >= warm_method_threshold_) &&
619 (method->GetProfilingInfo(sizeof(void*)) == nullptr)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100620 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
621 if (success) {
622 VLOG(jit) << "Start profiling " << PrettyMethod(method);
623 }
624
625 if (thread_pool_ == nullptr) {
626 // Calling ProfilingInfo::Create might put us in a suspended state, which could
627 // lead to the thread pool being deleted when we are shutting down.
628 DCHECK(Runtime::Current()->IsShuttingDown(self));
629 return;
630 }
631
632 if (!success) {
633 // We failed allocating. Instead of doing the collection on the Java thread, we push
634 // an allocation to a compiler thread, that will do the collection.
635 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
636 }
637 }
638 // Avoid jumping more than one state at a time.
639 new_count = std::min(new_count, hot_method_threshold_ - 1);
Calin Juravleffc87072016-04-20 14:22:09 +0100640 } else if (use_jit_compilation_) {
641 if (starting_count < hot_method_threshold_) {
642 if ((new_count >= hot_method_threshold_) &&
643 !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
644 DCHECK(thread_pool_ != nullptr);
645 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
646 }
647 // Avoid jumping more than one state at a time.
648 new_count = std::min(new_count, osr_method_threshold_ - 1);
649 } else if (starting_count < osr_method_threshold_) {
650 if (!with_backedges) {
651 // If the samples don't contain any back edge, we don't increment the hotness.
652 return;
653 }
654 if ((new_count >= osr_method_threshold_) && !code_cache_->IsOsrCompiled(method)) {
655 DCHECK(thread_pool_ != nullptr);
656 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
657 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100658 }
659 }
660 // Update hotness counter
661 method->SetCounter(new_count);
662}
663
664void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +0100665 Runtime* runtime = Runtime::Current();
666 if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100667 // The compiler requires a ProfilingInfo object.
668 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
669 JitCompileTask compile_task(method, JitCompileTask::kCompile);
670 compile_task.Run(thread);
671 return;
672 }
673
674 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
675 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
676 // instead of interpreting the method.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100677 if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
678 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
679 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100680 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100681 AddSamples(thread, method, 1, /* with_backedges */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100682 }
683}
684
685void Jit::InvokeVirtualOrInterface(Thread* thread,
686 mirror::Object* this_object,
687 ArtMethod* caller,
688 uint32_t dex_pc,
689 ArtMethod* callee ATTRIBUTE_UNUSED) {
690 ScopedAssertNoThreadSuspension ants(thread, __FUNCTION__);
691 DCHECK(this_object != nullptr);
692 ProfilingInfo* info = caller->GetProfilingInfo(sizeof(void*));
693 if (info != nullptr) {
694 // Since the instrumentation is marked from the declaring class we need to mark the card so
695 // that mod-union tables and card rescanning know about the update.
696 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(caller->GetDeclaringClass());
697 info->AddInvokeInfo(dex_pc, this_object->GetClass());
698 }
699}
700
701void Jit::WaitForCompilationToFinish(Thread* self) {
702 if (thread_pool_ != nullptr) {
703 thread_pool_->Wait(self, false, false);
704 }
705}
706
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800707} // namespace jit
708} // namespace art