blob: 56a2b6aba811b8f5a6d7c6b1c09af2f9f99a7a89 [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
181 // Check whether the provided max capacity in options is below 1GB.
182 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
183 // We need to have 32 bit offsets from method headers in code cache which point to things
184 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
185 // Ensure we're below 1 GB to be safe.
186 if (max_capacity > 1 * GB) {
187 std::ostringstream oss;
188 oss << "Maxium code cache capacity is limited to 1 GB, "
189 << PrettySize(max_capacity) << " is too big";
190 *error_msg = oss.str();
191 return nullptr;
192 }
193
194 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
195
196 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
197
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100198 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
199 jit_code_cache->private_region_.InitializeState(initial_capacity, max_capacity);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000200
201 // Zygote should never collect code to share the memory with the children.
202 if (is_zygote) {
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000203 jit_code_cache->garbage_collect_code_ = false;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000204 }
205
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100206 if (!jit_code_cache->private_region_.InitializeMappings(
207 rwx_memory_allowed, is_zygote, error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000208 return nullptr;
209 }
210
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100211 jit_code_cache->private_region_.InitializeSpaces();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000212
213 VLOG(jit) << "Created jit code cache: initial capacity="
214 << PrettySize(initial_capacity)
215 << ", maximum capacity="
216 << PrettySize(max_capacity);
217
218 return jit_code_cache.release();
219}
220
221JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100222 : is_weak_access_enabled_(true),
223 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
224 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100225 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000226 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100227 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000228 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000229 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000230 number_of_collections_(0),
231 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
232 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100233 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800234}
235
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000236JitCodeCache::~JitCodeCache() {}
237
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100238bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100239 return private_region_.IsInExecSpace(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240}
241
Alex Light2d441b12018-06-08 15:33:21 -0700242bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
243 ScopedObjectAccess soa(art::Thread::Current());
244 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
245 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
246 return true;
247 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
248 return FindCompiledCodeForInstrumentation(method) != nullptr;
249 }
250 return false;
251}
252
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000253bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100254 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000255 if (UNLIKELY(method->IsNative())) {
256 auto it = jni_stubs_map_.find(JniStubKey(method));
257 if (it != jni_stubs_map_.end() &&
258 it->second.IsCompiled() &&
259 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000260 return true;
261 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000262 } else {
263 for (const auto& it : method_code_map_) {
264 if (it.second == method) {
265 return true;
266 }
267 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000268 }
269 return false;
270}
271
Vladimir Marko2196c652017-11-30 16:16:07 +0000272const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
273 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100274 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000275 auto it = jni_stubs_map_.find(JniStubKey(method));
276 if (it != jni_stubs_map_.end()) {
277 JniStubData& data = it->second;
278 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
279 return data.GetCode();
280 }
281 }
282 return nullptr;
283}
284
Alex Light2d441b12018-06-08 15:33:21 -0700285const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700286 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
287 // find the instrumentation entrypoint.
288 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700289 return nullptr;
290 }
291 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
292 if (info == nullptr) {
293 return nullptr;
294 }
295 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
296 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
297 // nullptr.
298 return info->GetSavedEntryPoint();
299}
300
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100301const void* JitCodeCache::GetZygoteSavedEntryPoint(ArtMethod* method) {
David Srbecky3db3d372019-04-17 18:19:17 +0100302 if (Runtime::Current()->IsUsingApexBootImageLocation() &&
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100303 // Currently only applies to boot classpath
304 method->GetDeclaringClass()->GetClassLoader() == nullptr) {
305 const void* entry_point = nullptr;
306 if (method->IsNative()) {
307 const void* code_ptr = GetJniStubCode(method);
308 if (code_ptr != nullptr) {
309 entry_point = OatQuickMethodHeader::FromCodePointer(code_ptr)->GetEntryPoint();
310 }
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100311 } else {
312 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
313 if (profiling_info != nullptr) {
314 entry_point = profiling_info->GetSavedEntryPoint();
315 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100316 }
317 if (Runtime::Current()->IsZygote() || IsInZygoteExecSpace(entry_point)) {
318 return entry_point;
319 }
320 }
321 return nullptr;
322}
323
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100324uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100325 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100326 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000327 uint8_t* stack_map,
328 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100329 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000330 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100331 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000332 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100333 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700334 bool has_should_deoptimize_flag,
335 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100336 uint8_t* result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100337 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100338 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000339 stack_map,
340 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100341 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000342 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100343 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000344 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 roots,
346 has_should_deoptimize_flag,
347 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100348 if (result == nullptr) {
349 // Retry.
350 GarbageCollectCache(self);
351 result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100352 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100353 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000354 stack_map,
355 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100356 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000357 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100358 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000359 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700360 roots,
361 has_should_deoptimize_flag,
362 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100363 }
364 return result;
365}
366
367bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
368 bool in_collection = false;
369 while (collection_in_progress_) {
370 in_collection = true;
371 lock_cond_.Wait(self);
372 }
373 return in_collection;
374}
375
376static uintptr_t FromCodeToAllocation(const void* code) {
377 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
378 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
379}
380
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000381static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
382 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
383}
384
385static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
386 // The length of the table is stored just before the stack map (and therefore at the end of
387 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
388 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
389}
390
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800391static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
392 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
393 // pointer.
394 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
395}
396
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000397static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
398 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
399}
400
Vladimir Markoac3ac682018-09-20 11:01:43 +0100401static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700402 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
403 if (!kIsDebugBuild) {
404 return;
405 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700406 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100407 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700408 // Ensure the string is strongly interned. b/32995596
409 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100410 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700411 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
412 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
413 }
414 }
415}
416
417void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100418 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000419 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100420 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000421 // Put all roots in `roots_data`.
422 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100423 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000424 gc_roots[i] = GcRoot<mirror::Object>(object);
425 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000426}
427
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100428static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000429 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
430 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
431 uint32_t roots = GetNumberOfRoots(data);
432 if (number_of_roots != nullptr) {
433 *number_of_roots = roots;
434 }
435 return data - ComputeRootTableSize(roots);
436}
437
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100438// Use a sentinel for marking entries in the JIT table that have been cleared.
439// This helps diagnosing in case the compiled code tries to wrongly access such
440// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700441static mirror::Class* const weak_sentinel =
442 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100443
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000444// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100445static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
446 IsMarkedVisitor* visitor,
447 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000448 REQUIRES_SHARED(Locks::mutator_lock_) {
449 // This does not need a read barrier because this is called by GC.
450 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100451 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700452 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000453 // Look at the classloader of the class to know if it has been unloaded.
454 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000455 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000456 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000457 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000458 // The class loader is live, update the entry if the class has moved.
459 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
460 // Note that new_object can be null for CMS and newly allocated objects.
461 if (new_cls != nullptr && new_cls != cls) {
462 *root_ptr = GcRoot<mirror::Class>(new_cls);
463 }
464 } else {
465 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100466 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000467 }
468 }
469}
470
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000471void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100472 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000473 for (const auto& entry : method_code_map_) {
474 uint32_t number_of_roots = 0;
475 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
476 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
477 for (uint32_t i = 0; i < number_of_roots; ++i) {
478 // This does not need a read barrier because this is called by GC.
479 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100480 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000481 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000482 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000483 mirror::Object* new_object = visitor->IsMarked(object);
484 // We know the string is marked because it's a strongly-interned string that
485 // is always alive. The IsMarked implementation of the CMS collector returns
486 // null for newly allocated objects, but we know those haven't moved. Therefore,
487 // only update the entry if we get a different non-null string.
488 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
489 // out of the weak access/creation pause. b/32167580
490 if (new_object != nullptr && new_object != object) {
491 DCHECK(new_object->IsString());
492 roots[i] = GcRoot<mirror::Object>(new_object);
493 }
494 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100495 ProcessWeakClass(
496 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000497 }
498 }
499 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000500 // Walk over inline caches to clear entries containing unloaded classes.
501 for (ProfilingInfo* info : profiling_infos_) {
502 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
503 InlineCache* cache = &info->cache_[i];
504 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100505 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000506 }
507 }
508 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000509}
510
Orion Hodson607624f2018-05-11 10:10:46 +0100511void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000512 if (IsInZygoteExecSpace(code_ptr)) {
513 // No need to free, this is shared memory.
514 return;
515 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100516 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000517 // Notify native debugger that we are about to remove the code.
518 // It does nothing if we are not using native debugger.
David Srbeckyafc60cd2018-12-05 11:59:31 +0000519 RemoveNativeDebugInfoForJit(Thread::Current(), code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000520 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100521 private_region_.FreeData(GetRootTable(code_ptr));
Vladimir Marko2196c652017-11-30 16:16:07 +0000522 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100523
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100524 private_region_.FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100525}
526
Mingyao Yang063fc772016-08-02 11:02:54 -0700527void JitCodeCache::FreeAllMethodHeaders(
528 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700529 // We need to remove entries in method_headers from CHA dependencies
530 // first since once we do FreeCode() below, the memory can be reused
531 // so it's possible for the same method_header to start representing
532 // different compile code.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100533 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000534 {
535 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
536 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
537 ->RemoveDependentsWithMethodHeaders(method_headers);
538 }
539
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100540 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700541 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100542 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700543 }
544}
545
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100546void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800547 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700548 // We use a set to first collect all method_headers whose code need to be
549 // removed. We need to free the underlying code after we remove CHA dependencies
550 // for entries in this set. And it's more efficient to iterate through
551 // the CHA dependency map just once with an unordered_set.
552 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000553 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100554 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700555 // We do not check if a code cache GC is in progress, as this method comes
556 // with the classlinker_classes_lock_ held, and suspending ourselves could
557 // lead to a deadlock.
558 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100559 ScopedCodeCacheWrite scc(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000560 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
561 it->second.RemoveMethodsIn(alloc);
562 if (it->second.GetMethods().empty()) {
563 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
564 it = jni_stubs_map_.erase(it);
565 } else {
566 it->first.UpdateShorty(it->second.GetMethods().front());
567 ++it;
568 }
569 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700570 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
571 if (alloc.ContainsUnsafe(it->second)) {
572 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
573 it = method_code_map_.erase(it);
574 } else {
575 ++it;
576 }
577 }
578 }
579 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
580 if (alloc.ContainsUnsafe(it->first)) {
581 // Note that the code has already been pushed to method_headers in the loop
582 // above and is going to be removed in FreeCode() below.
583 it = osr_code_map_.erase(it);
584 } else {
585 ++it;
586 }
587 }
588 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
589 ProfilingInfo* info = *it;
590 if (alloc.ContainsUnsafe(info->GetMethod())) {
591 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100592 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700593 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000594 } else {
595 ++it;
596 }
597 }
598 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700599 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100600}
601
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000602bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
603 return kUseReadBarrier
604 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000605 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000606}
607
608void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
609 if (IsWeakAccessEnabled(self)) {
610 return;
611 }
612 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100613 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000614 while (!IsWeakAccessEnabled(self)) {
615 inline_cache_cond_.Wait(self);
616 }
617}
618
619void JitCodeCache::BroadcastForInlineCacheAccess() {
620 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100621 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000622 inline_cache_cond_.Broadcast(self);
623}
624
625void JitCodeCache::AllowInlineCacheAccess() {
626 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000627 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000628 BroadcastForInlineCacheAccess();
629}
630
631void JitCodeCache::DisallowInlineCacheAccess() {
632 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000633 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000634}
635
636void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
637 Handle<mirror::ObjectArray<mirror::Class>> array) {
638 WaitUntilInlineCacheAccessible(Thread::Current());
639 // Note that we don't need to lock `lock_` here, the compiler calling
640 // this method has already ensured the inline cache will not be deleted.
641 for (size_t in_cache = 0, in_array = 0;
642 in_cache < InlineCache::kIndividualCacheSize;
643 ++in_cache) {
644 mirror::Class* object = ic.classes_[in_cache].Read();
645 if (object != nullptr) {
646 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000647 }
648 }
649}
650
David Srbeckye36e7f22018-11-14 14:21:23 +0000651static void ClearMethodCounter(ArtMethod* method, bool was_warm)
652 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700653 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100654 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700655 }
656 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
657 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100658 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
659 // the warmup threshold is 1.
660 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
661 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700662}
663
Alex Light33b7b5d2018-08-07 19:13:51 +0000664void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
665 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100666 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000667 {
668 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100669 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000670 WaitForPotentialCollectionToComplete(self);
671 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100672 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100673 }
674}
675
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100676uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100677 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100678 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000679 uint8_t* stack_map,
680 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100681 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000682 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100683 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000684 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100685 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700686 bool has_should_deoptimize_flag,
687 const ArenaSet<ArtMethod*>&
688 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000689 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000690
691 if (!method->IsNative()) {
692 // We need to do this before grabbing the lock_ because it needs to be able to see the string
693 // InternTable. Native methods do not have roots.
694 DCheckRootsAreValid(roots);
695 }
696
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100697 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100698 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100699
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100700 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000701 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
702 // finish.
703 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100704 {
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100705 ScopedCodeCacheWrite scc(*region);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100706
707 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
708 // Ensure the header ends up at expected instruction alignment.
709 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
710 size_t total_size = header_size + code_size;
711
712 // AllocateCode allocates memory in non-executable region for alignment header and code. The
713 // header size may include alignment padding.
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100714 uint8_t* nox_memory = region->AllocateCode(total_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100715 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +0000716 return nullptr;
717 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000718
Orion Hodson1d3fd082018-09-28 09:38:35 +0100719 // code_ptr points to non-executable code.
720 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +0000721 std::copy(code, code + code_size, code_ptr);
722 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100723
724 // From here code_ptr points to executable code.
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100725 code_ptr = region->GetExecutableAddress(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100726
Alex Light33b7b5d2018-08-07 19:13:51 +0000727 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray57083762019-03-05 09:24:45 +0000728 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
729 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100730
731 DCHECK(!Runtime::Current()->IsAotCompiler());
732 if (has_should_deoptimize_flag) {
733 method_header->SetHasShouldDeoptimizeFlag();
734 }
735
736 // Update method_header pointer to executable code region.
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100737 method_header = region->GetExecutableAddress(method_header);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100738
739 // Both instruction and data caches need flushing to the point of unification where both share
740 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
741 // newly added code are written out to the point of unification. Flushing the instruction
742 // cache ensures the newly written code will be fetched from the point of unification before
743 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
744 // prevent stale code from residing in the instruction cache.
745 //
746 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
747 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
748 // operation. This is a kernel bug that we need to work around until affected devices
749 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +0000750 //
751 // For reference, this behavior is caused by this commit:
752 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +0100753 //
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100754 if (region->HasDualCodeMapping()) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100755 // Flush the data cache lines associated with the non-executable copy of the code just added.
756 FlushDataCache(nox_memory, nox_memory + total_size);
757 }
758 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
759 // flushed is for the executable mapping of the code just added.
Orion Hodsondf1ab202019-06-02 16:45:03 +0100760 uint8_t* x_memory = reinterpret_cast<uint8_t*>(method_header);
761 FlushInstructionCache(x_memory, x_memory + total_size);
Orion Hodsonf2331362018-07-11 15:14:10 +0100762
763 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
764 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
765 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
766 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
767 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
768 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +0100769 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
770 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
771 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +0100772 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +0100773
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000774 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100775 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100776
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000777 // We need to update the entry point in the runnable state for the instrumentation.
778 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000779 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
780 // compiled code is considered invalidated by some class linking, but below we still make the
781 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
782 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700783 MutexLock cha_mu(self, *Locks::cha_lock_);
784 bool single_impl_still_valid = true;
785 for (ArtMethod* single_impl : cha_single_implementation_list) {
786 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700787 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
788 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700789 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700790 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700791 break;
792 }
793 }
794
795 // Discard the code if any single-implementation assumptions are now invalid.
796 if (!single_impl_still_valid) {
797 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
798 return nullptr;
799 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000800 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800801 << "Should not be using cha on debuggable apps/runs!";
802
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100803 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700804 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100805 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700806 }
807
Vladimir Marko2196c652017-11-30 16:16:07 +0000808 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000809 auto it = jni_stubs_map_.find(JniStubKey(method));
810 DCHECK(it != jni_stubs_map_.end())
811 << "Entry inserted in NotifyCompilationOf() should be alive.";
812 JniStubData* data = &it->second;
813 DCHECK(ContainsElement(data->GetMethods(), method))
814 << "Entry inserted in NotifyCompilationOf() should contain this method.";
815 data->SetCode(code_ptr);
816 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
817 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100818 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
819 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
820 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000821 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100822 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000823 // Fill the root table before updating the entry point.
824 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
825 DCHECK_LE(roots_data, stack_map);
826 FillRootTable(roots_data, roots);
827 {
828 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +0100829 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +0000830 }
831 method_code_map_.Put(code_ptr, method);
832 if (osr) {
833 number_of_osr_compilations_++;
834 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100835 } else if (class_linker->IsQuickResolutionStub(
836 method->GetEntryPointFromQuickCompiledCode())) {
837 // This situation currently only occurs in the jit-zygote mode.
David Srbecky3db3d372019-04-17 18:19:17 +0100838 DCHECK(Runtime::Current()->IsUsingApexBootImageLocation());
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100839 DCHECK(!garbage_collect_code_);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100840 // TODO(ngeoffray): In most cases, the zygote will not have a profiling
841 // info for a compiled method. Use a map instead.
842 if (method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
843 // Save the entrypoint, so it can be fetched later once the class is
844 // initialized.
845 method->GetProfilingInfo(kRuntimePointerSize)->SetSavedEntryPoint(
846 method_header->GetEntryPoint());
847 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000848 } else {
849 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
850 method, method_header->GetEntryPoint());
851 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000852 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000853 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100854 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700855 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000856 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
857 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
858 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700859 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
860 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000861 histogram_code_memory_use_.AddValue(code_size);
862 if (code_size > kCodeSizeLogThreshold) {
863 LOG(INFO) << "JIT allocated "
864 << PrettySize(code_size)
865 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700866 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000867 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000868 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100869
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100870 return reinterpret_cast<uint8_t*>(method_header);
871}
872
873size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100874 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000875 return CodeCacheSizeLocked();
876}
877
Orion Hodsoneced6922017-06-01 10:54:28 +0100878bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000879 // This function is used only for testing and only with non-native methods.
880 CHECK(!method->IsNative());
881
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100882 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100883
Vladimir Marko2196c652017-11-30 16:16:07 +0000884 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
885 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100886
887 if (!in_cache) {
888 return false;
889 }
890
David Srbeckye36e7f22018-11-14 14:21:23 +0000891 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100892 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
893 method, GetQuickToInterpreterBridge());
894 VLOG(jit)
895 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
896 << ArtMethod::PrettyMethod(method) << "@" << method
897 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
898 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
899 return true;
900}
901
Vladimir Marko2196c652017-11-30 16:16:07 +0000902bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
903 if (LIKELY(!method->IsNative())) {
904 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
905 if (info != nullptr) {
906 RemoveElement(profiling_infos_, info);
907 }
908 method->SetProfilingInfo(nullptr);
909 }
910
911 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100912 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000913 if (UNLIKELY(method->IsNative())) {
914 auto it = jni_stubs_map_.find(JniStubKey(method));
915 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
916 in_cache = true;
917 if (it->second.GetMethods().empty()) {
918 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100919 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000920 }
921 jni_stubs_map_.erase(it);
922 } else {
923 it->first.UpdateShorty(it->second.GetMethods().front());
924 }
925 }
926 } else {
927 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
928 if (it->second == method) {
929 in_cache = true;
930 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100931 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000932 }
933 it = method_code_map_.erase(it);
934 } else {
935 ++it;
936 }
937 }
938
939 auto osr_it = osr_code_map_.find(method);
940 if (osr_it != osr_code_map_.end()) {
941 osr_code_map_.erase(osr_it);
942 }
943 }
944
945 return in_cache;
946}
947
Alex Lightdba61482016-12-21 08:20:29 -0800948// This notifies the code cache that the given method has been redefined and that it should remove
949// any cached information it has on the method. All threads must be suspended before calling this
950// method. The compiled code for the method (if there is any) must not be in any threads call stack.
951void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100952 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700953 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800954}
955
956// This invalidates old_method. Once this function returns one can no longer use old_method to
957// execute code unless it is fixed up. This fixup will happen later in the process of installing a
958// class redefinition.
959// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
960// shouldn't be used since it is no longer logically in the jit code cache.
961// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
962void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100963 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000964 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000965 // Update methods in jni_stubs_map_.
966 for (auto& entry : jni_stubs_map_) {
967 JniStubData& data = entry.second;
968 data.MoveObsoleteMethod(old_method, new_method);
969 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000970 return;
971 }
Alex Lightdba61482016-12-21 08:20:29 -0800972 // Update ProfilingInfo to the new one and remove it from the old_method.
973 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
974 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
975 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
976 old_method->SetProfilingInfo(nullptr);
977 // Since the JIT should be paused and all threads suspended by the time this is called these
978 // checks should always pass.
979 DCHECK(!info->IsInUseByCompiler());
980 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700981 // Get rid of the old saved entrypoint if it is there.
982 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800983 info->method_ = new_method;
984 }
985 // Update method_code_map_ to point to the new method.
986 for (auto& it : method_code_map_) {
987 if (it.second == old_method) {
988 it.second = new_method;
989 }
990 }
991 // Update osr_code_map_ to point to the new method.
992 auto code_map = osr_code_map_.find(old_method);
993 if (code_map != osr_code_map_.end()) {
994 osr_code_map_.Put(new_method, code_map->second);
995 osr_code_map_.erase(old_method);
996 }
997}
998
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000999void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001000 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001001 // Iterate over profiling infos to know which methods may have been JITted. Note that
1002 // to be JITted, a method must have a profiling info.
1003 for (ProfilingInfo* info : profiling_infos_) {
1004 ArtMethod* method = info->GetMethod();
1005 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
1006 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1007 }
1008 // If zygote does method tracing, or in some configuration where
1009 // the JIT zygote does GC, we also need to clear the saved entry point
1010 // in the profiling info.
1011 if (IsInZygoteExecSpace(info->GetSavedEntryPoint())) {
1012 info->SetSavedEntryPoint(nullptr);
1013 }
1014 }
1015}
1016
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001017size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001018 return private_region_.GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001019}
1020
1021size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001022 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001023 return DataCacheSizeLocked();
1024}
1025
1026size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001027 return private_region_.GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001028}
1029
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001030void JitCodeCache::ClearData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001031 JitMemoryRegion* region,
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001032 uint8_t* stack_map_data,
1033 uint8_t* roots_data) {
1034 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001035 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001036 region->FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001037}
1038
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001039size_t JitCodeCache::ReserveData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001040 JitMemoryRegion* region,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001041 size_t stack_map_size,
1042 size_t number_of_roots,
1043 ArtMethod* method,
1044 uint8_t** stack_map_data,
1045 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001046 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001047 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001048 uint8_t* result = nullptr;
1049
1050 {
1051 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001052 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001053 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001054 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001055 }
1056
1057 if (result == nullptr) {
1058 // Retry.
1059 GarbageCollectCache(self);
1060 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001061 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001062 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +01001063 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001064 }
1065
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001066 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001067 histogram_stack_map_memory_use_.AddValue(size);
1068 if (size > kStackMapSizeLogThreshold) {
1069 LOG(INFO) << "JIT allocated "
1070 << PrettySize(size)
1071 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001072 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001073 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001074 if (result != nullptr) {
1075 *roots_data = result;
1076 *stack_map_data = result + table_size;
1077 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001078 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001079 } else {
1080 *roots_data = nullptr;
1081 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001082 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001083 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001084}
1085
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001086class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001087 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001088 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1089 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001090
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001091 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001092 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001093 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001094 StackVisitor::WalkStack(
1095 [&](const art::StackVisitor* stack_visitor) {
1096 const OatQuickMethodHeader* method_header =
1097 stack_visitor->GetCurrentOatQuickMethodHeader();
1098 if (method_header == nullptr) {
1099 return true;
1100 }
1101 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001102 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001103 // Use the atomic set version, as multiple threads are executing this code.
1104 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1105 }
1106 return true;
1107 },
1108 thread,
1109 /* context= */ nullptr,
1110 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1111
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001112 if (kIsDebugBuild) {
1113 // The stack walking code queries the side instrumentation stack if it
1114 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1115 // must have been seen. We sanity check this below.
1116 for (const instrumentation::InstrumentationStackFrame& frame
1117 : *thread->GetInstrumentationStack()) {
1118 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1119 // its stack frame, it is not the method owning return_pc_. We just pass null to
1120 // LookupMethodHeader: the method is only checked against in debug builds.
1121 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001122 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001123 if (method_header != nullptr) {
1124 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001125 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001126 }
1127 }
1128 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001129 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001130 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001131
1132 private:
1133 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001134 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001135 Barrier* const barrier_;
1136};
1137
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001138void JitCodeCache::NotifyCollectionDone(Thread* self) {
1139 collection_in_progress_ = false;
1140 lock_cond_.Broadcast(self);
1141}
1142
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001143void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1144 Barrier barrier(0);
1145 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001146 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001147 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1148 // Now that we have run our checkpoint, move to a suspended state and wait
1149 // for other threads to run the checkpoint.
1150 ScopedThreadSuspension sts(self, kSuspended);
1151 if (threads_running_checkpoint != 0) {
1152 barrier.Increment(self, threads_running_checkpoint);
1153 }
1154}
1155
Nicolas Geoffray35122442016-03-02 12:05:30 +00001156bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001157 if (private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001158 // Always do a full collection when the code cache is full.
1159 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001160 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001161 // Always do partial collection when the code cache size is below the reserved
1162 // capacity.
1163 return false;
1164 } else if (last_collection_increased_code_cache_) {
1165 // This time do a full collection.
1166 return true;
1167 } else {
1168 // This time do a partial collection.
1169 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001170 }
1171}
1172
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001173void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001174 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001175 // Wait for an existing collection, or let everyone know we are starting one.
1176 {
1177 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001178 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001179 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001180 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001181 return;
1182 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001183 return;
1184 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001185 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001186 live_bitmap_.reset(CodeCacheBitmap::Create(
1187 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001188 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1189 reinterpret_cast<uintptr_t>(
1190 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001191 collection_in_progress_ = true;
1192 }
1193 }
1194
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001195 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001196 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001197 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001198
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001199 bool do_full_collection = false;
1200 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001201 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001202 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001203 }
1204
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001205 VLOG(jit) << "Do "
1206 << (do_full_collection ? "full" : "partial")
1207 << " code cache collection, code="
1208 << PrettySize(CodeCacheSize())
1209 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001210
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001211 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001212
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001213 VLOG(jit) << "After code cache collection, code="
1214 << PrettySize(CodeCacheSize())
1215 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001216
1217 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001218 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001219
1220 // Increase the code cache only when we do partial collections.
1221 // TODO: base this strategy on how full the code cache is?
1222 if (do_full_collection) {
1223 last_collection_increased_code_cache_ = false;
1224 } else {
1225 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001226 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001227 }
1228
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001229 bool next_collection_will_be_full = ShouldDoFullCollection();
1230
1231 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001232 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001233 // Save the entry point of methods we have compiled, and update the entry
1234 // point of those methods to the interpreter. If the method is invoked, the
1235 // interpreter will update its entry point to the compiled code and call it.
1236 for (ProfilingInfo* info : profiling_infos_) {
1237 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001238 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001239 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001240 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001241 // class of the method. We may be concurrently running a GC which makes accessing
1242 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1243 // checked that the current entry point is JIT compiled code.
1244 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001245 }
1246 }
1247
Vladimir Marko2196c652017-11-30 16:16:07 +00001248 // Change entry points of native methods back to the GenericJNI entrypoint.
1249 for (const auto& entry : jni_stubs_map_) {
1250 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001251 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001252 continue;
1253 }
1254 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1255 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1256 const OatQuickMethodHeader* method_header =
1257 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1258 for (ArtMethod* method : data.GetMethods()) {
1259 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1260 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1261 method->SetCounter(new_counter);
1262 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1263 }
1264 }
1265 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001266 }
1267 live_bitmap_.reset(nullptr);
1268 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001269 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001270 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001271 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001272}
1273
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001274void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001275 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001276 std::unordered_set<OatQuickMethodHeader*> method_headers;
1277 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001278 MutexLock mu(self, *Locks::jit_lock_);
1279 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001280 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001281 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1282 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001283 if (IsInZygoteExecSpace(data->GetCode()) ||
1284 !data->IsCompiled() ||
1285 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001286 ++it;
1287 } else {
1288 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1289 it = jni_stubs_map_.erase(it);
1290 }
1291 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001292 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1293 const void* code_ptr = it->first;
1294 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001295 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001296 ++it;
1297 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001298 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1299 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001300 it = method_code_map_.erase(it);
1301 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001302 }
1303 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001304 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001305}
1306
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001307bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001308 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001309 return garbage_collect_code_;
1310}
1311
1312void JitCodeCache::SetGarbageCollectCode(bool value) {
1313 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001314 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001315 if (garbage_collect_code_ != value) {
1316 if (garbage_collect_code_) {
1317 // When dynamically disabling the garbage collection, we neee
1318 // to make sure that a potential current collection is finished, and also
1319 // clear the saved entry point in profiling infos to avoid dangling pointers.
1320 WaitForPotentialCollectionToComplete(self);
1321 for (ProfilingInfo* info : profiling_infos_) {
1322 info->SetSavedEntryPoint(nullptr);
1323 }
1324 }
1325 // Update the flag while holding the lock to ensure no thread will try to GC.
1326 garbage_collect_code_ = value;
1327 }
1328}
1329
Nicolas Geoffray35122442016-03-02 12:05:30 +00001330void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001331 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001332 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001333 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001334 if (collect_profiling_info) {
1335 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1336 // Also remove the saved entry point from the ProfilingInfo objects.
1337 for (ProfilingInfo* info : profiling_infos_) {
1338 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001339 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001340 info->GetMethod()->SetProfilingInfo(nullptr);
1341 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001342
1343 if (info->GetSavedEntryPoint() != nullptr) {
1344 info->SetSavedEntryPoint(nullptr);
1345 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001346 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001347 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001348 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001349 }
1350 } else if (kIsDebugBuild) {
1351 // Sanity check that the profiling infos do not have a dangling entry point.
1352 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001353 DCHECK(!Runtime::Current()->IsZygote());
1354 const void* entry_point = info->GetSavedEntryPoint();
1355 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001356 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001357 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001358
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001359 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1360 // an entry point is either:
1361 // - an osr compiled code, that will be removed if not in a thread call stack.
1362 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001363 for (const auto& entry : jni_stubs_map_) {
1364 const JniStubData& data = entry.second;
1365 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001366 if (IsInZygoteExecSpace(code_ptr)) {
1367 continue;
1368 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001369 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1370 for (ArtMethod* method : data.GetMethods()) {
1371 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1372 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1373 break;
1374 }
1375 }
1376 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001377 for (const auto& it : method_code_map_) {
1378 ArtMethod* method = it.second;
1379 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001380 if (IsInZygoteExecSpace(code_ptr)) {
1381 continue;
1382 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001383 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1384 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1385 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1386 }
1387 }
1388
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001389 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001390 // on thread stacks).
1391 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001392 }
1393
1394 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001395 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001396
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001397 // At this point, mutator threads are still running, and entrypoints of methods can
1398 // change. We do know they cannot change to a code cache entry that is not marked,
1399 // therefore we can safely remove those entries.
1400 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001401
Nicolas Geoffray35122442016-03-02 12:05:30 +00001402 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001403 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001404 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001405 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001406 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001407 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001408 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1409 // that the compiled code would not get revived. As mutator threads run concurrently,
1410 // they may have revived the compiled code, and now we are in the situation where
1411 // a method has compiled code but no ProfilingInfo.
1412 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1413 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001414 if (ContainsPc(ptr) &&
1415 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001416 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001417 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001418 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001419 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001420 return true;
1421 }
1422 return false;
1423 });
1424 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001425 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001426}
1427
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001428OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001429 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1430 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001431 // On Thumb-2, the pc is offset by one.
1432 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001433 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001434 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1435 return nullptr;
1436 }
1437
Vladimir Marko2196c652017-11-30 16:16:07 +00001438 if (!kIsDebugBuild) {
1439 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1440 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001441 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001442
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001443 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001444 OatQuickMethodHeader* method_header = nullptr;
1445 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1446 if (method != nullptr && UNLIKELY(method->IsNative())) {
1447 auto it = jni_stubs_map_.find(JniStubKey(method));
1448 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1449 return nullptr;
1450 }
1451 const void* code_ptr = it->second.GetCode();
1452 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1453 if (!method_header->Contains(pc)) {
1454 return nullptr;
1455 }
1456 } else {
1457 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1458 if (it != method_code_map_.begin()) {
1459 --it;
1460 const void* code_ptr = it->first;
1461 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1462 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1463 found_method = it->second;
1464 }
1465 }
1466 if (method_header == nullptr && method == nullptr) {
1467 // Scan all compiled JNI stubs as well. This slow search is used only
1468 // for checks in debug build, for release builds the `method` is not null.
1469 for (auto&& entry : jni_stubs_map_) {
1470 const JniStubData& data = entry.second;
1471 if (data.IsCompiled() &&
1472 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1473 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1474 }
1475 }
1476 }
1477 if (method_header == nullptr) {
1478 return nullptr;
1479 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001480 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001481
1482 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001483 DCHECK_EQ(found_method, method)
1484 << ArtMethod::PrettyMethod(method) << " "
1485 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001486 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001487 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001488 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001489}
1490
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001491OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001492 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001493 auto it = osr_code_map_.find(method);
1494 if (it == osr_code_map_.end()) {
1495 return nullptr;
1496 }
1497 return OatQuickMethodHeader::FromCodePointer(it->second);
1498}
1499
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001500ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1501 ArtMethod* method,
1502 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001503 bool retry_allocation)
1504 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1505 NO_THREAD_SAFETY_ANALYSIS {
1506 ProfilingInfo* info = nullptr;
1507 if (!retry_allocation) {
1508 // If we are allocating for the interpreter, just try to lock, to avoid
1509 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001510 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001511 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001512 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001513 }
1514 } else {
1515 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001516 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001517 info = AddProfilingInfoInternal(self, method, entries);
1518 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001519
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001520 if (info == nullptr) {
1521 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001522 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001523 info = AddProfilingInfoInternal(self, method, entries);
1524 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001525 }
1526 return info;
1527}
1528
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001529ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001530 ArtMethod* method,
1531 const std::vector<uint32_t>& entries) {
1532 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001533 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001534 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001535
1536 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001537 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001538 if (info != nullptr) {
1539 return info;
1540 }
1541
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001542 uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001543 if (data == nullptr) {
1544 return nullptr;
1545 }
1546 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001547
1548 // Make sure other threads see the data in the profiling info object before the
1549 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001550 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001551
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001552 method->SetProfilingInfo(info);
1553 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001554 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001555 return info;
1556}
1557
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001558void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
1559 return private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001560}
1561
Calin Juravle99629622016-04-19 16:33:46 +01001562void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001563 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001564 Thread* self = Thread::Current();
1565 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001566 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001567 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001568 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001569 for (const ProfilingInfo* info : profiling_infos_) {
1570 ArtMethod* method = info->GetMethod();
1571 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001572 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1573 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001574 // Skip dex files which are not profiled.
1575 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001576 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001577 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001578
1579 // If the method didn't reach the compilation threshold don't save the inline caches.
1580 // They might be incomplete and cause unnecessary deoptimizations.
1581 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1582 if (method->GetCounter() < jit_compile_threshold) {
1583 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001584 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001585 continue;
1586 }
1587
Calin Juravle940eb0c2017-01-30 19:30:44 -08001588 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001589 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001590 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001591 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001592 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001593 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1594 mirror::Class* cls = cache.classes_[k].Read();
1595 if (cls == nullptr) {
1596 break;
1597 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001598
Calin Juravle13439f02017-02-21 01:17:21 -08001599 // Check if the receiver is in the boot class path or if it's in the
1600 // same class loader as the caller. If not, skip it, as there is not
1601 // much we can do during AOT.
1602 if (!cls->IsBootStrapClassLoaded() &&
1603 caller->GetClassLoader() != cls->GetClassLoader()) {
1604 is_missing_types = true;
1605 continue;
1606 }
1607
Calin Juravle4ca70a32017-02-21 16:22:24 -08001608 const DexFile* class_dex_file = nullptr;
1609 dex::TypeIndex type_index;
1610
1611 if (cls->GetDexCache() == nullptr) {
1612 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001613 // Make a best effort to find the type index in the method's dex file.
1614 // We could search all open dex files but that might turn expensive
1615 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001616 class_dex_file = dex_file;
1617 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1618 } else {
1619 class_dex_file = &(cls->GetDexFile());
1620 type_index = cls->GetDexTypeIndex();
1621 }
1622 if (!type_index.IsValid()) {
1623 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001624 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001625 continue;
1626 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001627 if (ContainsElement(dex_base_locations,
1628 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001629 // Only consider classes from the same apk (including multidex).
1630 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001631 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001632 } else {
1633 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001634 }
1635 }
1636 if (!profile_classes.empty()) {
1637 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001638 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001639 }
1640 }
1641 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001642 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001643 }
1644}
1645
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001646bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001647 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001648 return osr_code_map_.find(method) != osr_code_map_.end();
1649}
1650
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001651bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr, bool prejit) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001652 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001653 return false;
1654 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001655
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001656 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1657 if (class_linker->IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001658 if (!prejit) {
1659 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1660 // update the entrypoint due to having the resolution stub.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001661 VLOG(jit) << "Not compiling "
1662 << method->PrettyMethod()
1663 << " because it has the resolution stub";
1664 // Give it a new chance to be hot.
1665 ClearMethodCounter(method, /*was_warm=*/ false);
1666 return false;
1667 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001668 }
1669
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001670 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001671 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1672 return false;
1673 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001674
Vladimir Marko2196c652017-11-30 16:16:07 +00001675 if (UNLIKELY(method->IsNative())) {
1676 JniStubKey key(method);
1677 auto it = jni_stubs_map_.find(key);
1678 bool new_compilation = false;
1679 if (it == jni_stubs_map_.end()) {
1680 // Create a new entry to mark the stub as being compiled.
1681 it = jni_stubs_map_.Put(key, JniStubData{});
1682 new_compilation = true;
1683 }
1684 JniStubData* data = &it->second;
1685 data->AddMethod(method);
1686 if (data->IsCompiled()) {
1687 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1688 const void* entrypoint = method_header->GetEntryPoint();
1689 // Update also entrypoints of other methods held by the JniStubData.
1690 // We could simply update the entrypoint of `method` but if the last JIT GC has
1691 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1692 // as well change them back as this stub shall not be collected anyway and this
1693 // can avoid a few expensive GenericJNI calls.
1694 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1695 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001696 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1697 // `m` might be in the process of being deleted.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001698 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
1699 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
1700 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001701 }
1702 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001703 if (!IsInZygoteExecSpace(data->GetCode())) {
1704 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1705 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001706 }
1707 }
1708 return new_compilation;
1709 } else {
1710 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1711 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001712 // When prejitting, we don't allocate a profiling info.
1713 if (!prejit) {
1714 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1715 // Because the counter is not atomic, there are some rare cases where we may not hit the
1716 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1717 ClearMethodCounter(method, /*was_warm=*/ false);
1718 return false;
1719 }
1720 } else {
1721 if (info->IsMethodBeingCompiled(osr)) {
1722 return false;
1723 }
1724 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00001725 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001726 return true;
1727 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001728}
1729
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001730ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001731 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001732 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001733 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001734 if (!info->IncrementInlineUse()) {
1735 // Overflow of inlining uses, just bail.
1736 return nullptr;
1737 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001738 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001739 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001740}
1741
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001742void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001743 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001744 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001745 DCHECK(info != nullptr);
1746 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001747}
1748
Vladimir Marko2196c652017-11-30 16:16:07 +00001749void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1750 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001751 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001752 if (UNLIKELY(method->IsNative())) {
1753 auto it = jni_stubs_map_.find(JniStubKey(method));
1754 DCHECK(it != jni_stubs_map_.end());
1755 JniStubData* data = &it->second;
1756 DCHECK(ContainsElement(data->GetMethods(), method));
1757 if (UNLIKELY(!data->IsCompiled())) {
1758 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1759 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1760 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1761 } else {
1762 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001763 if (info != nullptr) {
1764 DCHECK(info->IsMethodBeingCompiled(osr));
1765 info->SetIsMethodBeingCompiled(false, osr);
1766 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001767 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001768}
1769
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001770void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1771 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001772 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001773 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001774 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001775 if ((profiling_info != nullptr) &&
1776 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001777 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1778 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001779 // Prevent future uses of the compiled code.
1780 profiling_info->SetSavedEntryPoint(nullptr);
1781 }
1782
Alex Light2d441b12018-06-08 15:33:21 -07001783 // Clear the method counter if we are running jitted code since we might want to jit this again in
1784 // the future.
1785 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001786 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001787 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001788 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1789 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001790 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001791 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001792 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001793 auto it = osr_code_map_.find(method);
1794 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1795 // Remove the OSR method, to avoid using it again.
1796 osr_code_map_.erase(it);
1797 }
1798 }
1799}
1800
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001801void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001802 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1803 os << "Current JIT code cache size: " << PrettySize(private_region_.GetUsedMemoryForCode())
1804 << "\n"
1805 << "Current JIT data cache size: " << PrettySize(private_region_.GetUsedMemoryForData())
1806 << "\n"
David Srbeckyafc60cd2018-12-05 11:59:31 +00001807 << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001808 << "Current JIT capacity: " << PrettySize(private_region_.GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001809 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001810 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1811 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1812 << "Total number of JIT compilations for on stack replacement: "
1813 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001814 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001815 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1816 histogram_code_memory_use_.PrintMemoryUse(os);
1817 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001818}
1819
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001820void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001821 if (is_zygote) {
1822 // Don't transition if this is for a child zygote.
1823 return;
1824 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001825 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001826
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001827 shared_region_ = std::move(private_region_);
1828
1829 // Reset all statistics to be specific to this process.
1830 number_of_compilations_ = 0;
1831 number_of_osr_compilations_ = 0;
1832 number_of_collections_ = 0;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001833
1834 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1835 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
1836
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001837 private_region_.InitializeState(initial_capacity, max_capacity);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001838
1839 std::string error_msg;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001840 if (!private_region_.InitializeMappings(
1841 /* rwx_memory_allowed= */ !is_system_server, is_zygote, &error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001842 LOG(WARNING) << "Could not reset JIT state after zygote fork: " << error_msg;
1843 return;
1844 }
1845
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001846 private_region_.InitializeSpaces();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001847}
1848
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001849} // namespace jit
1850} // namespace art