blob: 2a6684717706b1acd12d3e65cf706949201b0246 [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
122void Jit::AddTimingLogger(const TimingLogger& logger) {
123 cumulative_timings_.AddLogger(logger);
124}
125
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700126Jit::Jit() : dump_info_on_shutdown_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000127 cumulative_timings_("JIT timings"),
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000128 memory_use_("Memory used for compilation", 16),
129 lock_("JIT memory use lock"),
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700130 save_profiling_info_(false) {}
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800131
132Jit* Jit::Create(JitOptions* options, std::string* error_msg) {
133 std::unique_ptr<Jit> jit(new Jit);
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700134 jit->dump_info_on_shutdown_ = options->DumpJitInfoOnShutdown();
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700135 if (jit_compiler_handle_ == nullptr && !LoadCompiler(error_msg)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800136 return nullptr;
137 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000138 jit->code_cache_.reset(JitCodeCache::Create(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000139 options->GetCodeCacheInitialCapacity(),
140 options->GetCodeCacheMaxCapacity(),
141 jit->generate_debug_info_,
142 error_msg));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800143 if (jit->GetCodeCache() == nullptr) {
144 return nullptr;
145 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000146 jit->save_profiling_info_ = options->GetSaveProfilingInfo();
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000147 VLOG(jit) << "JIT created with initial_capacity="
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000148 << PrettySize(options->GetCodeCacheInitialCapacity())
149 << ", max_capacity=" << PrettySize(options->GetCodeCacheMaxCapacity())
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000150 << ", compile_threshold=" << options->GetCompileThreshold()
151 << ", save_profiling_info=" << options->GetSaveProfilingInfo();
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100152
153
154 jit->hot_method_threshold_ = options->GetCompileThreshold();
155 jit->warm_method_threshold_ = options->GetWarmupThreshold();
156 jit->osr_method_threshold_ = options->GetOsrThreshold();
Nicolas Geoffrayba6aae02016-04-14 14:17:29 +0100157 jit->priority_thread_weight_ = options->GetPriorityThreadWeight();
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100158 jit->transition_weight_ = std::max(
159 jit->warm_method_threshold_ / kDefaultTransitionRatio, static_cast<size_t>(1));
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100160
161 jit->CreateThreadPool();
162
163 // Notify native debugger about the classes already loaded before the creation of the jit.
164 jit->DumpTypeInfoForLoadedTypes(Runtime::Current()->GetClassLinker());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800165 return jit.release();
166}
167
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700168bool Jit::LoadCompilerLibrary(std::string* error_msg) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800169 jit_library_handle_ = dlopen(
170 kIsDebugBuild ? "libartd-compiler.so" : "libart-compiler.so", RTLD_NOW);
171 if (jit_library_handle_ == nullptr) {
172 std::ostringstream oss;
173 oss << "JIT could not load libart-compiler.so: " << dlerror();
174 *error_msg = oss.str();
175 return false;
176 }
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000177 jit_load_ = reinterpret_cast<void* (*)(bool*)>(dlsym(jit_library_handle_, "jit_load"));
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800178 if (jit_load_ == nullptr) {
179 dlclose(jit_library_handle_);
180 *error_msg = "JIT couldn't find jit_load entry point";
181 return false;
182 }
183 jit_unload_ = reinterpret_cast<void (*)(void*)>(
184 dlsym(jit_library_handle_, "jit_unload"));
185 if (jit_unload_ == nullptr) {
186 dlclose(jit_library_handle_);
187 *error_msg = "JIT couldn't find jit_unload entry point";
188 return false;
189 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000190 jit_compile_method_ = reinterpret_cast<bool (*)(void*, ArtMethod*, Thread*, bool)>(
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800191 dlsym(jit_library_handle_, "jit_compile_method"));
192 if (jit_compile_method_ == nullptr) {
193 dlclose(jit_library_handle_);
194 *error_msg = "JIT couldn't find jit_compile_method entry point";
195 return false;
196 }
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000197 jit_types_loaded_ = reinterpret_cast<void (*)(void*, mirror::Class**, size_t)>(
198 dlsym(jit_library_handle_, "jit_types_loaded"));
199 if (jit_types_loaded_ == nullptr) {
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000200 dlclose(jit_library_handle_);
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000201 *error_msg = "JIT couldn't find jit_types_loaded entry point";
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000202 return false;
203 }
Mathieu Chartierc1bc4152016-03-24 17:22:52 -0700204 return true;
205}
206
207bool Jit::LoadCompiler(std::string* error_msg) {
208 if (jit_library_handle_ == nullptr && !LoadCompilerLibrary(error_msg)) {
209 return false;
210 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000211 bool will_generate_debug_symbols = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800212 VLOG(jit) << "Calling JitLoad interpreter_only="
213 << Runtime::Current()->GetInstrumentation()->InterpretOnly();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000214 jit_compiler_handle_ = (jit_load_)(&will_generate_debug_symbols);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800215 if (jit_compiler_handle_ == nullptr) {
216 dlclose(jit_library_handle_);
217 *error_msg = "JIT couldn't load compiler";
218 return false;
219 }
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000220 generate_debug_info_ = will_generate_debug_symbols;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800221 return true;
222}
223
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000224bool Jit::CompileMethod(ArtMethod* method, Thread* self, bool osr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800225 DCHECK(!method->IsRuntimeMethod());
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000226
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100227 // Don't compile the method if it has breakpoints.
Mathieu Chartierd8565452015-03-26 09:41:50 -0700228 if (Dbg::IsDebuggerActive() && Dbg::MethodHasAnyBreakpoints(method)) {
229 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to breakpoint";
230 return false;
231 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100232
233 // Don't compile the method if we are supposed to be deoptimized.
234 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
235 if (instrumentation->AreAllMethodsDeoptimized() || instrumentation->IsDeoptimized(method)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000236 VLOG(jit) << "JIT not compiling " << PrettyMethod(method) << " due to deoptimization";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100237 return false;
238 }
239
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000240 // If we get a request to compile a proxy method, we pass the actual Java method
241 // of that proxy method, as the compiler does not expect a proxy method.
242 ArtMethod* method_to_compile = method->GetInterfaceMethodIfProxy(sizeof(void*));
243 if (!code_cache_->NotifyCompilationOf(method_to_compile, self, osr)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100244 return false;
245 }
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100246
247 VLOG(jit) << "Compiling method "
248 << PrettyMethod(method_to_compile)
249 << " osr=" << std::boolalpha << osr;
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000250 bool success = jit_compile_method_(jit_compiler_handle_, method_to_compile, self, osr);
buzbee454b3b62016-04-07 14:42:47 -0700251 code_cache_->DoneCompiling(method_to_compile, self, osr);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100252 if (!success) {
253 VLOG(jit) << "Failed to compile method "
254 << PrettyMethod(method_to_compile)
255 << " osr=" << std::boolalpha << osr;
256 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100257 return success;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800258}
259
260void Jit::CreateThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100261 // There is a DCHECK in the 'AddSamples' method to ensure the tread pool
262 // is not null when we instrument.
263 thread_pool_.reset(new ThreadPool("Jit thread pool", 1));
264 thread_pool_->SetPthreadPriority(kJitPoolThreadPthreadPriority);
265 thread_pool_->StartWorkers(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800266}
267
268void Jit::DeleteThreadPool() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100269 Thread* self = Thread::Current();
270 DCHECK(Runtime::Current()->IsShuttingDown(self));
271 if (thread_pool_ != nullptr) {
272 ThreadPool* cache = nullptr;
273 {
274 ScopedSuspendAll ssa(__FUNCTION__);
275 // Clear thread_pool_ field while the threads are suspended.
276 // A mutator in the 'AddSamples' method will check against it.
277 cache = thread_pool_.release();
278 }
279 cache->StopWorkers(self);
280 cache->RemoveAllTasks(self);
281 // We could just suspend all threads, but we know those threads
282 // will finish in a short period, so it's not worth adding a suspend logic
283 // here. Besides, this is only done for shutdown.
284 cache->Wait(self, false, false);
285 delete cache;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800286 }
287}
288
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000289void Jit::StartProfileSaver(const std::string& filename,
Calin Juravlec90bc922016-02-24 10:13:09 +0000290 const std::vector<std::string>& code_paths,
291 const std::string& foreign_dex_profile_path,
292 const std::string& app_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000293 if (save_profiling_info_) {
Calin Juravlec90bc922016-02-24 10:13:09 +0000294 ProfileSaver::Start(filename, code_cache_.get(), code_paths, foreign_dex_profile_path, app_dir);
Calin Juravle31f2c152015-10-23 17:56:15 +0100295 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000296}
297
298void Jit::StopProfileSaver() {
299 if (save_profiling_info_ && ProfileSaver::IsStarted()) {
300 ProfileSaver::Stop();
Calin Juravle31f2c152015-10-23 17:56:15 +0100301 }
302}
303
Siva Chandra05d24152016-01-05 17:43:17 -0800304bool Jit::JitAtFirstUse() {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100305 return HotMethodThreshold() == 0;
Siva Chandra05d24152016-01-05 17:43:17 -0800306}
307
Nicolas Geoffray35122442016-03-02 12:05:30 +0000308bool Jit::CanInvokeCompiledCode(ArtMethod* method) {
309 return code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode());
310}
311
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800312Jit::~Jit() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000313 DCHECK(!save_profiling_info_ || !ProfileSaver::IsStarted());
Mathieu Chartiera4885cb2015-03-09 15:38:54 -0700314 if (dump_info_on_shutdown_) {
315 DumpInfo(LOG(INFO));
316 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800317 DeleteThreadPool();
318 if (jit_compiler_handle_ != nullptr) {
319 jit_unload_(jit_compiler_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700320 jit_compiler_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800321 }
322 if (jit_library_handle_ != nullptr) {
323 dlclose(jit_library_handle_);
Mathieu Chartier72918ea2016-03-24 11:07:06 -0700324 jit_library_handle_ = nullptr;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800325 }
326}
327
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000328void Jit::NewTypeLoadedIfUsingJit(mirror::Class* type) {
329 jit::Jit* jit = Runtime::Current()->GetJit();
330 if (jit != nullptr && jit->generate_debug_info_) {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000331 DCHECK(jit->jit_types_loaded_ != nullptr);
332 jit->jit_types_loaded_(jit->jit_compiler_handle_, &type, 1);
333 }
334}
335
336void Jit::DumpTypeInfoForLoadedTypes(ClassLinker* linker) {
337 struct CollectClasses : public ClassVisitor {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800338 bool operator()(mirror::Class* klass) override {
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000339 classes_.push_back(klass);
340 return true;
341 }
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800342 std::vector<mirror::Class*> classes_;
Tamas Berghammerfffbee42016-01-15 13:09:34 +0000343 };
344
345 if (generate_debug_info_) {
346 ScopedObjectAccess so(Thread::Current());
347
348 CollectClasses visitor;
349 linker->VisitClasses(&visitor);
350 jit_types_loaded_(jit_compiler_handle_, visitor.classes_.data(), visitor.classes_.size());
Tamas Berghammer160e6df2016-01-05 14:29:02 +0000351 }
352}
353
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000354extern "C" void art_quick_osr_stub(void** stack,
355 uint32_t stack_size_in_bytes,
356 const uint8_t* native_pc,
357 JValue* result,
358 const char* shorty,
359 Thread* self);
360
361bool Jit::MaybeDoOnStackReplacement(Thread* thread,
362 ArtMethod* method,
363 uint32_t dex_pc,
364 int32_t dex_pc_offset,
365 JValue* result) {
Nicolas Geoffraye8662132016-02-15 10:00:42 +0000366 if (!kEnableOnStackReplacement) {
367 return false;
368 }
369
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000370 Jit* jit = Runtime::Current()->GetJit();
371 if (jit == nullptr) {
372 return false;
373 }
374
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000375 if (UNLIKELY(__builtin_frame_address(0) < thread->GetStackEnd())) {
376 // Don't attempt to do an OSR if we are close to the stack limit. Since
377 // the interpreter frames are still on stack, OSR has the potential
378 // to stack overflow even for a simple loop.
379 // b/27094810.
380 return false;
381 }
382
Nicolas Geoffrayd9bc4332016-02-05 23:32:25 +0000383 // Get the actual Java method if this method is from a proxy class. The compiler
384 // and the JIT code cache do not expect methods from proxy classes.
385 method = method->GetInterfaceMethodIfProxy(sizeof(void*));
386
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000387 // Cheap check if the method has been compiled already. That's an indicator that we should
388 // osr into it.
389 if (!jit->GetCodeCache()->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
390 return false;
391 }
392
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000393 // Fetch some data before looking up for an OSR method. We don't want thread
394 // suspension once we hold an OSR method, as the JIT code cache could delete the OSR
395 // method while we are being suspended.
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000396 const size_t number_of_vregs = method->GetCodeItem()->registers_size_;
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000397 const char* shorty = method->GetShorty();
398 std::string method_name(VLOG_IS_ON(jit) ? PrettyMethod(method) : "");
399 void** memory = nullptr;
400 size_t frame_size = 0;
401 ShadowFrame* shadow_frame = nullptr;
402 const uint8_t* native_pc = nullptr;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000403
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000404 {
405 ScopedAssertNoThreadSuspension sts(thread, "Holding OSR method");
406 const OatQuickMethodHeader* osr_method = jit->GetCodeCache()->LookupOsrMethodHeader(method);
407 if (osr_method == nullptr) {
408 // No osr method yet, just return to the interpreter.
409 return false;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000410 }
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000411
412 CodeInfo code_info = osr_method->GetOptimizedCodeInfo();
David Srbecky09ed0982016-02-12 21:58:43 +0000413 CodeInfoEncoding encoding = code_info.ExtractEncoding();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000414
415 // Find stack map starting at the target dex_pc.
416 StackMap stack_map = code_info.GetOsrStackMapForDexPc(dex_pc + dex_pc_offset, encoding);
417 if (!stack_map.IsValid()) {
418 // There is no OSR stack map for this dex pc offset. Just return to the interpreter in the
419 // hope that the next branch has one.
420 return false;
421 }
422
423 // We found a stack map, now fill the frame with dex register values from the interpreter's
424 // shadow frame.
425 DexRegisterMap vreg_map =
426 code_info.GetDexRegisterMapOf(stack_map, encoding, number_of_vregs);
427
428 frame_size = osr_method->GetFrameSizeInBytes();
429
430 // Allocate memory to put shadow frame values. The osr stub will copy that memory to
431 // stack.
432 // Note that we could pass the shadow frame to the stub, and let it copy the values there,
433 // but that is engineering complexity not worth the effort for something like OSR.
434 memory = reinterpret_cast<void**>(malloc(frame_size));
435 CHECK(memory != nullptr);
436 memset(memory, 0, frame_size);
437
438 // Art ABI: ArtMethod is at the bottom of the stack.
439 memory[0] = method;
440
441 shadow_frame = thread->PopShadowFrame();
442 if (!vreg_map.IsValid()) {
443 // If we don't have a dex register map, then there are no live dex registers at
444 // this dex pc.
445 } else {
446 for (uint16_t vreg = 0; vreg < number_of_vregs; ++vreg) {
447 DexRegisterLocation::Kind location =
448 vreg_map.GetLocationKind(vreg, number_of_vregs, code_info, encoding);
449 if (location == DexRegisterLocation::Kind::kNone) {
Nicolas Geoffrayc0b27962016-02-16 12:06:05 +0000450 // Dex register is dead or uninitialized.
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000451 continue;
452 }
453
454 if (location == DexRegisterLocation::Kind::kConstant) {
455 // We skip constants because the compiled code knows how to handle them.
456 continue;
457 }
458
David Srbecky7dc11782016-02-25 13:23:56 +0000459 DCHECK_EQ(location, DexRegisterLocation::Kind::kInStack);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000460
461 int32_t vreg_value = shadow_frame->GetVReg(vreg);
462 int32_t slot_offset = vreg_map.GetStackOffsetInBytes(vreg,
463 number_of_vregs,
464 code_info,
465 encoding);
466 DCHECK_LT(slot_offset, static_cast<int32_t>(frame_size));
467 DCHECK_GT(slot_offset, 0);
468 (reinterpret_cast<int32_t*>(memory))[slot_offset / sizeof(int32_t)] = vreg_value;
469 }
470 }
471
David Srbecky09ed0982016-02-12 21:58:43 +0000472 native_pc = stack_map.GetNativePcOffset(encoding.stack_map_encoding) +
473 osr_method->GetEntryPoint();
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000474 VLOG(jit) << "Jumping to "
475 << method_name
476 << "@"
477 << std::hex << reinterpret_cast<uintptr_t>(native_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000478 }
479
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000480 {
481 ManagedStack fragment;
482 thread->PushManagedStackFragment(&fragment);
483 (*art_quick_osr_stub)(memory,
484 frame_size,
485 native_pc,
486 result,
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000487 shorty,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000488 thread);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000489
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000490 if (UNLIKELY(thread->GetException() == Thread::GetDeoptimizationException())) {
491 thread->DeoptimizeWithDeoptimizationException(result);
492 }
493 thread->PopManagedStackFragment(fragment);
494 }
495 free(memory);
496 thread->PushShadowFrame(shadow_frame);
Nicolas Geoffrayd186dd82016-02-16 10:03:44 +0000497 VLOG(jit) << "Done running OSR code for " << method_name;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000498 return true;
499}
500
Nicolas Geoffraya4f81542016-03-08 16:57:48 +0000501void Jit::AddMemoryUsage(ArtMethod* method, size_t bytes) {
502 if (bytes > 4 * MB) {
503 LOG(INFO) << "Compiler allocated "
504 << PrettySize(bytes)
505 << " to compile "
506 << PrettyMethod(method);
507 }
508 MutexLock mu(Thread::Current(), lock_);
509 memory_use_.AddValue(bytes);
510}
511
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100512class JitCompileTask FINAL : public Task {
513 public:
514 enum TaskKind {
515 kAllocateProfile,
516 kCompile,
517 kCompileOsr
518 };
519
520 JitCompileTask(ArtMethod* method, TaskKind kind) : method_(method), kind_(kind) {
521 ScopedObjectAccess soa(Thread::Current());
522 // Add a global ref to the class to prevent class unloading until compilation is done.
523 klass_ = soa.Vm()->AddGlobalRef(soa.Self(), method_->GetDeclaringClass());
524 CHECK(klass_ != nullptr);
525 }
526
527 ~JitCompileTask() {
528 ScopedObjectAccess soa(Thread::Current());
529 soa.Vm()->DeleteGlobalRef(soa.Self(), klass_);
530 }
531
532 void Run(Thread* self) OVERRIDE {
533 ScopedObjectAccess soa(self);
534 if (kind_ == kCompile) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100535 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100536 } else if (kind_ == kCompileOsr) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100537 Runtime::Current()->GetJit()->CompileMethod(method_, self, /* osr */ true);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100538 } else {
539 DCHECK(kind_ == kAllocateProfile);
540 if (ProfilingInfo::Create(self, method_, /* retry_allocation */ true)) {
541 VLOG(jit) << "Start profiling " << PrettyMethod(method_);
542 }
543 }
544 }
545
546 void Finalize() OVERRIDE {
547 delete this;
548 }
549
550 private:
551 ArtMethod* const method_;
552 const TaskKind kind_;
553 jobject klass_;
554
555 DISALLOW_IMPLICIT_CONSTRUCTORS(JitCompileTask);
556};
557
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100558void Jit::AddSamples(Thread* self, ArtMethod* method, uint16_t count, bool with_backedges) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100559 if (thread_pool_ == nullptr) {
560 // Should only see this when shutting down.
561 DCHECK(Runtime::Current()->IsShuttingDown(self));
562 return;
563 }
564
565 if (method->IsClassInitializer() || method->IsNative()) {
566 // We do not want to compile such methods.
567 return;
568 }
569 DCHECK(thread_pool_ != nullptr);
570 DCHECK_GT(warm_method_threshold_, 0);
571 DCHECK_GT(hot_method_threshold_, warm_method_threshold_);
572 DCHECK_GT(osr_method_threshold_, hot_method_threshold_);
573 DCHECK_GE(priority_thread_weight_, 1);
574 DCHECK_LE(priority_thread_weight_, hot_method_threshold_);
575
576 int32_t starting_count = method->GetCounter();
577 if (Jit::ShouldUsePriorityThreadWeight()) {
578 count *= priority_thread_weight_;
579 }
580 int32_t new_count = starting_count + count; // int32 here to avoid wrap-around;
581 if (starting_count < warm_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100582 if ((new_count >= warm_method_threshold_) &&
583 (method->GetProfilingInfo(sizeof(void*)) == nullptr)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100584 bool success = ProfilingInfo::Create(self, method, /* retry_allocation */ false);
585 if (success) {
586 VLOG(jit) << "Start profiling " << PrettyMethod(method);
587 }
588
589 if (thread_pool_ == nullptr) {
590 // Calling ProfilingInfo::Create might put us in a suspended state, which could
591 // lead to the thread pool being deleted when we are shutting down.
592 DCHECK(Runtime::Current()->IsShuttingDown(self));
593 return;
594 }
595
596 if (!success) {
597 // We failed allocating. Instead of doing the collection on the Java thread, we push
598 // an allocation to a compiler thread, that will do the collection.
599 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kAllocateProfile));
600 }
601 }
602 // Avoid jumping more than one state at a time.
603 new_count = std::min(new_count, hot_method_threshold_ - 1);
604 } else if (starting_count < hot_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100605 if ((new_count >= hot_method_threshold_) &&
606 !code_cache_->ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100607 DCHECK(thread_pool_ != nullptr);
608 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompile));
609 }
610 // Avoid jumping more than one state at a time.
611 new_count = std::min(new_count, osr_method_threshold_ - 1);
612 } else if (starting_count < osr_method_threshold_) {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100613 if (!with_backedges) {
614 // If the samples don't contain any back edge, we don't increment the hotness.
615 return;
616 }
617 if ((new_count >= osr_method_threshold_) && !code_cache_->IsOsrCompiled(method)) {
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100618 DCHECK(thread_pool_ != nullptr);
619 thread_pool_->AddTask(self, new JitCompileTask(method, JitCompileTask::kCompileOsr));
620 }
621 }
622 // Update hotness counter
623 method->SetCounter(new_count);
624}
625
626void Jit::MethodEntered(Thread* thread, ArtMethod* method) {
627 if (UNLIKELY(Runtime::Current()->GetJit()->JitAtFirstUse())) {
628 // The compiler requires a ProfilingInfo object.
629 ProfilingInfo::Create(thread, method, /* retry_allocation */ true);
630 JitCompileTask compile_task(method, JitCompileTask::kCompile);
631 compile_task.Run(thread);
632 return;
633 }
634
635 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
636 // Update the entrypoint if the ProfilingInfo has one. The interpreter will call it
637 // instead of interpreting the method.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100638 if ((profiling_info != nullptr) && (profiling_info->GetSavedEntryPoint() != nullptr)) {
639 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
640 method, profiling_info->GetSavedEntryPoint());
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100641 } else {
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100642 AddSamples(thread, method, 1, /* with_backedges */false);
Nicolas Geoffray274fe4a2016-04-12 16:33:24 +0100643 }
644}
645
646void Jit::InvokeVirtualOrInterface(Thread* thread,
647 mirror::Object* this_object,
648 ArtMethod* caller,
649 uint32_t dex_pc,
650 ArtMethod* callee ATTRIBUTE_UNUSED) {
651 ScopedAssertNoThreadSuspension ants(thread, __FUNCTION__);
652 DCHECK(this_object != nullptr);
653 ProfilingInfo* info = caller->GetProfilingInfo(sizeof(void*));
654 if (info != nullptr) {
655 // Since the instrumentation is marked from the declaring class we need to mark the card so
656 // that mod-union tables and card rescanning know about the update.
657 Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(caller->GetDeclaringClass());
658 info->AddInvokeInfo(dex_pc, this_object->GetClass());
659 }
660}
661
662void Jit::WaitForCompilationToFinish(Thread* self) {
663 if (thread_pool_ != nullptr) {
664 thread_pool_->Wait(self, false, false);
665 }
666}
667
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800668} // namespace jit
669} // namespace art