blob: 2bb8819cb34e4c8cf7495fb4a5b2ce77e995efb0 [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"
26#include "jit_code_cache.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010027#include "oat_file_manager.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000028#include "oat_quick_method_header.h"
Calin Juravle33083d62017-01-18 15:29:12 -080029#include "profile_compilation_info.h"
Calin Juravle4d77b6a2015-12-01 18:38:09 +000030#include "profile_saver.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080031#include "runtime.h"
32#include "runtime_options.h"
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +000033#include "stack_map.h"
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010034#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "utils.h"
36
37namespace art {
38namespace jit {
39
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +000040static constexpr bool kEnableOnStackReplacement = true;
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +010041// At what priority to schedule jit threads. 9 is the lowest foreground priority on device.
42static constexpr int kJitPoolThreadPthreadPriority = 9;
Nicolas Geoffraye8662132016-02-15 10:00:42 +000043
Mathieu Chartier72918ea2016-03-24 11:07:06 -070044// JIT compiler
45void* Jit::jit_library_handle_= nullptr;
46void* Jit::jit_compiler_handle_ = nullptr;
47void* (*Jit::jit_load_)(bool*) = nullptr;
48void (*Jit::jit_unload_)(void*) = nullptr;
49bool (*Jit::jit_compile_method_)(void*, ArtMethod*, Thread*, bool) = nullptr;
50void (*Jit::jit_types_loaded_)(void*, mirror::Class**, size_t count) = nullptr;
51bool Jit::generate_debug_info_ = false;
52
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080053JitOptions* JitOptions::CreateFromRuntimeArguments(const RuntimeArgumentMap& options) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080054 auto* jit_options = new JitOptions;
Calin Juravleffc87072016-04-20 14:22:09 +010055 jit_options->use_jit_compilation_ = options.GetOrDefault(RuntimeArgumentMap::UseJitCompilation);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000056
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057 jit_options->code_cache_initial_capacity_ =
58 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheInitialCapacity);
59 jit_options->code_cache_max_capacity_ =
60 options.GetOrDefault(RuntimeArgumentMap::JITCodeCacheMaxCapacity);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -070061 jit_options->dump_info_on_shutdown_ =
62 options.Exists(RuntimeArgumentMap::DumpJITInfoOnShutdown);
Calin Juravle138dbff2016-06-28 19:36:58 +010063 jit_options->profile_saver_options_ =
64 options.GetOrDefault(RuntimeArgumentMap::ProfileSaverOpts);
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000065
66 jit_options->compile_threshold_ = options.GetOrDefault(RuntimeArgumentMap::JITCompileThreshold);
67 if (jit_options->compile_threshold_ > std::numeric_limits<uint16_t>::max()) {
68 LOG(FATAL) << "Method compilation threshold is above its internal limit.";
69 }
70
71 if (options.Exists(RuntimeArgumentMap::JITWarmupThreshold)) {
72 jit_options->warmup_threshold_ = *options.Get(RuntimeArgumentMap::JITWarmupThreshold);
73 if (jit_options->warmup_threshold_ > std::numeric_limits<uint16_t>::max()) {
74 LOG(FATAL) << "Method warmup threshold is above its internal limit.";
75 }
76 } else {
77 jit_options->warmup_threshold_ = jit_options->compile_threshold_ / 2;
78 }
79
80 if (options.Exists(RuntimeArgumentMap::JITOsrThreshold)) {
81 jit_options->osr_threshold_ = *options.Get(RuntimeArgumentMap::JITOsrThreshold);
82 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
83 LOG(FATAL) << "Method on stack replacement threshold is above its internal limit.";
84 }
85 } else {
86 jit_options->osr_threshold_ = jit_options->compile_threshold_ * 2;
87 if (jit_options->osr_threshold_ > std::numeric_limits<uint16_t>::max()) {
88 jit_options->osr_threshold_ = std::numeric_limits<uint16_t>::max();
89 }
90 }
91
Calin Juravleb2771b42016-04-07 17:09:25 +010092 if (options.Exists(RuntimeArgumentMap::JITPriorityThreadWeight)) {
93 jit_options->priority_thread_weight_ =
94 *options.Get(RuntimeArgumentMap::JITPriorityThreadWeight);
95 if (jit_options->priority_thread_weight_ > jit_options->warmup_threshold_) {
96 LOG(FATAL) << "Priority thread weight is above the warmup threshold.";
97 } else if (jit_options->priority_thread_weight_ == 0) {
98 LOG(FATAL) << "Priority thread weight cannot be 0.";
99 }
100 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100101 jit_options->priority_thread_weight_ = std::max(
102 jit_options->warmup_threshold_ / Jit::kDefaultPriorityThreadWeightRatio,
103 static_cast<size_t>(1));
Calin Juravleb2771b42016-04-07 17:09:25 +0100104 }
105
Calin Juravle155ff3d2016-04-27 14:14:58 +0100106 if (options.Exists(RuntimeArgumentMap::JITInvokeTransitionWeight)) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100107 jit_options->invoke_transition_weight_ =
108 *options.Get(RuntimeArgumentMap::JITInvokeTransitionWeight);
Calin Juravle155ff3d2016-04-27 14:14:58 +0100109 if (jit_options->invoke_transition_weight_ > jit_options->warmup_threshold_) {
110 LOG(FATAL) << "Invoke transition weight is above the warmup threshold.";
111 } else if (jit_options->invoke_transition_weight_ == 0) {
Nicolas Geoffray7c9f3ba2016-05-06 16:52:36 +0100112 LOG(FATAL) << "Invoke transition weight cannot be 0.";
Calin Juravle155ff3d2016-04-27 14:14:58 +0100113 }
Calin Juravle155ff3d2016-04-27 14:14:58 +0100114 } else {
115 jit_options->invoke_transition_weight_ = std::max(
116 jit_options->warmup_threshold_ / Jit::kDefaultInvokeTransitionWeightRatio,
Mathieu Chartier6beced42016-11-15 15:51:31 -0800117 static_cast<size_t>(1));
Calin Juravle155ff3d2016-04-27 14:14:58 +0100118 }
119
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800120 return jit_options;
121}
122
Calin Juravleb2771b42016-04-07 17:09:25 +0100123bool Jit::ShouldUsePriorityThreadWeight() {
Calin Juravle97cbc922016-04-15 16:16:35 +0100124 return Runtime::Current()->InJankPerceptibleProcessState()
125 && Thread::Current()->IsJitSensitiveThread();
Calin Juravleb2771b42016-04-07 17:09:25 +0100126}
127
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700128void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000129 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700130 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000131 MutexLock mu(Thread::Current(), lock_);
132 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700133}
134
Calin Juravleb8e69992016-03-09 15:37:48 +0000135void Jit::DumpForSigQuit(std::ostream& os) {
136 DumpInfo(os);
137 ProfileSaver::DumpInstanceInfo(os);
138}
139
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700140void Jit::AddTimingLogger(const TimingLogger& logger) {
141 cumulative_timings_.AddLogger(logger);
142}
143
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700144Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000145 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000146 memory_use_("Memory used for compilation", 16),
147 lock_("JIT memory use lock"),
Calin Juravle138dbff2016-06-28 19:36:58 +0100148 use_jit_compilation_(true) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800149
150Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100151 DCHECK(options->UseJitCompilation() || options->GetProfileSaverOptions().IsEnabled());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800152 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700153 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700154 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800155 return nullptr;
156 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000157 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000158 options->GetCodeCacheInitialCapacity(),
159 options->GetCodeCacheMaxCapacity(),
160 jit->generate_debug_info_,
161 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800162 if (jit->GetCodeCache() == nullptr) {
163 return nullptr;
164 }
Calin Juravleffc87072016-04-20 14:22:09 +0100165 jit->use_jit_compilation_ = options->UseJitCompilation();
Calin Juravle138dbff2016-06-28 19:36:58 +0100166 jit->profile_saver_options_ = options->GetProfileSaverOptions();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000167 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000168 << PrettySize(options->GetCodeCacheInitialCapacity())
169 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000170 << ", compile_threshold=" << options->GetCompileThreshold()
Calin Juravle138dbff2016-06-28 19:36:58 +0100171 << ", profile_saver_options=" << options->GetProfileSaverOptions();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100172
173
174 jit->hot_method_threshold_ = options->GetCompileThreshold();
175 jit->warm_method_threshold_ = options->GetWarmupThreshold();
176 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100177 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Calin Juravle155ff3d2016-04-27 14:14:58 +0100178 jit->invoke_transition_weight_ = options->GetInvokeTransitionWeight();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100179
180 jit->CreateThreadPool();
181
182 // Notify native debugger about the classes already loaded before the creation of the jit.
183 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800184 return jit.release();
185}
186
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700187bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800188 jit_library_handle_ = dlopen(
189 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
190 if (jit_library_handle_ == nullptr) {
191 std::ostringstream oss;
192 oss << "JIT could not load libart-compiler.so: " << dlerror();
193 *error_msg = oss.str();
194 return false;
195 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000196 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800197 if (jit_load_ == nullptr) {
198 dlclose(jit_library_handle_);
199 *error_msg = "JIT couldn't find jit_load entry point";
200 return false;
201 }
202 jit_unload_ = reinterpret_cast<void (*)(void*)>(
203 dlsym(jit_library_handle_, "jit_unload"));
204 if (jit_unload_ == nullptr) {
205 dlclose(jit_library_handle_);
206 *error_msg = "JIT couldn't find jit_unload entry point";
207 return false;
208 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000209 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800210 dlsym(jit_library_handle_, "jit_compile_method"));
211 if (jit_compile_method_ == nullptr) {
212 dlclose(jit_library_handle_);
213 *error_msg = "JIT couldn't find jit_compile_method entry point";
214 return false;
215 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000216 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
217 dlsym(jit_library_handle_, "jit_types_loaded"));
218 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000219 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000220 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000221 return false;
222 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700223 return true;
224}
225
226bool Jit::LoadCompiler(std::string* error_msg) {
227 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
228 return false;
229 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000230 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800231 VLOG(jit) << "Calling JitLoad interpreter_only="
232 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000233 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800234 if (jit_compiler_handle_ == nullptr) {
235 dlclose(jit_library_handle_);
236 *error_msg = "JIT couldn't load compiler";
237 return false;
238 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000239 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240 return true;
241}
242
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000243bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
Calin Juravleffc87072016-04-20 14:22:09 +0100244 DCHECK(Runtime::Current()->UseJitCompilation());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800245 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000246
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100247 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700248 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700249 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to breakpoint";
Mathieu Chartierd8565452015-03-26 09:41:50 -0700250 return false;
251 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100252
253 // Don't compile the method if we are supposed to be deoptimized.
254 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
255 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
David Sehr709b0702016-10-13 09:12:37 -0700256 VLOG(jit) << "JIT not compiling " << method->PrettyMethod() << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100257 return false;
258 }
259
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000260 // If we get a request to compile a proxy method, we pass the actual Java method
261 // of that proxy method, as the compiler does not expect a proxy method.
Andreas Gampe542451c2016-07-26 09:02:02 -0700262 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000263 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100264 return false;
265 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100266
267 VLOG(jit) << "Compiling method "
David Sehr709b0702016-10-13 09:12:37 -0700268 << ArtMethod::PrettyMethod(method_to_compile)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100269 << " osr=" << std::boolalpha << osr;
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000270 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700271 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100272 if (!success) {
273 VLOG(jit) << "Failed to compile 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;
276 }
Andreas Gampe320ba912016-11-18 17:39:45 -0800277 if (kIsDebugBuild) {
278 if (self->IsExceptionPending()) {
279 mirror::Throwable* exception = self->GetException();
280 LOG(FATAL) << "No pending exception expected after compiling "
281 << ArtMethod::PrettyMethod(method)
282 << ": "
283 << exception->Dump();
284 }
285 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100286 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800287}
288
289void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100290 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
291 // is not null when we instrument.
292 thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
293 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000294 Start();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800295}
296
297void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100298 Thread* self = Thread::Current();
299 DCHECK(Runtime::Current()->IsShuttingDown(self));
300 if (thread_pool_ != nullptr) {
301 ThreadPool* cache = nullptr;
302 {
303 ScopedSuspendAll ssa(__FUNCTION__);
304 // Clear thread_pool_ field while the threads are suspended.
305 // A mutator in the 'AddSamples' method will check against it.
306 cache = thread_pool_.release();
307 }
308 cache->StopWorkers(self);
309 cache->RemoveAllTasks(self);
310 // We could just suspend all threads, but we know those threads
311 // will finish in a short period, so it's not worth adding a suspend logic
312 // here. Besides, this is only done for shutdown.
313 cache->Wait(self, false, false);
314 delete cache;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800315 }
316}
317
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000318void Jit::StartProfileSaver(const std::string& filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000319 const std::vector<std::string>& code_paths,
320 const std::string& foreign_dex_profile_path,
321 const std::string& app_dir) {
Calin Juravle138dbff2016-06-28 19:36:58 +0100322 if (profile_saver_options_.IsEnabled()) {
323 ProfileSaver::Start(profile_saver_options_,
324 filename,
325 code_cache_.get(),
326 code_paths,
327 foreign_dex_profile_path,
328 app_dir);
Calin Juravle31f2c152015-10-23 17:56:15 +0100329 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000330}
331
332void Jit::StopProfileSaver() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100333 if (profile_saver_options_.IsEnabled() && ProfileSaver::IsStarted()) {
Calin Juravleb8e69992016-03-09 15:37:48 +0000334 ProfileSaver::Stop(dump_info_on_shutdown_);
Calin Juravle31f2c152015-10-23 17:56:15 +0100335 }
336}
337
Siva Chandra05d24152016-01-05 17:43:17 -0800338bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100339 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800340}
341
Nicolas Geoffray35122442016-03-02 12:05:30 +0000342bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
343 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
344}
345
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800346Jit::~Jit() {
Calin Juravle138dbff2016-06-28 19:36:58 +0100347 DCHECK(!profile_saver_options_.IsEnabled() || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700348 if (dump_info_on_shutdown_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700349 DumpInfo(LOG_STREAM(INFO));
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700350 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800351 DeleteThreadPool();
352 if (jit_compiler_handle_ != nullptr) {
353 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700354 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800355 }
356 if (jit_library_handle_ != nullptr) {
357 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700358 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800359 }
360}
361
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000362void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
Calin Juravleffc87072016-04-20 14:22:09 +0100363 if (!Runtime::Current()->UseJitCompilation()) {
364 // No need to notify if we only use the JIT to save profiles.
365 return;
366 }
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000367 jit::Jit* jit = Runtime::Current()->GetJit();
Calin Juravleffc87072016-04-20 14:22:09 +0100368 if (jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000369 DCHECK(jit->jit_types_loaded_ != nullptr);
370 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
371 }
372}
373
374void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
375 struct CollectClasses : public ClassVisitor {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700376 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
377 classes_.push_back(klass.Ptr());
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000378 return true;
379 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800380 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000381 };
382
383 if (generate_debug_info_) {
384 ScopedObjectAccess so(Thread::Current());
385
386 CollectClasses visitor;
387 linker->VisitClasses(&visitor);
388 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000389 }
390}
391
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000392extern "C" void art_quick_osr_stub(void** stack,
393 uint32_t stack_size_in_bytes,
394 const uint8_t* native_pc,
395 JValue* result,
396 const char* shorty,
397 Thread* self);
398
399bool Jit::MaybeDoOnStackReplacement(Thread* thread,
400 ArtMethod* method,
401 uint32_t dex_pc,
402 int32_t dex_pc_offset,
403 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000404 if (!kEnableOnStackReplacement) {
405 return false;
406 }
407
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000408 Jit* jit = Runtime::Current()->GetJit();
409 if (jit == nullptr) {
410 return false;
411 }
412
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000413 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
414 // Don't attempt to do an OSR if we are close to the stack limit. Since
415 // the interpreter frames are still on stack, OSR has the potential
416 // to stack overflow even for a simple loop.
417 // b/27094810.
418 return false;
419 }
420
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000421 // Get the actual Java method if this method is from a proxy class. The compiler
422 // and the JIT code cache do not expect methods from proxy classes.
Andreas Gampe542451c2016-07-26 09:02:02 -0700423 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000424
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000425 // Cheap check if the method has been compiled already. That's an indicator that we should
426 // osr into it.
427 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
428 return false;
429 }
430
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000431 // Fetch some data before looking up for an OSR method. We don't want thread
432 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
433 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000434 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000435 const char* shorty = method->GetShorty();
David Sehr709b0702016-10-13 09:12:37 -0700436 std::string method_name(VLOG_IS_ON(jit) ? method->PrettyMethod() : "");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000437 void** memory = nullptr;
438 size_t frame_size = 0;
439 ShadowFrame* shadow_frame = nullptr;
440 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000441
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000442 {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700443 ScopedAssertNoThreadSuspension sts("Holding OSR method");
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000444 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
445 if (osr_method == nullptr) {
446 // No osr method yet, just return to the interpreter.
447 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000448 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000449
450 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000451 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000452
453 // Find stack map starting at the target dex_pc.
454 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
455 if (!stack_map.IsValid()) {
456 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
457 // hope that the next branch has one.
458 return false;
459 }
460
Aart Bik29bdaee2016-05-18 15:44:07 -0700461 // Before allowing the jump, make sure the debugger is not active to avoid jumping from
462 // interpreter to OSR while e.g. single stepping. Note that we could selectively disable
463 // OSR when single stepping, but that's currently hard to know at this point.
464 if (Dbg::IsDebuggerActive()) {
465 return false;
466 }
467
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000468 // We found a stack map, now fill the frame with dex register values from the interpreter's
469 // shadow frame.
470 DexRegisterMap vreg_map =
471 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
472
473 frame_size = osr_method->GetFrameSizeInBytes();
474
475 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
476 // stack.
477 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
478 // but that is engineering complexity not worth the effort for something like OSR.
479 memory = reinterpret_cast<void**>(malloc(frame_size));
480 CHECK(memory != nullptr);
481 memset(memory, 0, frame_size);
482
483 // Art ABI: ArtMethod is at the bottom of the stack.
484 memory[0] = method;
485
486 shadow_frame = thread->PopShadowFrame();
487 if (!vreg_map.IsValid()) {
488 // If we don't have a dex register map, then there are no live dex registers at
489 // this dex pc.
490 } else {
491 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
492 DexRegisterLocation::Kind location =
493 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
494 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000495 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000496 continue;
497 }
498
499 if (location == DexRegisterLocation::Kind::kConstant) {
500 // We skip constants because the compiled code knows how to handle them.
501 continue;
502 }
503
David Srbecky7dc11782016-02-25 13:23:56 +0000504 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000505
506 int32_t vreg_value = shadow_frame->GetVReg(vreg);
507 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
508 number_of_vregs,
509 code_info,
510 encoding);
511 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 Srbecky09ed0982016-02-12 21:58:43 +0000517 native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
518 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
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100557class JitCompileTask FINAL : public Task {
558 public:
559 enum TaskKind {
560 kAllocateProfile,
561 kCompile,
562 kCompileOsr
563 };
564
565 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
566 ScopedObjectAccess soa(Thread::Current());
567 // Add a global ref to the class to prevent class unloading until compilation is done.
568 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
569 CHECK(klass_ != nullptr);
570 }
571
572 ~JitCompileTask() {
573 ScopedObjectAccess soa(Thread::Current());
574 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
575 }
576
577 void Run(Thread* self) OVERRIDE {
578 ScopedObjectAccess soa(self);
579 if (kind_ == kCompile) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100580 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100581 } else if (kind_ == kCompileOsr) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100582 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100583 } else {
584 DCHECK(kind_ == kAllocateProfile);
585 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
David Sehr709b0702016-10-13 09:12:37 -0700586 VLOG(jit) << "Start profiling " << ArtMethod::PrettyMethod(method_);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100587 }
588 }
Calin Juravlea2638922016-04-29 16:44:11 +0100589 ProfileSaver::NotifyJitActivity();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100590 }
591
592 void Finalize() OVERRIDE {
593 delete this;
594 }
595
596 private:
597 ArtMethod* const method_;
598 const TaskKind kind_;
599 jobject klass_;
600
601 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
602};
603
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100604void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100605 if (thread_pool_ == nullptr) {
606 // Should only see this when shutting down.
607 DCHECK(Runtime::Current()->IsShuttingDown(self));
608 return;
609 }
610
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100611 if (method->IsClassInitializer() || method->IsNative() || !method->IsCompilable()) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100612 // We do not want to compile such methods.
613 return;
614 }
615 DCHECK(thread_pool_ != nullptr);
616 DCHECK_GT(warm_method_threshold_, 0);
617 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
618 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
619 DCHECK_GE(priority_thread_weight_, 1);
620 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
621
622 int32_t starting_count = method->GetCounter();
623 if (Jit::ShouldUsePriorityThreadWeight()) {
624 count *= priority_thread_weight_;
625 }
626 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
627 if (starting_count < warm_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100628 if ((new_count >= warm_method_threshold_) &&
Andreas Gampe542451c2016-07-26 09:02:02 -0700629 (method->GetProfilingInfo(kRuntimePointerSize) == nullptr)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100630 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
631 if (success) {
David Sehr709b0702016-10-13 09:12:37 -0700632 VLOG(jit) << "Start profiling " << method->PrettyMethod();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100633 }
634
635 if (thread_pool_ == nullptr) {
636 // Calling ProfilingInfo::Create might put us in a suspended state, which could
637 // lead to the thread pool being deleted when we are shutting down.
638 DCHECK(Runtime::Current()->IsShuttingDown(self));
639 return;
640 }
641
642 if (!success) {
643 // We failed allocating. Instead of doing the collection on the Java thread, we push
644 // an allocation to a compiler thread, that will do the collection.
645 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
646 }
647 }
648 // Avoid jumping more than one state at a time.
649 new_count = std::min(new_count, hot_method_threshold_ - 1);
Calin Juravleffc87072016-04-20 14:22:09 +0100650 } else if (use_jit_compilation_) {
651 if (starting_count < hot_method_threshold_) {
652 if ((new_count >= hot_method_threshold_) &&
653 !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
654 DCHECK(thread_pool_ != nullptr);
655 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
656 }
657 // Avoid jumping more than one state at a time.
658 new_count = std::min(new_count, osr_method_threshold_ - 1);
659 } else if (starting_count < osr_method_threshold_) {
660 if (!with_backedges) {
661 // If the samples don't contain any back edge, we don't increment the hotness.
662 return;
663 }
664 if ((new_count >= osr_method_threshold_) && !code_cache_->IsOsrCompiled(method)) {
665 DCHECK(thread_pool_ != nullptr);
666 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
667 }
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100668 }
669 }
670 // Update hotness counter
671 method->SetCounter(new_count);
672}
673
674void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
Calin Juravleffc87072016-04-20 14:22:09 +0100675 Runtime* runtime = Runtime::Current();
676 if (UNLIKELY(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse())) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100677 // The compiler requires a ProfilingInfo object.
678 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
679 JitCompileTask compile_task(method, JitCompileTask::kCompile);
680 compile_task.Run(thread);
681 return;
682 }
683
Andreas Gampe542451c2016-07-26 09:02:02 -0700684 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100685 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
686 // instead of interpreting the method.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100687 if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
688 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
689 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100690 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100691 AddSamples(thread, method, 1, /* with_backedges */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100692 }
693}
694
Mathieu Chartieref41db72016-10-25 15:08:01 -0700695void Jit::InvokeVirtualOrInterface(ObjPtr<mirror::Object> this_object,
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100696 ArtMethod* caller,
697 uint32_t dex_pc,
698 ArtMethod* callee ATTRIBUTE_UNUSED) {
Mathieu Chartier268764d2016-09-13 12:09:38 -0700699 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100700 DCHECK(this_object != nullptr);
Andreas Gampe542451c2016-07-26 09:02:02 -0700701 ProfilingInfo* info = caller->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100702 if (info != nullptr) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100703 info->AddInvokeInfo(dex_pc, this_object->GetClass());
704 }
705}
706
707void Jit::WaitForCompilationToFinish(Thread* self) {
708 if (thread_pool_ != nullptr) {
709 thread_pool_->Wait(self, false, false);
710 }
711}
712
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000713void Jit::Stop() {
714 Thread* self = Thread::Current();
715 // TODO(ngeoffray): change API to not require calling WaitForCompilationToFinish twice.
716 WaitForCompilationToFinish(self);
717 GetThreadPool()->StopWorkers(self);
718 WaitForCompilationToFinish(self);
719}
720
721void Jit::Start() {
722 GetThreadPool()->StartWorkers(Thread::Current());
723}
724
Andreas Gampef149b3f2016-11-16 14:58:24 -0800725ScopedJitSuspend::ScopedJitSuspend() {
726 jit::Jit* jit = Runtime::Current()->GetJit();
727 was_on_ = (jit != nullptr) && (jit->GetThreadPool() != nullptr);
728 if (was_on_) {
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000729 jit->Stop();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800730 }
731}
732
733ScopedJitSuspend::~ScopedJitSuspend() {
734 if (was_on_) {
735 DCHECK(Runtime::Current()->GetJit() != nullptr);
736 DCHECK(Runtime::Current()->GetJit()->GetThreadPool() != nullptr);
Nicolas Geoffray021c5f22016-12-16 11:22:05 +0000737 Runtime::Current()->GetJit()->Start();
Andreas Gampef149b3f2016-11-16 14:58:24 -0800738 }
739}
740
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800741} // namespace jit
742} // namespace art