blob: 558e4435f0018ffc33697522e22af023f9e3f80c [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 {
100 jit_options->priority_thread_weight_ =
101 std::max(jit_options->compile_threshold_ / 2000, static_cast<size_t>(1));
102 }
103
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800104 return jit_options;
105}
106
Calin Juravleb2771b42016-04-07 17:09:25 +0100107bool Jit::ShouldUsePriorityThreadWeight() {
108 // TODO(calin): verify that IsSensitiveThread covers only the cases we are interested on.
109 // In particular if apps can set StrictMode policies for any of their threads, case in which
110 // we need to find another way to track sensitive threads.
111 return Runtime::Current()->InJankPerceptibleProcessState() && Thread::IsSensitiveThread();
112}
113
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700114void Jit::DumpInfo(std::ostream& os) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000115 code_cache_->Dump(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700116 cumulative_timings_.Dump(os);
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000117 MutexLock mu(Thread::Current(), lock_);
118 memory_use_.PrintMemoryUse(os);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700119}
120
121void Jit::AddTimingLogger(const TimingLogger& logger) {
122 cumulative_timings_.AddLogger(logger);
123}
124
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700125Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000126 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000127 memory_use_("Memory used for compilation", 16),
128 lock_("JIT memory use lock"),
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700129 save_profiling_info_(false) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800130
131Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
132 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700133 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700134 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800135 return nullptr;
136 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000137 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000138 options->GetCodeCacheInitialCapacity(),
139 options->GetCodeCacheMaxCapacity(),
140 jit->generate_debug_info_,
141 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800142 if (jit->GetCodeCache() == nullptr) {
143 return nullptr;
144 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000145 jit->save_profiling_info_ = options->GetSaveProfilingInfo();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000146 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000147 << PrettySize(options->GetCodeCacheInitialCapacity())
148 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000149 << ", compile_threshold=" << options->GetCompileThreshold()
150 << ", save_profiling_info=" << options->GetSaveProfilingInfo();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100151
152
153 jit->hot_method_threshold_ = options->GetCompileThreshold();
154 jit->warm_method_threshold_ = options->GetWarmupThreshold();
155 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100156 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100157
158 jit->CreateThreadPool();
159
160 // Notify native debugger about the classes already loaded before the creation of the jit.
161 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800162 return jit.release();
163}
164
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700165bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800166 jit_library_handle_ = dlopen(
167 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
168 if (jit_library_handle_ == nullptr) {
169 std::ostringstream oss;
170 oss << "JIT could not load libart-compiler.so: " << dlerror();
171 *error_msg = oss.str();
172 return false;
173 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000174 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800175 if (jit_load_ == nullptr) {
176 dlclose(jit_library_handle_);
177 *error_msg = "JIT couldn't find jit_load entry point";
178 return false;
179 }
180 jit_unload_ = reinterpret_cast<void (*)(void*)>(
181 dlsym(jit_library_handle_, "jit_unload"));
182 if (jit_unload_ == nullptr) {
183 dlclose(jit_library_handle_);
184 *error_msg = "JIT couldn't find jit_unload entry point";
185 return false;
186 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000187 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800188 dlsym(jit_library_handle_, "jit_compile_method"));
189 if (jit_compile_method_ == nullptr) {
190 dlclose(jit_library_handle_);
191 *error_msg = "JIT couldn't find jit_compile_method entry point";
192 return false;
193 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000194 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
195 dlsym(jit_library_handle_, "jit_types_loaded"));
196 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000197 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000198 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000199 return false;
200 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700201 return true;
202}
203
204bool Jit::LoadCompiler(std::string* error_msg) {
205 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
206 return false;
207 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000208 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800209 VLOG(jit) << "Calling JitLoad interpreter_only="
210 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000211 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800212 if (jit_compiler_handle_ == nullptr) {
213 dlclose(jit_library_handle_);
214 *error_msg = "JIT couldn't load compiler";
215 return false;
216 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000217 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800218 return true;
219}
220
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000221bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800222 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000223
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100224 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700225 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
226 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to breakpoint";
227 return false;
228 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100229
230 // Don't compile the method if we are supposed to be deoptimized.
231 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
232 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000233 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100234 return false;
235 }
236
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000237 // If we get a request to compile a proxy method, we pass the actual Java method
238 // of that proxy method, as the compiler does not expect a proxy method.
239 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(sizeof(void*));
240 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100241 return false;
242 }
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000243 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700244 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100245 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800246}
247
248void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100249 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
250 // is not null when we instrument.
251 thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
252 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
253 thread_pool_->StartWorkers(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800254}
255
256void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100257 Thread* self = Thread::Current();
258 DCHECK(Runtime::Current()->IsShuttingDown(self));
259 if (thread_pool_ != nullptr) {
260 ThreadPool* cache = nullptr;
261 {
262 ScopedSuspendAll ssa(__FUNCTION__);
263 // Clear thread_pool_ field while the threads are suspended.
264 // A mutator in the 'AddSamples' method will check against it.
265 cache = thread_pool_.release();
266 }
267 cache->StopWorkers(self);
268 cache->RemoveAllTasks(self);
269 // We could just suspend all threads, but we know those threads
270 // will finish in a short period, so it's not worth adding a suspend logic
271 // here. Besides, this is only done for shutdown.
272 cache->Wait(self, false, false);
273 delete cache;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800274 }
275}
276
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000277void Jit::StartProfileSaver(const std::string& filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000278 const std::vector<std::string>& code_paths,
279 const std::string& foreign_dex_profile_path,
280 const std::string& app_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000281 if (save_profiling_info_) {
Calin Juravlec90bc922016-02-24 10:13:09 +0000282 ProfileSaver::Start(filename, code_cache_.get(), code_paths, foreign_dex_profile_path, app_dir);
Calin Juravle31f2c152015-10-23 17:56:15 +0100283 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000284}
285
286void Jit::StopProfileSaver() {
287 if (save_profiling_info_ && ProfileSaver::IsStarted()) {
288 ProfileSaver::Stop();
Calin Juravle31f2c152015-10-23 17:56:15 +0100289 }
290}
291
Siva Chandra05d24152016-01-05 17:43:17 -0800292bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100293 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800294}
295
Nicolas Geoffray35122442016-03-02 12:05:30 +0000296bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
297 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
298}
299
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800300Jit::~Jit() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000301 DCHECK(!save_profiling_info_ || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700302 if (dump_info_on_shutdown_) {
303 DumpInfo(LOG(INFO));
304 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800305 DeleteThreadPool();
306 if (jit_compiler_handle_ != nullptr) {
307 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700308 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800309 }
310 if (jit_library_handle_ != nullptr) {
311 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700312 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800313 }
314}
315
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000316void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
317 jit::Jit* jit = Runtime::Current()->GetJit();
318 if (jit != nullptr && jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000319 DCHECK(jit->jit_types_loaded_ != nullptr);
320 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
321 }
322}
323
324void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
325 struct CollectClasses : public ClassVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800326 bool operator()(mirror::Class* klass) override {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000327 classes_.push_back(klass);
328 return true;
329 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800330 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000331 };
332
333 if (generate_debug_info_) {
334 ScopedObjectAccess so(Thread::Current());
335
336 CollectClasses visitor;
337 linker->VisitClasses(&visitor);
338 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000339 }
340}
341
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000342extern "C" void art_quick_osr_stub(void** stack,
343 uint32_t stack_size_in_bytes,
344 const uint8_t* native_pc,
345 JValue* result,
346 const char* shorty,
347 Thread* self);
348
349bool Jit::MaybeDoOnStackReplacement(Thread* thread,
350 ArtMethod* method,
351 uint32_t dex_pc,
352 int32_t dex_pc_offset,
353 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000354 if (!kEnableOnStackReplacement) {
355 return false;
356 }
357
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000358 Jit* jit = Runtime::Current()->GetJit();
359 if (jit == nullptr) {
360 return false;
361 }
362
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000363 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
364 // Don't attempt to do an OSR if we are close to the stack limit. Since
365 // the interpreter frames are still on stack, OSR has the potential
366 // to stack overflow even for a simple loop.
367 // b/27094810.
368 return false;
369 }
370
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000371 // Get the actual Java method if this method is from a proxy class. The compiler
372 // and the JIT code cache do not expect methods from proxy classes.
373 method = method->GetInterfaceMethodIfProxy(sizeof(void*));
374
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000375 // Cheap check if the method has been compiled already. That's an indicator that we should
376 // osr into it.
377 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
378 return false;
379 }
380
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000381 // Fetch some data before looking up for an OSR method. We don't want thread
382 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
383 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000384 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000385 const char* shorty = method->GetShorty();
386 std::string method_name(VLOG_IS_ON(jit) ? PrettyMethod(method) : "");
387 void** memory = nullptr;
388 size_t frame_size = 0;
389 ShadowFrame* shadow_frame = nullptr;
390 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000391
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000392 {
393 ScopedAssertNoThreadSuspension sts(thread, "Holding OSR method");
394 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
395 if (osr_method == nullptr) {
396 // No osr method yet, just return to the interpreter.
397 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000398 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000399
400 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000401 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000402
403 // Find stack map starting at the target dex_pc.
404 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
405 if (!stack_map.IsValid()) {
406 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
407 // hope that the next branch has one.
408 return false;
409 }
410
411 // We found a stack map, now fill the frame with dex register values from the interpreter's
412 // shadow frame.
413 DexRegisterMap vreg_map =
414 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
415
416 frame_size = osr_method->GetFrameSizeInBytes();
417
418 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
419 // stack.
420 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
421 // but that is engineering complexity not worth the effort for something like OSR.
422 memory = reinterpret_cast<void**>(malloc(frame_size));
423 CHECK(memory != nullptr);
424 memset(memory, 0, frame_size);
425
426 // Art ABI: ArtMethod is at the bottom of the stack.
427 memory[0] = method;
428
429 shadow_frame = thread->PopShadowFrame();
430 if (!vreg_map.IsValid()) {
431 // If we don't have a dex register map, then there are no live dex registers at
432 // this dex pc.
433 } else {
434 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
435 DexRegisterLocation::Kind location =
436 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
437 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000438 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000439 continue;
440 }
441
442 if (location == DexRegisterLocation::Kind::kConstant) {
443 // We skip constants because the compiled code knows how to handle them.
444 continue;
445 }
446
David Srbecky7dc11782016-02-25 13:23:56 +0000447 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000448
449 int32_t vreg_value = shadow_frame->GetVReg(vreg);
450 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
451 number_of_vregs,
452 code_info,
453 encoding);
454 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
455 DCHECK_GT(slot_offset, 0);
456 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
457 }
458 }
459
David Srbecky09ed0982016-02-12 21:58:43 +0000460 native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
461 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000462 VLOG(jit) << "Jumping to "
463 << method_name
464 << "@"
465 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000466 }
467
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000468 {
469 ManagedStack fragment;
470 thread->PushManagedStackFragment(&fragment);
471 (*art_quick_osr_stub)(memory,
472 frame_size,
473 native_pc,
474 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000475 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000476 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000477
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000478 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
479 thread->DeoptimizeWithDeoptimizationException(result);
480 }
481 thread->PopManagedStackFragment(fragment);
482 }
483 free(memory);
484 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000485 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000486 return true;
487}
488
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000489void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
490 if (bytes > 4 * MB) {
491 LOG(INFO) << "Compiler allocated "
492 << PrettySize(bytes)
493 << " to compile "
494 << PrettyMethod(method);
495 }
496 MutexLock mu(Thread::Current(), lock_);
497 memory_use_.AddValue(bytes);
498}
499
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100500class JitCompileTask FINAL : public Task {
501 public:
502 enum TaskKind {
503 kAllocateProfile,
504 kCompile,
505 kCompileOsr
506 };
507
508 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
509 ScopedObjectAccess soa(Thread::Current());
510 // Add a global ref to the class to prevent class unloading until compilation is done.
511 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
512 CHECK(klass_ != nullptr);
513 }
514
515 ~JitCompileTask() {
516 ScopedObjectAccess soa(Thread::Current());
517 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
518 }
519
520 void Run(Thread* self) OVERRIDE {
521 ScopedObjectAccess soa(self);
522 if (kind_ == kCompile) {
523 VLOG(jit) << "JitCompileTask compiling method " << PrettyMethod(method_);
524 if (!Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false)) {
525 VLOG(jit) << "Failed to compile method " << PrettyMethod(method_);
526 }
527 } else if (kind_ == kCompileOsr) {
528 VLOG(jit) << "JitCompileTask compiling method osr " << PrettyMethod(method_);
529 if (!Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true)) {
530 VLOG(jit) << "Failed to compile method osr " << PrettyMethod(method_);
531 }
532 } else {
533 DCHECK(kind_ == kAllocateProfile);
534 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
535 VLOG(jit) << "Start profiling " << PrettyMethod(method_);
536 }
537 }
538 }
539
540 void Finalize() OVERRIDE {
541 delete this;
542 }
543
544 private:
545 ArtMethod* const method_;
546 const TaskKind kind_;
547 jobject klass_;
548
549 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
550};
551
552void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count) {
553 if (thread_pool_ == nullptr) {
554 // Should only see this when shutting down.
555 DCHECK(Runtime::Current()->IsShuttingDown(self));
556 return;
557 }
558
559 if (method->IsClassInitializer() || method->IsNative()) {
560 // We do not want to compile such methods.
561 return;
562 }
563 DCHECK(thread_pool_ != nullptr);
564 DCHECK_GT(warm_method_threshold_, 0);
565 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
566 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
567 DCHECK_GE(priority_thread_weight_, 1);
568 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
569
570 int32_t starting_count = method->GetCounter();
571 if (Jit::ShouldUsePriorityThreadWeight()) {
572 count *= priority_thread_weight_;
573 }
574 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
575 if (starting_count < warm_method_threshold_) {
576 if (new_count >= warm_method_threshold_) {
577 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
578 if (success) {
579 VLOG(jit) << "Start profiling " << PrettyMethod(method);
580 }
581
582 if (thread_pool_ == nullptr) {
583 // Calling ProfilingInfo::Create might put us in a suspended state, which could
584 // lead to the thread pool being deleted when we are shutting down.
585 DCHECK(Runtime::Current()->IsShuttingDown(self));
586 return;
587 }
588
589 if (!success) {
590 // We failed allocating. Instead of doing the collection on the Java thread, we push
591 // an allocation to a compiler thread, that will do the collection.
592 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
593 }
594 }
595 // Avoid jumping more than one state at a time.
596 new_count = std::min(new_count, hot_method_threshold_ - 1);
597 } else if (starting_count < hot_method_threshold_) {
598 if (new_count >= hot_method_threshold_) {
599 DCHECK(thread_pool_ != nullptr);
600 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
601 }
602 // Avoid jumping more than one state at a time.
603 new_count = std::min(new_count, osr_method_threshold_ - 1);
604 } else if (starting_count < osr_method_threshold_) {
605 if (new_count >= osr_method_threshold_) {
606 DCHECK(thread_pool_ != nullptr);
607 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
608 }
609 }
610 // Update hotness counter
611 method->SetCounter(new_count);
612}
613
614void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
615 if (UNLIKELY(Runtime::Current()->GetJit()->JitAtFirstUse())) {
616 // The compiler requires a ProfilingInfo object.
617 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
618 JitCompileTask compile_task(method, JitCompileTask::kCompile);
619 compile_task.Run(thread);
620 return;
621 }
622
623 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
624 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
625 // instead of interpreting the method.
626 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
627 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
628 if ((profiling_info != nullptr) &&
629 (profiling_info->GetSavedEntryPoint() != nullptr) &&
630 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
631 method->SetEntryPointFromQuickCompiledCode(profiling_info->GetSavedEntryPoint());
632 } else {
633 AddSamples(thread, method, 1);
634 }
635}
636
637void Jit::InvokeVirtualOrInterface(Thread* thread,
638 mirror::Object* this_object,
639 ArtMethod* caller,
640 uint32_t dex_pc,
641 ArtMethod* callee ATTRIBUTE_UNUSED) {
642 ScopedAssertNoThreadSuspension ants(thread, __FUNCTION__);
643 DCHECK(this_object != nullptr);
644 ProfilingInfo* info = caller->GetProfilingInfo(sizeof(void*));
645 if (info != nullptr) {
646 // Since the instrumentation is marked from the declaring class we need to mark the card so
647 // that mod-union tables and card rescanning know about the update.
648 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(caller->GetDeclaringClass());
649 info->AddInvokeInfo(dex_pc, this_object->GetClass());
650 }
651}
652
653void Jit::WaitForCompilationToFinish(Thread* self) {
654 if (thread_pool_ != nullptr) {
655 thread_pool_->Wait(self, false, false);
656 }
657}
658
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800659} // namespace jit
660} // namespace art