blob: 36699738c06f954060e74f84cb231f77c6df6a8d [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_code_cache.h"
18
19#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
Orion Hodson1d3fd082018-09-28 09:38:35 +010022
Andreas Gampe5629d2d2017-05-15 16:28:13 -070023#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070025#include "base/enums.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070026#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080027#include "base/logging.h" // For VLOG.
Orion Hodson563ada22018-09-04 11:28:31 +010028#include "base/membarrier.h"
Orion Hodson1d3fd082018-09-28 09:38:35 +010029#include "base/memfd.h"
David Sehr79e26072018-04-06 17:58:50 -070030#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010034#include "base/time_utils.h"
Orion Hodsonf2331362018-07-11 15:14:10 +010035#include "base/utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070036#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000037#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070039#include "dex/method_reference.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010040#include "entrypoints/runtime_asm_entrypoints.h"
41#include "gc/accounting/bitmap-inl.h"
Andreas Gampe88dbad32018-06-26 19:54:12 -070042#include "gc/allocator/dlmalloc.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010043#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000044#include "handle.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070045#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070046#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000047#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000048#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010049#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010050#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070052#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070053#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070054#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070055#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070056#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000057#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010058#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080059
60namespace art {
61namespace jit {
62
Nicolas Geoffray933330a2016-03-16 14:20:06 +000063static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
64static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
65
Vladimir Marko2196c652017-11-30 16:16:07 +000066class JitCodeCache::JniStubKey {
67 public:
68 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
69 : shorty_(method->GetShorty()),
70 is_static_(method->IsStatic()),
71 is_fast_native_(method->IsFastNative()),
72 is_critical_native_(method->IsCriticalNative()),
73 is_synchronized_(method->IsSynchronized()) {
74 DCHECK(!(is_fast_native_ && is_critical_native_));
75 }
76
77 bool operator<(const JniStubKey& rhs) const {
78 if (is_static_ != rhs.is_static_) {
79 return rhs.is_static_;
80 }
81 if (is_synchronized_ != rhs.is_synchronized_) {
82 return rhs.is_synchronized_;
83 }
84 if (is_fast_native_ != rhs.is_fast_native_) {
85 return rhs.is_fast_native_;
86 }
87 if (is_critical_native_ != rhs.is_critical_native_) {
88 return rhs.is_critical_native_;
89 }
90 return strcmp(shorty_, rhs.shorty_) < 0;
91 }
92
93 // Update the shorty to point to another method's shorty. Call this function when removing
94 // the method that references the old shorty from JniCodeData and not removing the entire
95 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
96 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
97 const char* shorty = method->GetShorty();
98 DCHECK_STREQ(shorty_, shorty);
99 shorty_ = shorty;
100 }
101
102 private:
103 // The shorty points to a DexFile data and may need to change
104 // to point to the same shorty in a different DexFile.
105 mutable const char* shorty_;
106
107 const bool is_static_;
108 const bool is_fast_native_;
109 const bool is_critical_native_;
110 const bool is_synchronized_;
111};
112
113class JitCodeCache::JniStubData {
114 public:
115 JniStubData() : code_(nullptr), methods_() {}
116
117 void SetCode(const void* code) {
118 DCHECK(code != nullptr);
119 code_ = code;
120 }
121
122 const void* GetCode() const {
123 return code_;
124 }
125
126 bool IsCompiled() const {
127 return GetCode() != nullptr;
128 }
129
130 void AddMethod(ArtMethod* method) {
131 if (!ContainsElement(methods_, method)) {
132 methods_.push_back(method);
133 }
134 }
135
136 const std::vector<ArtMethod*>& GetMethods() const {
137 return methods_;
138 }
139
140 void RemoveMethodsIn(const LinearAlloc& alloc) {
141 auto kept_end = std::remove_if(
142 methods_.begin(),
143 methods_.end(),
144 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
145 methods_.erase(kept_end, methods_.end());
146 }
147
148 bool RemoveMethod(ArtMethod* method) {
149 auto it = std::find(methods_.begin(), methods_.end(), method);
150 if (it != methods_.end()) {
151 methods_.erase(it);
152 return true;
153 } else {
154 return false;
155 }
156 }
157
158 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
159 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
160 }
161
162 private:
163 const void* code_;
164 std::vector<ArtMethod*> methods_;
165};
166
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000167JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
168 bool rwx_memory_allowed,
169 bool is_zygote,
170 std::string* error_msg) {
171 // Register for membarrier expedited sync core if JIT will be generating code.
172 if (!used_only_for_profile_data) {
173 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
174 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
175 // flushed and it's used when adding code to the JIT. The memory used by the new code may
176 // have just been released and, in theory, the old code could still be in a pipeline.
177 VLOG(jit) << "Kernel does not support membarrier sync-core";
178 }
179 }
180
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100181 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000182 // Check whether the provided max capacity in options is below 1GB.
183 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
184 // We need to have 32 bit offsets from method headers in code cache which point to things
185 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
186 // Ensure we're below 1 GB to be safe.
187 if (max_capacity > 1 * GB) {
188 std::ostringstream oss;
189 oss << "Maxium code cache capacity is limited to 1 GB, "
190 << PrettySize(max_capacity) << " is too big";
191 *error_msg = oss.str();
192 return nullptr;
193 }
194
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100195 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100196 JitMemoryRegion region;
197 if (!region.Initialize(initial_capacity,
198 max_capacity,
199 rwx_memory_allowed,
200 is_zygote,
201 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000202 return nullptr;
203 }
204
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100205 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
206 if (is_zygote) {
207 // Zygote should never collect code to share the memory with the children.
208 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000209 jit_code_cache->shared_region_ = std::move(region);
210 } else {
211 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100212 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000213
214 VLOG(jit) << "Created jit code cache: initial capacity="
215 << PrettySize(initial_capacity)
216 << ", maximum capacity="
217 << PrettySize(max_capacity);
218
219 return jit_code_cache.release();
220}
221
222JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100223 : is_weak_access_enabled_(true),
224 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100225 zygote_map_(&shared_region_),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100226 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100227 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000228 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100229 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000230 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000231 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000232 number_of_collections_(0),
233 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
234 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100235 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800236}
237
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000238JitCodeCache::~JitCodeCache() {}
239
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100240bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100241 return private_region_.IsInExecSpace(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800242}
243
Alex Light2d441b12018-06-08 15:33:21 -0700244bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
245 ScopedObjectAccess soa(art::Thread::Current());
246 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
247 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
248 return true;
249 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
250 return FindCompiledCodeForInstrumentation(method) != nullptr;
251 }
252 return false;
253}
254
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000255bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100256 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000257 if (UNLIKELY(method->IsNative())) {
258 auto it = jni_stubs_map_.find(JniStubKey(method));
259 if (it != jni_stubs_map_.end() &&
260 it->second.IsCompiled() &&
261 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000262 return true;
263 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000264 } else {
265 for (const auto& it : method_code_map_) {
266 if (it.second == method) {
267 return true;
268 }
269 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100270 if (zygote_map_.ContainsMethod(method)) {
271 return true;
272 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000273 }
274 return false;
275}
276
Vladimir Marko2196c652017-11-30 16:16:07 +0000277const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
278 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100279 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000280 auto it = jni_stubs_map_.find(JniStubKey(method));
281 if (it != jni_stubs_map_.end()) {
282 JniStubData& data = it->second;
283 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
284 return data.GetCode();
285 }
286 }
287 return nullptr;
288}
289
Alex Light2d441b12018-06-08 15:33:21 -0700290const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700291 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
292 // find the instrumentation entrypoint.
293 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700294 return nullptr;
295 }
296 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
297 if (info == nullptr) {
298 return nullptr;
299 }
300 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
301 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
302 // nullptr.
303 return info->GetSavedEntryPoint();
304}
305
Nicolas Geoffray32384402019-07-17 20:06:44 +0100306const void* JitCodeCache::GetSavedEntryPointOfPreCompiledMethod(ArtMethod* method) {
307 if (Runtime::Current()->IsUsingApexBootImageLocation() && method->IsPreCompiled()) {
308 if (method->GetDeclaringClass()->GetClassLoader() == nullptr) {
309 return zygote_map_.GetCodeFor(method);
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100310 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100311 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
312 auto it = saved_compiled_methods_map_.find(method);
313 if (it != saved_compiled_methods_map_.end()) {
314 return it->second;
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100315 }
Nicolas Geoffray32384402019-07-17 20:06:44 +0100316 return nullptr;
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100317 }
318 }
319 return nullptr;
320}
321
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100322uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100323 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100324 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000326 size_t code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100327 const uint8_t* stack_map,
328 size_t stack_map_size,
329 uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100330 const std::vector<Handle<mirror::Object>>& roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100331 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700332 bool has_should_deoptimize_flag,
333 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100334 uint8_t* result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100335 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100336 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100337 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000338 code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100339 stack_map,
340 stack_map_size,
341 roots_data,
Mingyao Yang063fc772016-08-02 11:02:54 -0700342 roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100343 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700344 has_should_deoptimize_flag,
345 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100346 if (result == nullptr) {
347 // Retry.
348 GarbageCollectCache(self);
349 result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100350 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100351 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100352 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000353 code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100354 stack_map,
355 stack_map_size,
356 roots_data,
Mingyao Yang063fc772016-08-02 11:02:54 -0700357 roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100358 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700359 has_should_deoptimize_flag,
360 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100361 }
362 return result;
363}
364
365bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
366 bool in_collection = false;
367 while (collection_in_progress_) {
368 in_collection = true;
369 lock_cond_.Wait(self);
370 }
371 return in_collection;
372}
373
374static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodsone764f382019-06-27 12:56:48 +0100375 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100376 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
377}
378
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000379static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
380 // The length of the table is stored just before the stack map (and therefore at the end of
381 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
382 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
383}
384
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000385static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots,
386 bool is_shared_region)
Alex Light3e36a9c2018-06-19 09:45:05 -0700387 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
388 if (!kIsDebugBuild) {
389 return;
390 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700391 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100392 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700393 // Ensure the string is strongly interned. b/32995596
394 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100395 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700396 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
397 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
398 }
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000399 // Ensure that we don't put movable objects in the shared region.
400 if (is_shared_region) {
401 CHECK(!Runtime::Current()->GetHeap()->IsMovableObject(object.Get()));
402 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700403 }
404}
405
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100406static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000407 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
408 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
409 uint32_t roots = GetNumberOfRoots(data);
410 if (number_of_roots != nullptr) {
411 *number_of_roots = roots;
412 }
413 return data - ComputeRootTableSize(roots);
414}
415
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100416// Use a sentinel for marking entries in the JIT table that have been cleared.
417// This helps diagnosing in case the compiled code tries to wrongly access such
418// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700419static mirror::Class* const weak_sentinel =
420 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100421
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000422// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100423static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
424 IsMarkedVisitor* visitor,
425 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000426 REQUIRES_SHARED(Locks::mutator_lock_) {
427 // This does not need a read barrier because this is called by GC.
428 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100429 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700430 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000431 // Look at the classloader of the class to know if it has been unloaded.
432 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000433 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000434 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000435 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000436 // The class loader is live, update the entry if the class has moved.
437 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
438 // Note that new_object can be null for CMS and newly allocated objects.
439 if (new_cls != nullptr && new_cls != cls) {
440 *root_ptr = GcRoot<mirror::Class>(new_cls);
441 }
442 } else {
443 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100444 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000445 }
446 }
447}
448
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000449void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100450 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000451 for (const auto& entry : method_code_map_) {
452 uint32_t number_of_roots = 0;
453 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
454 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
455 for (uint32_t i = 0; i < number_of_roots; ++i) {
456 // This does not need a read barrier because this is called by GC.
457 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100458 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000459 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000460 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000461 mirror::Object* new_object = visitor->IsMarked(object);
462 // We know the string is marked because it's a strongly-interned string that
463 // is always alive. The IsMarked implementation of the CMS collector returns
464 // null for newly allocated objects, but we know those haven't moved. Therefore,
465 // only update the entry if we get a different non-null string.
466 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
467 // out of the weak access/creation pause. b/32167580
468 if (new_object != nullptr && new_object != object) {
469 DCHECK(new_object->IsString());
470 roots[i] = GcRoot<mirror::Object>(new_object);
471 }
472 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100473 ProcessWeakClass(
474 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000475 }
476 }
477 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000478 // Walk over inline caches to clear entries containing unloaded classes.
479 for (ProfilingInfo* info : profiling_infos_) {
480 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
481 InlineCache* cache = &info->cache_[i];
482 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100483 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000484 }
485 }
486 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000487}
488
Orion Hodson607624f2018-05-11 10:10:46 +0100489void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000490 if (IsInZygoteExecSpace(code_ptr)) {
491 // No need to free, this is shared memory.
492 return;
493 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100494 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000495 // Notify native debugger that we are about to remove the code.
496 // It does nothing if we are not using native debugger.
David Srbeckyafc60cd2018-12-05 11:59:31 +0000497 RemoveNativeDebugInfoForJit(Thread::Current(), code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000498 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100499 private_region_.FreeData(GetRootTable(code_ptr));
Vladimir Marko2196c652017-11-30 16:16:07 +0000500 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100501
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100502 private_region_.FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100503}
504
Mingyao Yang063fc772016-08-02 11:02:54 -0700505void JitCodeCache::FreeAllMethodHeaders(
506 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700507 // We need to remove entries in method_headers from CHA dependencies
508 // first since once we do FreeCode() below, the memory can be reused
509 // so it's possible for the same method_header to start representing
510 // different compile code.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100511 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000512 {
513 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
514 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
515 ->RemoveDependentsWithMethodHeaders(method_headers);
516 }
517
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100518 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700519 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100520 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700521 }
522}
523
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100524void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800525 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700526 // We use a set to first collect all method_headers whose code need to be
527 // removed. We need to free the underlying code after we remove CHA dependencies
528 // for entries in this set. And it's more efficient to iterate through
529 // the CHA dependency map just once with an unordered_set.
530 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000531 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100532 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700533 // We do not check if a code cache GC is in progress, as this method comes
534 // with the classlinker_classes_lock_ held, and suspending ourselves could
535 // lead to a deadlock.
536 {
Vladimir Marko2196c652017-11-30 16:16:07 +0000537 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
538 it->second.RemoveMethodsIn(alloc);
539 if (it->second.GetMethods().empty()) {
540 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
541 it = jni_stubs_map_.erase(it);
542 } else {
543 it->first.UpdateShorty(it->second.GetMethods().front());
544 ++it;
545 }
546 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700547 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
548 if (alloc.ContainsUnsafe(it->second)) {
549 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
550 it = method_code_map_.erase(it);
551 } else {
552 ++it;
553 }
554 }
555 }
556 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
557 if (alloc.ContainsUnsafe(it->first)) {
558 // Note that the code has already been pushed to method_headers in the loop
559 // above and is going to be removed in FreeCode() below.
560 it = osr_code_map_.erase(it);
561 } else {
562 ++it;
563 }
564 }
565 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
566 ProfilingInfo* info = *it;
567 if (alloc.ContainsUnsafe(info->GetMethod())) {
568 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100569 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700570 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000571 } else {
572 ++it;
573 }
574 }
575 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700576 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100577}
578
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000579bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
580 return kUseReadBarrier
581 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000582 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000583}
584
585void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
586 if (IsWeakAccessEnabled(self)) {
587 return;
588 }
589 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100590 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000591 while (!IsWeakAccessEnabled(self)) {
592 inline_cache_cond_.Wait(self);
593 }
594}
595
596void JitCodeCache::BroadcastForInlineCacheAccess() {
597 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100598 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000599 inline_cache_cond_.Broadcast(self);
600}
601
602void JitCodeCache::AllowInlineCacheAccess() {
603 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000604 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000605 BroadcastForInlineCacheAccess();
606}
607
608void JitCodeCache::DisallowInlineCacheAccess() {
609 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000610 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000611}
612
613void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
614 Handle<mirror::ObjectArray<mirror::Class>> array) {
615 WaitUntilInlineCacheAccessible(Thread::Current());
616 // Note that we don't need to lock `lock_` here, the compiler calling
617 // this method has already ensured the inline cache will not be deleted.
618 for (size_t in_cache = 0, in_array = 0;
619 in_cache < InlineCache::kIndividualCacheSize;
620 ++in_cache) {
621 mirror::Class* object = ic.classes_[in_cache].Read();
622 if (object != nullptr) {
623 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000624 }
625 }
626}
627
David Srbeckye36e7f22018-11-14 14:21:23 +0000628static void ClearMethodCounter(ArtMethod* method, bool was_warm)
629 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700630 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100631 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700632 }
633 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
634 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100635 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
636 // the warmup threshold is 1.
637 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
638 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700639}
640
Alex Light33b7b5d2018-08-07 19:13:51 +0000641void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
642 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100643 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000644 {
645 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100646 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000647 WaitForPotentialCollectionToComplete(self);
648 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100649 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100650 }
651}
652
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100653uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100654 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100655 ArtMethod* method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100656 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000657 size_t code_size,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100658 const uint8_t* stack_map,
659 size_t stack_map_size,
660 uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100661 const std::vector<Handle<mirror::Object>>& roots,
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100662 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700663 bool has_should_deoptimize_flag,
664 const ArenaSet<ArtMethod*>&
665 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000666 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000667
668 if (!method->IsNative()) {
669 // We need to do this before grabbing the lock_ because it needs to be able to see the string
670 // InternTable. Native methods do not have roots.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +0000671 DCheckRootsAreValid(roots, IsSharedRegion(*region));
Alex Light33b7b5d2018-08-07 19:13:51 +0000672 }
673
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100674 size_t root_table_size = ComputeRootTableSize(roots.size());
675 uint8_t* stack_map_data = roots_data + root_table_size;
676
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100677 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000678 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
679 // finish.
680 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100681 const uint8_t* code_ptr = region->AllocateCode(
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100682 code, code_size, stack_map_data, has_should_deoptimize_flag);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100683 if (code_ptr == nullptr) {
684 return nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100685 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100686 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
687
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100688 // Commit roots and stack maps before updating the entry point.
Orion Hodsonaeb02232019-06-25 14:18:18 +0100689 if (!region->CommitData(roots_data, roots, stack_map, stack_map_size)) {
690 ScopedCodeCacheWrite ccw(*region);
691 uintptr_t allocation = FromCodeToAllocation(code_ptr);
692 region->FreeCode(reinterpret_cast<uint8_t*>(allocation));
693 return nullptr;
694 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100695
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100696 number_of_compilations_++;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100697
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000698 // We need to update the entry point in the runnable state for the instrumentation.
699 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000700 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
701 // compiled code is considered invalidated by some class linking, but below we still make the
702 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
703 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700704 MutexLock cha_mu(self, *Locks::cha_lock_);
705 bool single_impl_still_valid = true;
706 for (ArtMethod* single_impl : cha_single_implementation_list) {
707 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700708 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
709 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700710 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700711 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700712 break;
713 }
714 }
715
716 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100717 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700718 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
Orion Hodson31492522019-06-18 12:13:49 +0100719 ScopedCodeCacheWrite ccw(*region);
720 uintptr_t allocation = FromCodeToAllocation(code_ptr);
721 region->FreeCode(reinterpret_cast<uint8_t*>(allocation));
Mingyao Yang063fc772016-08-02 11:02:54 -0700722 return nullptr;
723 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000724 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800725 << "Should not be using cha on debuggable apps/runs!";
726
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100727 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700728 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100729 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700730 }
731
Vladimir Marko2196c652017-11-30 16:16:07 +0000732 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000733 auto it = jni_stubs_map_.find(JniStubKey(method));
734 DCHECK(it != jni_stubs_map_.end())
735 << "Entry inserted in NotifyCompilationOf() should be alive.";
736 JniStubData* data = &it->second;
737 DCHECK(ContainsElement(data->GetMethods(), method))
738 << "Entry inserted in NotifyCompilationOf() should contain this method.";
739 data->SetCode(code_ptr);
740 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
741 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100742 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
743 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
744 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000745 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100746 } else {
Nicolas Geoffray32384402019-07-17 20:06:44 +0100747 if (method->IsPreCompiled() && IsSharedRegion(*region)) {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +0100748 zygote_map_.Put(code_ptr, method);
749 } else {
750 method_code_map_.Put(code_ptr, method);
751 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000752 if (osr) {
753 number_of_osr_compilations_++;
754 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100755 } else if (class_linker->IsQuickResolutionStub(
756 method->GetEntryPointFromQuickCompiledCode())) {
757 // This situation currently only occurs in the jit-zygote mode.
David Srbecky3db3d372019-04-17 18:19:17 +0100758 DCHECK(Runtime::Current()->IsUsingApexBootImageLocation());
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100759 DCHECK(!garbage_collect_code_);
Nicolas Geoffray32384402019-07-17 20:06:44 +0100760 DCHECK(method->IsPreCompiled());
761 // The shared region can easily be queried. For the private region, we
762 // use a side map.
763 if (!IsSharedRegion(*region)) {
764 saved_compiled_methods_map_.Put(method, code_ptr);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100765 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000766 } else {
767 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
768 method, method_header->GetEntryPoint());
769 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000770 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000771 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100772 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700773 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000774 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
775 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
776 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700777 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
778 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000779 histogram_code_memory_use_.AddValue(code_size);
780 if (code_size > kCodeSizeLogThreshold) {
781 LOG(INFO) << "JIT allocated "
782 << PrettySize(code_size)
783 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700784 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000785 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000786 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100787
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100788 return reinterpret_cast<uint8_t*>(method_header);
789}
790
791size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100792 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000793 return CodeCacheSizeLocked();
794}
795
Orion Hodsoneced6922017-06-01 10:54:28 +0100796bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000797 // This function is used only for testing and only with non-native methods.
798 CHECK(!method->IsNative());
799
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100800 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100801
Vladimir Marko2196c652017-11-30 16:16:07 +0000802 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
803 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100804
805 if (!in_cache) {
806 return false;
807 }
808
David Srbeckye36e7f22018-11-14 14:21:23 +0000809 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100810 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
811 method, GetQuickToInterpreterBridge());
812 VLOG(jit)
813 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
814 << ArtMethod::PrettyMethod(method) << "@" << method
815 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
816 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
817 return true;
818}
819
Vladimir Marko2196c652017-11-30 16:16:07 +0000820bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
821 if (LIKELY(!method->IsNative())) {
822 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
823 if (info != nullptr) {
824 RemoveElement(profiling_infos_, info);
825 }
826 method->SetProfilingInfo(nullptr);
827 }
828
829 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100830 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000831 if (UNLIKELY(method->IsNative())) {
832 auto it = jni_stubs_map_.find(JniStubKey(method));
833 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
834 in_cache = true;
835 if (it->second.GetMethods().empty()) {
836 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100837 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000838 }
839 jni_stubs_map_.erase(it);
840 } else {
841 it->first.UpdateShorty(it->second.GetMethods().front());
842 }
843 }
844 } else {
845 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
846 if (it->second == method) {
847 in_cache = true;
848 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100849 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000850 }
851 it = method_code_map_.erase(it);
852 } else {
853 ++it;
854 }
855 }
856
857 auto osr_it = osr_code_map_.find(method);
858 if (osr_it != osr_code_map_.end()) {
859 osr_code_map_.erase(osr_it);
860 }
861 }
862
863 return in_cache;
864}
865
Alex Lightdba61482016-12-21 08:20:29 -0800866// This notifies the code cache that the given method has been redefined and that it should remove
867// any cached information it has on the method. All threads must be suspended before calling this
868// method. The compiled code for the method (if there is any) must not be in any threads call stack.
869void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100870 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700871 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800872}
873
874// This invalidates old_method. Once this function returns one can no longer use old_method to
875// execute code unless it is fixed up. This fixup will happen later in the process of installing a
876// class redefinition.
877// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
878// shouldn't be used since it is no longer logically in the jit code cache.
879// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
880void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100881 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000882 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000883 // Update methods in jni_stubs_map_.
884 for (auto& entry : jni_stubs_map_) {
885 JniStubData& data = entry.second;
886 data.MoveObsoleteMethod(old_method, new_method);
887 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000888 return;
889 }
Alex Lightdba61482016-12-21 08:20:29 -0800890 // Update ProfilingInfo to the new one and remove it from the old_method.
891 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
892 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
893 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
894 old_method->SetProfilingInfo(nullptr);
895 // Since the JIT should be paused and all threads suspended by the time this is called these
896 // checks should always pass.
897 DCHECK(!info->IsInUseByCompiler());
898 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700899 // Get rid of the old saved entrypoint if it is there.
900 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800901 info->method_ = new_method;
902 }
903 // Update method_code_map_ to point to the new method.
904 for (auto& it : method_code_map_) {
905 if (it.second == old_method) {
906 it.second = new_method;
907 }
908 }
909 // Update osr_code_map_ to point to the new method.
910 auto code_map = osr_code_map_.find(old_method);
911 if (code_map != osr_code_map_.end()) {
912 osr_code_map_.Put(new_method, code_map->second);
913 osr_code_map_.erase(old_method);
914 }
915}
916
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000917void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100918 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayaf213cc2019-07-01 10:50:55 +0100919 for (const auto& it : method_code_map_) {
920 ArtMethod* method = it.second;
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000921 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
922 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
923 }
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000924 }
925}
926
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000927size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100928 return private_region_.GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100929}
930
931size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100932 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000933 return DataCacheSizeLocked();
934}
935
936size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100937 return private_region_.GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800938}
939
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000940void JitCodeCache::ClearData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100941 JitMemoryRegion* region,
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000942 uint8_t* roots_data) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100943 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100944 region->FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000945}
946
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100947uint8_t* JitCodeCache::ReserveData(Thread* self,
948 JitMemoryRegion* region,
949 size_t stack_map_size,
950 size_t number_of_roots,
951 ArtMethod* method) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000952 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +0100953 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100954 uint8_t* result = nullptr;
955
956 {
957 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100958 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100959 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100960 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100961 }
962
963 if (result == nullptr) {
964 // Retry.
965 GarbageCollectCache(self);
966 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100967 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100968 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100969 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100970 }
971
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100972 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000973 histogram_stack_map_memory_use_.AddValue(size);
974 if (size > kStackMapSizeLogThreshold) {
975 LOG(INFO) << "JIT allocated "
976 << PrettySize(size)
977 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700978 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800979 }
Nicolas Geoffray00a37ff2019-06-20 14:27:22 +0100980 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800981}
982
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100983class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100984 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +0000985 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
986 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100987
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100988 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800989 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100990 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +0000991 StackVisitor::WalkStack(
992 [&](const art::StackVisitor* stack_visitor) {
993 const OatQuickMethodHeader* method_header =
994 stack_visitor->GetCurrentOatQuickMethodHeader();
995 if (method_header == nullptr) {
996 return true;
997 }
998 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +0000999 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001000 // Use the atomic set version, as multiple threads are executing this code.
1001 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1002 }
1003 return true;
1004 },
1005 thread,
1006 /* context= */ nullptr,
1007 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1008
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001009 if (kIsDebugBuild) {
1010 // The stack walking code queries the side instrumentation stack if it
1011 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1012 // must have been seen. We sanity check this below.
1013 for (const instrumentation::InstrumentationStackFrame& frame
1014 : *thread->GetInstrumentationStack()) {
1015 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1016 // its stack frame, it is not the method owning return_pc_. We just pass null to
1017 // LookupMethodHeader: the method is only checked against in debug builds.
1018 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001019 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001020 if (method_header != nullptr) {
1021 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001022 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001023 }
1024 }
1025 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001026 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001027 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001028
1029 private:
1030 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001031 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001032 Barrier* const barrier_;
1033};
1034
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001035void JitCodeCache::NotifyCollectionDone(Thread* self) {
1036 collection_in_progress_ = false;
1037 lock_cond_.Broadcast(self);
1038}
1039
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001040void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1041 Barrier barrier(0);
1042 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001043 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001044 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1045 // Now that we have run our checkpoint, move to a suspended state and wait
1046 // for other threads to run the checkpoint.
1047 ScopedThreadSuspension sts(self, kSuspended);
1048 if (threads_running_checkpoint != 0) {
1049 barrier.Increment(self, threads_running_checkpoint);
1050 }
1051}
1052
Nicolas Geoffray35122442016-03-02 12:05:30 +00001053bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001054 if (private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001055 // Always do a full collection when the code cache is full.
1056 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001057 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001058 // Always do partial collection when the code cache size is below the reserved
1059 // capacity.
1060 return false;
1061 } else if (last_collection_increased_code_cache_) {
1062 // This time do a full collection.
1063 return true;
1064 } else {
1065 // This time do a partial collection.
1066 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001067 }
1068}
1069
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001070void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001071 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001072 // Wait for an existing collection, or let everyone know we are starting one.
1073 {
1074 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001075 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001076 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001077 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001078 return;
1079 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001080 return;
1081 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001082 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001083 live_bitmap_.reset(CodeCacheBitmap::Create(
1084 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001085 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1086 reinterpret_cast<uintptr_t>(
1087 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001088 collection_in_progress_ = true;
1089 }
1090 }
1091
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001092 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001093 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001094 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001095
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001096 bool do_full_collection = false;
1097 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001098 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001099 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001100 }
1101
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001102 VLOG(jit) << "Do "
1103 << (do_full_collection ? "full" : "partial")
1104 << " code cache collection, code="
1105 << PrettySize(CodeCacheSize())
1106 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001107
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001108 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001109
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001110 VLOG(jit) << "After code cache collection, code="
1111 << PrettySize(CodeCacheSize())
1112 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001113
1114 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001115 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001116
1117 // Increase the code cache only when we do partial collections.
1118 // TODO: base this strategy on how full the code cache is?
1119 if (do_full_collection) {
1120 last_collection_increased_code_cache_ = false;
1121 } else {
1122 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001123 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001124 }
1125
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001126 bool next_collection_will_be_full = ShouldDoFullCollection();
1127
1128 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001129 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001130 // Save the entry point of methods we have compiled, and update the entry
1131 // point of those methods to the interpreter. If the method is invoked, the
1132 // interpreter will update its entry point to the compiled code and call it.
1133 for (ProfilingInfo* info : profiling_infos_) {
1134 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001135 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001136 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001137 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001138 // class of the method. We may be concurrently running a GC which makes accessing
1139 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1140 // checked that the current entry point is JIT compiled code.
1141 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001142 }
1143 }
1144
Vladimir Marko2196c652017-11-30 16:16:07 +00001145 // Change entry points of native methods back to the GenericJNI entrypoint.
1146 for (const auto& entry : jni_stubs_map_) {
1147 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001148 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001149 continue;
1150 }
1151 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1152 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1153 const OatQuickMethodHeader* method_header =
1154 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1155 for (ArtMethod* method : data.GetMethods()) {
1156 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1157 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1158 method->SetCounter(new_counter);
1159 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1160 }
1161 }
1162 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001163 }
1164 live_bitmap_.reset(nullptr);
1165 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001166 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001167 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001168 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001169}
1170
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001171void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001172 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001173 std::unordered_set<OatQuickMethodHeader*> method_headers;
1174 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001175 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001176 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001177 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1178 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001179 if (IsInZygoteExecSpace(data->GetCode()) ||
1180 !data->IsCompiled() ||
1181 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001182 ++it;
1183 } else {
1184 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1185 it = jni_stubs_map_.erase(it);
1186 }
1187 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001188 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1189 const void* code_ptr = it->first;
1190 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001191 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001192 ++it;
1193 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001194 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1195 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001196 it = method_code_map_.erase(it);
1197 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001198 }
1199 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001200 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001201}
1202
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001203bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001204 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001205 return garbage_collect_code_;
1206}
1207
1208void JitCodeCache::SetGarbageCollectCode(bool value) {
1209 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001210 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001211 if (garbage_collect_code_ != value) {
1212 if (garbage_collect_code_) {
1213 // When dynamically disabling the garbage collection, we neee
1214 // to make sure that a potential current collection is finished, and also
1215 // clear the saved entry point in profiling infos to avoid dangling pointers.
1216 WaitForPotentialCollectionToComplete(self);
1217 for (ProfilingInfo* info : profiling_infos_) {
1218 info->SetSavedEntryPoint(nullptr);
1219 }
1220 }
1221 // Update the flag while holding the lock to ensure no thread will try to GC.
1222 garbage_collect_code_ = value;
1223 }
1224}
1225
Nicolas Geoffray35122442016-03-02 12:05:30 +00001226void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001227 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001228 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001229 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001230 if (collect_profiling_info) {
1231 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1232 // Also remove the saved entry point from the ProfilingInfo objects.
1233 for (ProfilingInfo* info : profiling_infos_) {
1234 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001235 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001236 info->GetMethod()->SetProfilingInfo(nullptr);
1237 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001238
1239 if (info->GetSavedEntryPoint() != nullptr) {
1240 info->SetSavedEntryPoint(nullptr);
1241 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001242 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001243 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001244 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001245 }
1246 } else if (kIsDebugBuild) {
1247 // Sanity check that the profiling infos do not have a dangling entry point.
1248 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001249 DCHECK(!Runtime::Current()->IsZygote());
1250 const void* entry_point = info->GetSavedEntryPoint();
1251 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001252 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001253 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001254
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001255 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1256 // an entry point is either:
1257 // - an osr compiled code, that will be removed if not in a thread call stack.
1258 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001259 for (const auto& entry : jni_stubs_map_) {
1260 const JniStubData& data = entry.second;
1261 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001262 if (IsInZygoteExecSpace(code_ptr)) {
1263 continue;
1264 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001265 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1266 for (ArtMethod* method : data.GetMethods()) {
1267 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1268 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1269 break;
1270 }
1271 }
1272 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001273 for (const auto& it : method_code_map_) {
1274 ArtMethod* method = it.second;
1275 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001276 if (IsInZygoteExecSpace(code_ptr)) {
1277 continue;
1278 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001279 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1280 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1281 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1282 }
1283 }
1284
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001285 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001286 // on thread stacks).
1287 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001288 }
1289
1290 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001291 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001292
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001293 // At this point, mutator threads are still running, and entrypoints of methods can
1294 // change. We do know they cannot change to a code cache entry that is not marked,
1295 // therefore we can safely remove those entries.
1296 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001297
Nicolas Geoffray35122442016-03-02 12:05:30 +00001298 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001299 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001300 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001301 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001302 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001303 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001304 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1305 // that the compiled code would not get revived. As mutator threads run concurrently,
1306 // they may have revived the compiled code, and now we are in the situation where
1307 // a method has compiled code but no ProfilingInfo.
1308 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1309 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001310 if (ContainsPc(ptr) &&
1311 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001312 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001313 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001314 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001315 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001316 return true;
1317 }
1318 return false;
1319 });
1320 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001321 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001322}
1323
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001324OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001325 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1326 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001327 // On Thumb-2, the pc is offset by one.
1328 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001329 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001330 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1331 return nullptr;
1332 }
1333
Vladimir Marko2196c652017-11-30 16:16:07 +00001334 if (!kIsDebugBuild) {
1335 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1336 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001337 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001338
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001339 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001340 OatQuickMethodHeader* method_header = nullptr;
1341 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1342 if (method != nullptr && UNLIKELY(method->IsNative())) {
1343 auto it = jni_stubs_map_.find(JniStubKey(method));
1344 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1345 return nullptr;
1346 }
1347 const void* code_ptr = it->second.GetCode();
1348 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1349 if (!method_header->Contains(pc)) {
1350 return nullptr;
1351 }
1352 } else {
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001353 if (shared_region_.IsInExecSpace(reinterpret_cast<const void*>(pc))) {
1354 const void* code_ptr = zygote_map_.GetCodeFor(method, pc);
1355 if (code_ptr != nullptr) {
1356 return OatQuickMethodHeader::FromCodePointer(code_ptr);
1357 }
1358 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001359 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1360 if (it != method_code_map_.begin()) {
1361 --it;
1362 const void* code_ptr = it->first;
1363 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1364 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1365 found_method = it->second;
1366 }
1367 }
1368 if (method_header == nullptr && method == nullptr) {
1369 // Scan all compiled JNI stubs as well. This slow search is used only
1370 // for checks in debug build, for release builds the `method` is not null.
1371 for (auto&& entry : jni_stubs_map_) {
1372 const JniStubData& data = entry.second;
1373 if (data.IsCompiled() &&
1374 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1375 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1376 }
1377 }
1378 }
1379 if (method_header == nullptr) {
1380 return nullptr;
1381 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001382 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001383
1384 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001385 DCHECK_EQ(found_method, method)
1386 << ArtMethod::PrettyMethod(method) << " "
1387 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001388 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001389 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001390 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001391}
1392
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001393OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001394 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001395 auto it = osr_code_map_.find(method);
1396 if (it == osr_code_map_.end()) {
1397 return nullptr;
1398 }
1399 return OatQuickMethodHeader::FromCodePointer(it->second);
1400}
1401
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001402ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1403 ArtMethod* method,
1404 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001405 bool retry_allocation)
1406 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1407 NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001408 DCHECK(CanAllocateProfilingInfo());
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001409 ProfilingInfo* info = nullptr;
1410 if (!retry_allocation) {
1411 // If we are allocating for the interpreter, just try to lock, to avoid
1412 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001413 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001414 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001415 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001416 }
1417 } else {
1418 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001419 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001420 info = AddProfilingInfoInternal(self, method, entries);
1421 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001422
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001423 if (info == nullptr) {
1424 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001425 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001426 info = AddProfilingInfoInternal(self, method, entries);
1427 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001428 }
1429 return info;
1430}
1431
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001432ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001433 ArtMethod* method,
1434 const std::vector<uint32_t>& entries) {
1435 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001436 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001437 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001438
1439 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001440 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001441 if (info != nullptr) {
1442 return info;
1443 }
1444
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001445 uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001446 if (data == nullptr) {
1447 return nullptr;
1448 }
1449 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001450
1451 // Make sure other threads see the data in the profiling info object before the
1452 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001453 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001454
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001455 method->SetProfilingInfo(info);
1456 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001457 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001458 return info;
1459}
1460
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001461void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001462 return shared_region_.OwnsSpace(mspace)
1463 ? shared_region_.MoreCore(mspace, increment)
1464 : private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001465}
1466
Calin Juravle99629622016-04-19 16:33:46 +01001467void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001468 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001469 Thread* self = Thread::Current();
1470 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001471 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001472 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001473 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001474 for (const ProfilingInfo* info : profiling_infos_) {
1475 ArtMethod* method = info->GetMethod();
1476 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001477 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1478 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001479 // Skip dex files which are not profiled.
1480 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001481 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001482 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001483
1484 // If the method didn't reach the compilation threshold don't save the inline caches.
1485 // They might be incomplete and cause unnecessary deoptimizations.
1486 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1487 if (method->GetCounter() < jit_compile_threshold) {
1488 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001489 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001490 continue;
1491 }
1492
Calin Juravle940eb0c2017-01-30 19:30:44 -08001493 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001494 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001495 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001496 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001497 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001498 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1499 mirror::Class* cls = cache.classes_[k].Read();
1500 if (cls == nullptr) {
1501 break;
1502 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001503
Calin Juravle13439f02017-02-21 01:17:21 -08001504 // Check if the receiver is in the boot class path or if it's in the
1505 // same class loader as the caller. If not, skip it, as there is not
1506 // much we can do during AOT.
1507 if (!cls->IsBootStrapClassLoaded() &&
1508 caller->GetClassLoader() != cls->GetClassLoader()) {
1509 is_missing_types = true;
1510 continue;
1511 }
1512
Calin Juravle4ca70a32017-02-21 16:22:24 -08001513 const DexFile* class_dex_file = nullptr;
1514 dex::TypeIndex type_index;
1515
1516 if (cls->GetDexCache() == nullptr) {
1517 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001518 // Make a best effort to find the type index in the method's dex file.
1519 // We could search all open dex files but that might turn expensive
1520 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001521 class_dex_file = dex_file;
1522 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1523 } else {
1524 class_dex_file = &(cls->GetDexFile());
1525 type_index = cls->GetDexTypeIndex();
1526 }
1527 if (!type_index.IsValid()) {
1528 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001529 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001530 continue;
1531 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001532 if (ContainsElement(dex_base_locations,
1533 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001534 // Only consider classes from the same apk (including multidex).
1535 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001536 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001537 } else {
1538 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001539 }
1540 }
1541 if (!profile_classes.empty()) {
1542 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001543 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001544 }
1545 }
1546 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001547 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001548 }
1549}
1550
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001551bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001552 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001553 return osr_code_map_.find(method) != osr_code_map_.end();
1554}
1555
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001556bool JitCodeCache::NotifyCompilationOf(ArtMethod* method,
1557 Thread* self,
1558 bool osr,
1559 bool prejit,
1560 JitMemoryRegion* region) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001561 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001562 return false;
1563 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001564
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001565 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1566 if (class_linker->IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001567 if (!prejit) {
1568 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1569 // update the entrypoint due to having the resolution stub.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001570 VLOG(jit) << "Not compiling "
1571 << method->PrettyMethod()
1572 << " because it has the resolution stub";
1573 // Give it a new chance to be hot.
1574 ClearMethodCounter(method, /*was_warm=*/ false);
1575 return false;
1576 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001577 }
1578
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001579 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001580 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1581 return false;
1582 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001583
Vladimir Marko2196c652017-11-30 16:16:07 +00001584 if (UNLIKELY(method->IsNative())) {
1585 JniStubKey key(method);
1586 auto it = jni_stubs_map_.find(key);
1587 bool new_compilation = false;
1588 if (it == jni_stubs_map_.end()) {
1589 // Create a new entry to mark the stub as being compiled.
1590 it = jni_stubs_map_.Put(key, JniStubData{});
1591 new_compilation = true;
1592 }
1593 JniStubData* data = &it->second;
1594 data->AddMethod(method);
1595 if (data->IsCompiled()) {
1596 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1597 const void* entrypoint = method_header->GetEntryPoint();
1598 // Update also entrypoints of other methods held by the JniStubData.
1599 // We could simply update the entrypoint of `method` but if the last JIT GC has
1600 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1601 // as well change them back as this stub shall not be collected anyway and this
1602 // can avoid a few expensive GenericJNI calls.
1603 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1604 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001605 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1606 // `m` might be in the process of being deleted.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001607 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
1608 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
1609 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001610 }
1611 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001612 if (!IsInZygoteExecSpace(data->GetCode())) {
1613 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1614 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001615 }
1616 }
1617 return new_compilation;
1618 } else {
1619 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1620 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001621 // When prejitting, we don't allocate a profiling info.
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001622 if (!prejit && !IsSharedRegion(*region)) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001623 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1624 // Because the counter is not atomic, there are some rare cases where we may not hit the
1625 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1626 ClearMethodCounter(method, /*was_warm=*/ false);
1627 return false;
1628 }
1629 } else {
1630 if (info->IsMethodBeingCompiled(osr)) {
1631 return false;
1632 }
1633 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00001634 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001635 return true;
1636 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001637}
1638
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001639ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001640 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001641 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001642 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001643 if (!info->IncrementInlineUse()) {
1644 // Overflow of inlining uses, just bail.
1645 return nullptr;
1646 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001647 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001648 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001649}
1650
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001651void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001652 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001653 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001654 DCHECK(info != nullptr);
1655 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001656}
1657
Vladimir Marko2196c652017-11-30 16:16:07 +00001658void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1659 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001660 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001661 if (UNLIKELY(method->IsNative())) {
1662 auto it = jni_stubs_map_.find(JniStubKey(method));
1663 DCHECK(it != jni_stubs_map_.end());
1664 JniStubData* data = &it->second;
1665 DCHECK(ContainsElement(data->GetMethods(), method));
1666 if (UNLIKELY(!data->IsCompiled())) {
1667 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1668 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1669 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1670 } else {
1671 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001672 if (info != nullptr) {
1673 DCHECK(info->IsMethodBeingCompiled(osr));
1674 info->SetIsMethodBeingCompiled(false, osr);
1675 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001676 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001677}
1678
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001679void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1680 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001681 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001682 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001683 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001684 if ((profiling_info != nullptr) &&
1685 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001686 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1687 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001688 // Prevent future uses of the compiled code.
1689 profiling_info->SetSavedEntryPoint(nullptr);
1690 }
1691
Alex Light2d441b12018-06-08 15:33:21 -07001692 // Clear the method counter if we are running jitted code since we might want to jit this again in
1693 // the future.
1694 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001695 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001696 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001697 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1698 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001699 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001700 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001701 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001702 auto it = osr_code_map_.find(method);
1703 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1704 // Remove the OSR method, to avoid using it again.
1705 osr_code_map_.erase(it);
1706 }
1707 }
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001708
Nicolas Geoffray32384402019-07-17 20:06:44 +01001709 // In case the method was pre-compiled, clear that information so we
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001710 // can recompile it ourselves.
Nicolas Geoffray32384402019-07-17 20:06:44 +01001711 if (method->IsPreCompiled()) {
1712 method->ClearPreCompiled();
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001713 }
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001714}
1715
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001716void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001717 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1718 os << "Current JIT code cache size: " << PrettySize(private_region_.GetUsedMemoryForCode())
1719 << "\n"
1720 << "Current JIT data cache size: " << PrettySize(private_region_.GetUsedMemoryForData())
1721 << "\n"
David Srbeckyafc60cd2018-12-05 11:59:31 +00001722 << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001723 << "Current JIT capacity: " << PrettySize(private_region_.GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001724 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001725 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1726 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1727 << "Total number of JIT compilations for on stack replacement: "
1728 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001729 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001730 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1731 histogram_code_memory_use_.PrintMemoryUse(os);
1732 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001733}
1734
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001735void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayb08d5db2019-07-17 10:45:36 +01001736 Thread* self = Thread::Current();
1737
1738 // Remove potential tasks that have been inherited from the zygote.
1739 // We do this now and not in Jit::PostForkChildAction, as system server calls
1740 // JitCodeCache::PostForkChildAction first, and then does some code loading
1741 // that may result in new JIT tasks that we want to keep.
1742 ThreadPool* pool = Runtime::Current()->GetJit()->GetThreadPool();
1743 if (pool != nullptr) {
1744 pool->RemoveAllTasks(self);
1745 }
1746
1747 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray88f3fd92019-06-27 16:32:13 +01001748
1749 // Reset potential writable MemMaps inherited from the zygote. We never want
1750 // to write to them.
1751 shared_region_.ResetWritableMappings();
1752
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001753 if (is_zygote || Runtime::Current()->IsSafeMode()) {
1754 // Don't create a private region for a child zygote. Regions are usually map shared
1755 // (to satisfy dual-view), and we don't want children of a child zygote to inherit it.
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001756 return;
1757 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001758
1759 // Reset all statistics to be specific to this process.
1760 number_of_compilations_ = 0;
1761 number_of_osr_compilations_ = 0;
1762 number_of_collections_ = 0;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001763
1764 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1765 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001766 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001767 if (!private_region_.Initialize(initial_capacity,
1768 max_capacity,
1769 /* rwx_memory_allowed= */ !is_system_server,
1770 is_zygote,
1771 &error_msg)) {
1772 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001773 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001774}
1775
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001776JitMemoryRegion* JitCodeCache::GetCurrentRegion() {
1777 return Runtime::Current()->IsZygote() ? &shared_region_ : &private_region_;
1778}
1779
Nicolas Geoffraye32d24c2019-07-05 10:28:59 +01001780void ZygoteMap::Initialize(uint32_t number_of_methods) {
1781 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1782 // Allocate for 40-80% capacity. This will offer OK lookup times, and termination
1783 // cases.
1784 size_t capacity = RoundUpToPowerOfTwo(number_of_methods * 100 / 80);
1785 Entry* data = reinterpret_cast<Entry*>(region_->AllocateData(capacity * sizeof(Entry)));
1786 if (data != nullptr) {
1787 region_->FillData(data, capacity, Entry { nullptr, nullptr });
1788 map_ = ArrayRef(data, capacity);
1789 }
1790}
1791
1792const void* ZygoteMap::GetCodeFor(ArtMethod* method, uintptr_t pc) const {
1793 if (map_.empty()) {
1794 return nullptr;
1795 }
1796
1797 if (method == nullptr) {
1798 // Do a linear search. This should only be used in debug builds.
1799 CHECK(kIsDebugBuild);
1800 for (const Entry& entry : map_) {
1801 const void* code_ptr = entry.code_ptr;
1802 if (code_ptr != nullptr) {
1803 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1804 if (method_header->Contains(pc)) {
1805 return code_ptr;
1806 }
1807 }
1808 }
1809 return nullptr;
1810 }
1811
1812 std::hash<ArtMethod*> hf;
1813 size_t index = hf(method) & (map_.size() - 1u);
1814 size_t original_index = index;
1815 // Loop over the array: we know this loop terminates as we will either
1816 // encounter the given method, or a null entry. Both terminate the loop.
1817 // Note that the zygote may concurrently write new entries to the map. That's OK as the
1818 // map is never resized.
1819 while (true) {
1820 const Entry& entry = map_[index];
1821 if (entry.method == nullptr) {
1822 // Not compiled yet.
1823 return nullptr;
1824 }
1825 if (entry.method == method) {
1826 if (entry.code_ptr == nullptr) {
1827 // This is a race with the zygote which wrote the method, but hasn't written the
1828 // code. Just bail and wait for the next time we need the method.
1829 return nullptr;
1830 }
1831 if (pc != 0 && !OatQuickMethodHeader::FromCodePointer(entry.code_ptr)->Contains(pc)) {
1832 return nullptr;
1833 }
1834 return entry.code_ptr;
1835 }
1836 index = (index + 1) & (map_.size() - 1);
1837 DCHECK_NE(original_index, index);
1838 }
1839}
1840
1841void ZygoteMap::Put(const void* code, ArtMethod* method) {
1842 if (map_.empty()) {
1843 return;
1844 }
1845 CHECK(Runtime::Current()->IsZygote());
1846 std::hash<ArtMethod*> hf;
1847 size_t index = hf(method) & (map_.size() - 1);
1848 size_t original_index = index;
1849 // Because the size of the map is bigger than the number of methods that will
1850 // be added, we are guaranteed to find a free slot in the array, and
1851 // therefore for this loop to terminate.
1852 while (true) {
1853 Entry* entry = &map_[index];
1854 if (entry->method == nullptr) {
1855 // Note that readers can read this memory concurrently, but that's OK as
1856 // we are writing pointers.
1857 region_->WriteData(entry, Entry { method, code });
1858 break;
1859 }
1860 index = (index + 1) & (map_.size() - 1);
1861 DCHECK_NE(original_index, index);
1862 }
1863 DCHECK_EQ(GetCodeFor(method), code);
1864}
1865
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001866} // namespace jit
1867} // namespace art