blob: e68058dcf48f7805735be1f067d955d7ce90b341 [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;
Mathieu Chartier455f67c2015-03-17 13:48:29 -070054 jit_options->use_jit_ = options.GetOrDefault(RuntimeArgumentMap::UseJIT);
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 Juravle31f2c152015-10-23 17:56:15 +010062 jit_options->save_profiling_info_ =
Nicolas Geoffray83f080a2016-03-08 16:50:21 +000063 options.GetOrDefault(RuntimeArgumentMap::JITSaveProfilingInfo);
64
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
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800105 return jit_options;
106}
107
Calin Juravleb2771b42016-04-07 17:09:25 +0100108bool Jit::ShouldUsePriorityThreadWeight() {
109 // TODO(calin): verify that IsSensitiveThread covers only the cases we are interested on.
110 // In particular if apps can set StrictMode policies for any of their threads, case in which
111 // we need to find another way to track sensitive threads.
112 return Runtime::Current()->InJankPerceptibleProcessState() && Thread::IsSensitiveThread();
113}
114
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700115void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000116 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700117 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000118 MutexLock mu(Thread::Current(), lock_);
119 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700120}
121
Calin Juravleb8e69992016-03-09 15:37:48 +0000122void Jit::DumpForSigQuit(std::ostream& os) {
123 DumpInfo(os);
124 ProfileSaver::DumpInstanceInfo(os);
125}
126
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700127void Jit::AddTimingLogger(const TimingLogger& logger) {
128 cumulative_timings_.AddLogger(logger);
129}
130
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700131Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000132 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000133 memory_use_("Memory used for compilation", 16),
134 lock_("JIT memory use lock"),
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700135 save_profiling_info_(false) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800136
137Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
138 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700139 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700140 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800141 return nullptr;
142 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000143 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000144 options->GetCodeCacheInitialCapacity(),
145 options->GetCodeCacheMaxCapacity(),
146 jit->generate_debug_info_,
147 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800148 if (jit->GetCodeCache() == nullptr) {
149 return nullptr;
150 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000151 jit->save_profiling_info_ = options->GetSaveProfilingInfo();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000152 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000153 << PrettySize(options->GetCodeCacheInitialCapacity())
154 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000155 << ", compile_threshold=" << options->GetCompileThreshold()
156 << ", save_profiling_info=" << options->GetSaveProfilingInfo();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100157
158
159 jit->hot_method_threshold_ = options->GetCompileThreshold();
160 jit->warm_method_threshold_ = options->GetWarmupThreshold();
161 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100162 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100163 jit->transition_weight_ = std::max(
164 jit->warm_method_threshold_ / kDefaultTransitionRatio, static_cast<size_t>(1));
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100165
166 jit->CreateThreadPool();
167
168 // Notify native debugger about the classes already loaded before the creation of the jit.
169 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800170 return jit.release();
171}
172
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700173bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800174 jit_library_handle_ = dlopen(
175 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
176 if (jit_library_handle_ == nullptr) {
177 std::ostringstream oss;
178 oss << "JIT could not load libart-compiler.so: " << dlerror();
179 *error_msg = oss.str();
180 return false;
181 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000182 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800183 if (jit_load_ == nullptr) {
184 dlclose(jit_library_handle_);
185 *error_msg = "JIT couldn't find jit_load entry point";
186 return false;
187 }
188 jit_unload_ = reinterpret_cast<void (*)(void*)>(
189 dlsym(jit_library_handle_, "jit_unload"));
190 if (jit_unload_ == nullptr) {
191 dlclose(jit_library_handle_);
192 *error_msg = "JIT couldn't find jit_unload entry point";
193 return false;
194 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000195 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800196 dlsym(jit_library_handle_, "jit_compile_method"));
197 if (jit_compile_method_ == nullptr) {
198 dlclose(jit_library_handle_);
199 *error_msg = "JIT couldn't find jit_compile_method entry point";
200 return false;
201 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000202 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
203 dlsym(jit_library_handle_, "jit_types_loaded"));
204 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000205 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000206 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000207 return false;
208 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700209 return true;
210}
211
212bool Jit::LoadCompiler(std::string* error_msg) {
213 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
214 return false;
215 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000216 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800217 VLOG(jit) << "Calling JitLoad interpreter_only="
218 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000219 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800220 if (jit_compiler_handle_ == nullptr) {
221 dlclose(jit_library_handle_);
222 *error_msg = "JIT couldn't load compiler";
223 return false;
224 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000225 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800226 return true;
227}
228
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000229bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800230 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000231
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100232 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700233 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
234 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to breakpoint";
235 return false;
236 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100237
238 // Don't compile the method if we are supposed to be deoptimized.
239 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
240 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000241 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100242 return false;
243 }
244
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000245 // If we get a request to compile a proxy method, we pass the actual Java method
246 // of that proxy method, as the compiler does not expect a proxy method.
247 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(sizeof(void*));
248 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100249 return false;
250 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100251
252 VLOG(jit) << "Compiling method "
253 << PrettyMethod(method_to_compile)
254 << " osr=" << std::boolalpha << osr;
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000255 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700256 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100257 if (!success) {
258 VLOG(jit) << "Failed to compile method "
259 << PrettyMethod(method_to_compile)
260 << " osr=" << std::boolalpha << osr;
261 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100262 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800263}
264
265void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100266 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
267 // is not null when we instrument.
268 thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
269 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
270 thread_pool_->StartWorkers(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800271}
272
273void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100274 Thread* self = Thread::Current();
275 DCHECK(Runtime::Current()->IsShuttingDown(self));
276 if (thread_pool_ != nullptr) {
277 ThreadPool* cache = nullptr;
278 {
279 ScopedSuspendAll ssa(__FUNCTION__);
280 // Clear thread_pool_ field while the threads are suspended.
281 // A mutator in the 'AddSamples' method will check against it.
282 cache = thread_pool_.release();
283 }
284 cache->StopWorkers(self);
285 cache->RemoveAllTasks(self);
286 // We could just suspend all threads, but we know those threads
287 // will finish in a short period, so it's not worth adding a suspend logic
288 // here. Besides, this is only done for shutdown.
289 cache->Wait(self, false, false);
290 delete cache;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800291 }
292}
293
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000294void Jit::StartProfileSaver(const std::string& filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000295 const std::vector<std::string>& code_paths,
296 const std::string& foreign_dex_profile_path,
297 const std::string& app_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000298 if (save_profiling_info_) {
Calin Juravlec90bc922016-02-24 10:13:09 +0000299 ProfileSaver::Start(filename, code_cache_.get(), code_paths, foreign_dex_profile_path, app_dir);
Calin Juravle31f2c152015-10-23 17:56:15 +0100300 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000301}
302
303void Jit::StopProfileSaver() {
304 if (save_profiling_info_ && ProfileSaver::IsStarted()) {
Calin Juravleb8e69992016-03-09 15:37:48 +0000305 ProfileSaver::Stop(dump_info_on_shutdown_);
Calin Juravle31f2c152015-10-23 17:56:15 +0100306 }
307}
308
Siva Chandra05d24152016-01-05 17:43:17 -0800309bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100310 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800311}
312
Nicolas Geoffray35122442016-03-02 12:05:30 +0000313bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
314 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
315}
316
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800317Jit::~Jit() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000318 DCHECK(!save_profiling_info_ || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700319 if (dump_info_on_shutdown_) {
320 DumpInfo(LOG(INFO));
321 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800322 DeleteThreadPool();
323 if (jit_compiler_handle_ != nullptr) {
324 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700325 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800326 }
327 if (jit_library_handle_ != nullptr) {
328 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700329 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800330 }
331}
332
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000333void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
334 jit::Jit* jit = Runtime::Current()->GetJit();
335 if (jit != nullptr && jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000336 DCHECK(jit->jit_types_loaded_ != nullptr);
337 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
338 }
339}
340
341void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
342 struct CollectClasses : public ClassVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800343 bool operator()(mirror::Class* klass) override {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000344 classes_.push_back(klass);
345 return true;
346 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800347 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000348 };
349
350 if (generate_debug_info_) {
351 ScopedObjectAccess so(Thread::Current());
352
353 CollectClasses visitor;
354 linker->VisitClasses(&visitor);
355 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000356 }
357}
358
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000359extern "C" void art_quick_osr_stub(void** stack,
360 uint32_t stack_size_in_bytes,
361 const uint8_t* native_pc,
362 JValue* result,
363 const char* shorty,
364 Thread* self);
365
366bool Jit::MaybeDoOnStackReplacement(Thread* thread,
367 ArtMethod* method,
368 uint32_t dex_pc,
369 int32_t dex_pc_offset,
370 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000371 if (!kEnableOnStackReplacement) {
372 return false;
373 }
374
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000375 Jit* jit = Runtime::Current()->GetJit();
376 if (jit == nullptr) {
377 return false;
378 }
379
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000380 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
381 // Don't attempt to do an OSR if we are close to the stack limit. Since
382 // the interpreter frames are still on stack, OSR has the potential
383 // to stack overflow even for a simple loop.
384 // b/27094810.
385 return false;
386 }
387
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000388 // Get the actual Java method if this method is from a proxy class. The compiler
389 // and the JIT code cache do not expect methods from proxy classes.
390 method = method->GetInterfaceMethodIfProxy(sizeof(void*));
391
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000392 // Cheap check if the method has been compiled already. That's an indicator that we should
393 // osr into it.
394 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
395 return false;
396 }
397
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000398 // Fetch some data before looking up for an OSR method. We don't want thread
399 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
400 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000401 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000402 const char* shorty = method->GetShorty();
403 std::string method_name(VLOG_IS_ON(jit) ? PrettyMethod(method) : "");
404 void** memory = nullptr;
405 size_t frame_size = 0;
406 ShadowFrame* shadow_frame = nullptr;
407 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000408
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000409 {
410 ScopedAssertNoThreadSuspension sts(thread, "Holding OSR method");
411 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
412 if (osr_method == nullptr) {
413 // No osr method yet, just return to the interpreter.
414 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000415 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000416
417 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000418 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000419
420 // Find stack map starting at the target dex_pc.
421 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
422 if (!stack_map.IsValid()) {
423 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
424 // hope that the next branch has one.
425 return false;
426 }
427
428 // We found a stack map, now fill the frame with dex register values from the interpreter's
429 // shadow frame.
430 DexRegisterMap vreg_map =
431 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
432
433 frame_size = osr_method->GetFrameSizeInBytes();
434
435 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
436 // stack.
437 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
438 // but that is engineering complexity not worth the effort for something like OSR.
439 memory = reinterpret_cast<void**>(malloc(frame_size));
440 CHECK(memory != nullptr);
441 memset(memory, 0, frame_size);
442
443 // Art ABI: ArtMethod is at the bottom of the stack.
444 memory[0] = method;
445
446 shadow_frame = thread->PopShadowFrame();
447 if (!vreg_map.IsValid()) {
448 // If we don't have a dex register map, then there are no live dex registers at
449 // this dex pc.
450 } else {
451 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
452 DexRegisterLocation::Kind location =
453 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
454 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000455 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000456 continue;
457 }
458
459 if (location == DexRegisterLocation::Kind::kConstant) {
460 // We skip constants because the compiled code knows how to handle them.
461 continue;
462 }
463
David Srbecky7dc11782016-02-25 13:23:56 +0000464 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000465
466 int32_t vreg_value = shadow_frame->GetVReg(vreg);
467 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
468 number_of_vregs,
469 code_info,
470 encoding);
471 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
472 DCHECK_GT(slot_offset, 0);
473 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
474 }
475 }
476
David Srbecky09ed0982016-02-12 21:58:43 +0000477 native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
478 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000479 VLOG(jit) << "Jumping to "
480 << method_name
481 << "@"
482 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000483 }
484
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000485 {
486 ManagedStack fragment;
487 thread->PushManagedStackFragment(&fragment);
488 (*art_quick_osr_stub)(memory,
489 frame_size,
490 native_pc,
491 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000492 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000493 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000494
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000495 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
496 thread->DeoptimizeWithDeoptimizationException(result);
497 }
498 thread->PopManagedStackFragment(fragment);
499 }
500 free(memory);
501 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000502 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000503 return true;
504}
505
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000506void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
507 if (bytes > 4 * MB) {
508 LOG(INFO) << "Compiler allocated "
509 << PrettySize(bytes)
510 << " to compile "
511 << PrettyMethod(method);
512 }
513 MutexLock mu(Thread::Current(), lock_);
514 memory_use_.AddValue(bytes);
515}
516
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100517class JitCompileTask FINAL : public Task {
518 public:
519 enum TaskKind {
520 kAllocateProfile,
521 kCompile,
522 kCompileOsr
523 };
524
525 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
526 ScopedObjectAccess soa(Thread::Current());
527 // Add a global ref to the class to prevent class unloading until compilation is done.
528 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
529 CHECK(klass_ != nullptr);
530 }
531
532 ~JitCompileTask() {
533 ScopedObjectAccess soa(Thread::Current());
534 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
535 }
536
537 void Run(Thread* self) OVERRIDE {
538 ScopedObjectAccess soa(self);
539 if (kind_ == kCompile) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100540 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100541 } else if (kind_ == kCompileOsr) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100542 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100543 } else {
544 DCHECK(kind_ == kAllocateProfile);
545 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
546 VLOG(jit) << "Start profiling " << PrettyMethod(method_);
547 }
548 }
549 }
550
551 void Finalize() OVERRIDE {
552 delete this;
553 }
554
555 private:
556 ArtMethod* const method_;
557 const TaskKind kind_;
558 jobject klass_;
559
560 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
561};
562
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100563void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100564 if (thread_pool_ == nullptr) {
565 // Should only see this when shutting down.
566 DCHECK(Runtime::Current()->IsShuttingDown(self));
567 return;
568 }
569
570 if (method->IsClassInitializer() || method->IsNative()) {
571 // We do not want to compile such methods.
572 return;
573 }
574 DCHECK(thread_pool_ != nullptr);
575 DCHECK_GT(warm_method_threshold_, 0);
576 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
577 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
578 DCHECK_GE(priority_thread_weight_, 1);
579 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
580
581 int32_t starting_count = method->GetCounter();
582 if (Jit::ShouldUsePriorityThreadWeight()) {
583 count *= priority_thread_weight_;
584 }
585 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
586 if (starting_count < warm_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100587 if ((new_count >= warm_method_threshold_) &&
588 (method->GetProfilingInfo(sizeof(void*)) == nullptr)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100589 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
590 if (success) {
591 VLOG(jit) << "Start profiling " << PrettyMethod(method);
592 }
593
594 if (thread_pool_ == nullptr) {
595 // Calling ProfilingInfo::Create might put us in a suspended state, which could
596 // lead to the thread pool being deleted when we are shutting down.
597 DCHECK(Runtime::Current()->IsShuttingDown(self));
598 return;
599 }
600
601 if (!success) {
602 // We failed allocating. Instead of doing the collection on the Java thread, we push
603 // an allocation to a compiler thread, that will do the collection.
604 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
605 }
606 }
607 // Avoid jumping more than one state at a time.
608 new_count = std::min(new_count, hot_method_threshold_ - 1);
609 } else if (starting_count < hot_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100610 if ((new_count >= hot_method_threshold_) &&
611 !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100612 DCHECK(thread_pool_ != nullptr);
613 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
614 }
615 // Avoid jumping more than one state at a time.
616 new_count = std::min(new_count, osr_method_threshold_ - 1);
617 } else if (starting_count < osr_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100618 if (!with_backedges) {
619 // If the samples don't contain any back edge, we don't increment the hotness.
620 return;
621 }
622 if ((new_count >= osr_method_threshold_) && !code_cache_->IsOsrCompiled(method)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100623 DCHECK(thread_pool_ != nullptr);
624 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
625 }
626 }
627 // Update hotness counter
628 method->SetCounter(new_count);
629}
630
631void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
632 if (UNLIKELY(Runtime::Current()->GetJit()->JitAtFirstUse())) {
633 // The compiler requires a ProfilingInfo object.
634 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
635 JitCompileTask compile_task(method, JitCompileTask::kCompile);
636 compile_task.Run(thread);
637 return;
638 }
639
640 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
641 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
642 // instead of interpreting the method.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100643 if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
644 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
645 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100646 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100647 AddSamples(thread, method, 1, /* with_backedges */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100648 }
649}
650
651void Jit::InvokeVirtualOrInterface(Thread* thread,
652 mirror::Object* this_object,
653 ArtMethod* caller,
654 uint32_t dex_pc,
655 ArtMethod* callee ATTRIBUTE_UNUSED) {
656 ScopedAssertNoThreadSuspension ants(thread, __FUNCTION__);
657 DCHECK(this_object != nullptr);
658 ProfilingInfo* info = caller->GetProfilingInfo(sizeof(void*));
659 if (info != nullptr) {
660 // Since the instrumentation is marked from the declaring class we need to mark the card so
661 // that mod-union tables and card rescanning know about the update.
662 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(caller->GetDeclaringClass());
663 info->AddInvokeInfo(dex_pc, this_object->GetClass());
664 }
665}
666
667void Jit::WaitForCompilationToFinish(Thread* self) {
668 if (thread_pool_ != nullptr) {
669 thread_pool_->Wait(self, false, false);
670 }
671}
672
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800673} // namespace jit
674} // namespace art