blob: 300225e64645df10ec1bca7e9949fb29fd1cb50d [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Andreas Gampec7d878d2018-11-19 18:42:06 +000021#include <android-base/logging.h>
Orion Hodson1d3fd082018-09-28 09:38:35 +010022
Andreas Gampe5629d2d2017-05-15 16:28:13 -070023#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070025#include "base/enums.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070026#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080027#include "base/logging.h" // For VLOG.
Orion Hodson563ada22018-09-04 11:28:31 +010028#include "base/membarrier.h"
Orion Hodson1d3fd082018-09-28 09:38:35 +010029#include "base/memfd.h"
David Sehr79e26072018-04-06 17:58:50 -070030#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010034#include "base/time_utils.h"
Orion Hodsonf2331362018-07-11 15:14:10 +010035#include "base/utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070036#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000037#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file_loader.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070039#include "dex/method_reference.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010040#include "entrypoints/runtime_asm_entrypoints.h"
41#include "gc/accounting/bitmap-inl.h"
Andreas Gampe88dbad32018-06-26 19:54:12 -070042#include "gc/allocator/dlmalloc.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010043#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000044#include "handle.h"
Andreas Gampef0f3c592018-06-26 13:28:00 -070045#include "instrumentation.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070046#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000047#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000048#include "jit/profiling_info.h"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +010049#include "jit/jit_scoped_code_cache_write.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010050#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080051#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070052#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070053#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070054#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070055#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070056#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000057#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010058#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080059
60namespace art {
61namespace jit {
62
Nicolas Geoffray933330a2016-03-16 14:20:06 +000063static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
64static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
65
Vladimir Marko2196c652017-11-30 16:16:07 +000066class JitCodeCache::JniStubKey {
67 public:
68 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
69 : shorty_(method->GetShorty()),
70 is_static_(method->IsStatic()),
71 is_fast_native_(method->IsFastNative()),
72 is_critical_native_(method->IsCriticalNative()),
73 is_synchronized_(method->IsSynchronized()) {
74 DCHECK(!(is_fast_native_ && is_critical_native_));
75 }
76
77 bool operator<(const JniStubKey& rhs) const {
78 if (is_static_ != rhs.is_static_) {
79 return rhs.is_static_;
80 }
81 if (is_synchronized_ != rhs.is_synchronized_) {
82 return rhs.is_synchronized_;
83 }
84 if (is_fast_native_ != rhs.is_fast_native_) {
85 return rhs.is_fast_native_;
86 }
87 if (is_critical_native_ != rhs.is_critical_native_) {
88 return rhs.is_critical_native_;
89 }
90 return strcmp(shorty_, rhs.shorty_) < 0;
91 }
92
93 // Update the shorty to point to another method's shorty. Call this function when removing
94 // the method that references the old shorty from JniCodeData and not removing the entire
95 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
96 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
97 const char* shorty = method->GetShorty();
98 DCHECK_STREQ(shorty_, shorty);
99 shorty_ = shorty;
100 }
101
102 private:
103 // The shorty points to a DexFile data and may need to change
104 // to point to the same shorty in a different DexFile.
105 mutable const char* shorty_;
106
107 const bool is_static_;
108 const bool is_fast_native_;
109 const bool is_critical_native_;
110 const bool is_synchronized_;
111};
112
113class JitCodeCache::JniStubData {
114 public:
115 JniStubData() : code_(nullptr), methods_() {}
116
117 void SetCode(const void* code) {
118 DCHECK(code != nullptr);
119 code_ = code;
120 }
121
122 const void* GetCode() const {
123 return code_;
124 }
125
126 bool IsCompiled() const {
127 return GetCode() != nullptr;
128 }
129
130 void AddMethod(ArtMethod* method) {
131 if (!ContainsElement(methods_, method)) {
132 methods_.push_back(method);
133 }
134 }
135
136 const std::vector<ArtMethod*>& GetMethods() const {
137 return methods_;
138 }
139
140 void RemoveMethodsIn(const LinearAlloc& alloc) {
141 auto kept_end = std::remove_if(
142 methods_.begin(),
143 methods_.end(),
144 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
145 methods_.erase(kept_end, methods_.end());
146 }
147
148 bool RemoveMethod(ArtMethod* method) {
149 auto it = std::find(methods_.begin(), methods_.end(), method);
150 if (it != methods_.end()) {
151 methods_.erase(it);
152 return true;
153 } else {
154 return false;
155 }
156 }
157
158 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
159 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
160 }
161
162 private:
163 const void* code_;
164 std::vector<ArtMethod*> methods_;
165};
166
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000167JitCodeCache* JitCodeCache::Create(bool used_only_for_profile_data,
168 bool rwx_memory_allowed,
169 bool is_zygote,
170 std::string* error_msg) {
171 // Register for membarrier expedited sync core if JIT will be generating code.
172 if (!used_only_for_profile_data) {
173 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
174 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
175 // flushed and it's used when adding code to the JIT. The memory used by the new code may
176 // have just been released and, in theory, the old code could still be in a pipeline.
177 VLOG(jit) << "Kernel does not support membarrier sync-core";
178 }
179 }
180
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100181 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000182 // Check whether the provided max capacity in options is below 1GB.
183 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
184 // We need to have 32 bit offsets from method headers in code cache which point to things
185 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
186 // Ensure we're below 1 GB to be safe.
187 if (max_capacity > 1 * GB) {
188 std::ostringstream oss;
189 oss << "Maxium code cache capacity is limited to 1 GB, "
190 << PrettySize(max_capacity) << " is too big";
191 *error_msg = oss.str();
192 return nullptr;
193 }
194
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100195 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100196 JitMemoryRegion region;
197 if (!region.Initialize(initial_capacity,
198 max_capacity,
199 rwx_memory_allowed,
200 is_zygote,
201 error_msg)) {
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000202 return nullptr;
203 }
204
Nicolas Geoffray9c54e182019-06-18 10:42:52 +0100205 std::unique_ptr<JitCodeCache> jit_code_cache(new JitCodeCache());
206 if (is_zygote) {
207 // Zygote should never collect code to share the memory with the children.
208 jit_code_cache->garbage_collect_code_ = false;
209 }
210 jit_code_cache->private_region_ = std::move(region);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +0000211
212 VLOG(jit) << "Created jit code cache: initial capacity="
213 << PrettySize(initial_capacity)
214 << ", maximum capacity="
215 << PrettySize(max_capacity);
216
217 return jit_code_cache.release();
218}
219
220JitCodeCache::JitCodeCache()
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100221 : is_weak_access_enabled_(true),
222 inline_cache_cond_("Jit inline cache condition variable", *Locks::jit_lock_),
223 lock_cond_("Jit code cache condition variable", *Locks::jit_lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100224 collection_in_progress_(false),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000225 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100226 garbage_collect_code_(true),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000227 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000228 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000229 number_of_collections_(0),
230 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
231 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100232 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800233}
234
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000235JitCodeCache::~JitCodeCache() {}
236
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100238 return private_region_.IsInExecSpace(ptr) || shared_region_.IsInExecSpace(ptr);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800239}
240
Alex Light2d441b12018-06-08 15:33:21 -0700241bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
242 ScopedObjectAccess soa(art::Thread::Current());
243 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
244 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
245 return true;
246 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
247 return FindCompiledCodeForInstrumentation(method) != nullptr;
248 }
249 return false;
250}
251
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000252bool JitCodeCache::ContainsMethod(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100253 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000254 if (UNLIKELY(method->IsNative())) {
255 auto it = jni_stubs_map_.find(JniStubKey(method));
256 if (it != jni_stubs_map_.end() &&
257 it->second.IsCompiled() &&
258 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000259 return true;
260 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000261 } else {
262 for (const auto& it : method_code_map_) {
263 if (it.second == method) {
264 return true;
265 }
266 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000267 }
268 return false;
269}
270
Vladimir Marko2196c652017-11-30 16:16:07 +0000271const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
272 DCHECK(method->IsNative());
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100273 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000274 auto it = jni_stubs_map_.find(JniStubKey(method));
275 if (it != jni_stubs_map_.end()) {
276 JniStubData& data = it->second;
277 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
278 return data.GetCode();
279 }
280 }
281 return nullptr;
282}
283
Alex Light2d441b12018-06-08 15:33:21 -0700284const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700285 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
286 // find the instrumentation entrypoint.
287 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700288 return nullptr;
289 }
290 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
291 if (info == nullptr) {
292 return nullptr;
293 }
294 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
295 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
296 // nullptr.
297 return info->GetSavedEntryPoint();
298}
299
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100300const void* JitCodeCache::GetZygoteSavedEntryPoint(ArtMethod* method) {
David Srbecky3db3d372019-04-17 18:19:17 +0100301 if (Runtime::Current()->IsUsingApexBootImageLocation() &&
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100302 // Currently only applies to boot classpath
303 method->GetDeclaringClass()->GetClassLoader() == nullptr) {
304 const void* entry_point = nullptr;
305 if (method->IsNative()) {
306 const void* code_ptr = GetJniStubCode(method);
307 if (code_ptr != nullptr) {
308 entry_point = OatQuickMethodHeader::FromCodePointer(code_ptr)->GetEntryPoint();
309 }
Nicolas Geoffraya3b31ba2019-04-14 20:10:16 +0100310 } else {
311 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
312 if (profiling_info != nullptr) {
313 entry_point = profiling_info->GetSavedEntryPoint();
314 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100315 }
316 if (Runtime::Current()->IsZygote() || IsInZygoteExecSpace(entry_point)) {
317 return entry_point;
318 }
319 }
320 return nullptr;
321}
322
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100323uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100324 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100325 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000326 uint8_t* stack_map,
327 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100328 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000329 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100330 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000331 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100332 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700333 bool has_should_deoptimize_flag,
334 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100335 uint8_t* result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100336 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100337 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000338 stack_map,
339 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100340 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000341 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100342 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000343 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700344 roots,
345 has_should_deoptimize_flag,
346 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100347 if (result == nullptr) {
348 // Retry.
349 GarbageCollectCache(self);
350 result = CommitCodeInternal(self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100351 region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100352 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000353 stack_map,
354 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100355 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000356 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100357 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000358 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700359 roots,
360 has_should_deoptimize_flag,
361 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100362 }
363 return result;
364}
365
366bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
367 bool in_collection = false;
368 while (collection_in_progress_) {
369 in_collection = true;
370 lock_cond_.Wait(self);
371 }
372 return in_collection;
373}
374
375static uintptr_t FromCodeToAllocation(const void* code) {
Orion Hodson521ff982019-06-18 13:56:28 +0100376 size_t alignment = GetJitCodeAlignment();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100377 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
378}
379
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000380static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
381 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
382}
383
384static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
385 // The length of the table is stored just before the stack map (and therefore at the end of
386 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
387 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
388}
389
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800390static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
391 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
392 // pointer.
393 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
394}
395
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000396static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
397 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
398}
399
Vladimir Markoac3ac682018-09-20 11:01:43 +0100400static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700401 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
402 if (!kIsDebugBuild) {
403 return;
404 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700405 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100406 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700407 // Ensure the string is strongly interned. b/32995596
408 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100409 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700410 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
411 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
412 }
413 }
414}
415
416void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100417 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000418 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100419 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000420 // Put all roots in `roots_data`.
421 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100422 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000423 gc_roots[i] = GcRoot<mirror::Object>(object);
424 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000425}
426
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100427static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000428 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
429 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
430 uint32_t roots = GetNumberOfRoots(data);
431 if (number_of_roots != nullptr) {
432 *number_of_roots = roots;
433 }
434 return data - ComputeRootTableSize(roots);
435}
436
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100437// Use a sentinel for marking entries in the JIT table that have been cleared.
438// This helps diagnosing in case the compiled code tries to wrongly access such
439// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700440static mirror::Class* const weak_sentinel =
441 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100442
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000443// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100444static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
445 IsMarkedVisitor* visitor,
446 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000447 REQUIRES_SHARED(Locks::mutator_lock_) {
448 // This does not need a read barrier because this is called by GC.
449 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100450 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700451 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000452 // Look at the classloader of the class to know if it has been unloaded.
453 // This does not need a read barrier because this is called by GC.
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000454 ObjPtr<mirror::Object> class_loader =
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000455 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000456 if (class_loader == nullptr || visitor->IsMarked(class_loader.Ptr()) != nullptr) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000457 // The class loader is live, update the entry if the class has moved.
458 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
459 // Note that new_object can be null for CMS and newly allocated objects.
460 if (new_cls != nullptr && new_cls != cls) {
461 *root_ptr = GcRoot<mirror::Class>(new_cls);
462 }
463 } else {
464 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100465 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000466 }
467 }
468}
469
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000470void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100471 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000472 for (const auto& entry : method_code_map_) {
473 uint32_t number_of_roots = 0;
474 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
475 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
476 for (uint32_t i = 0; i < number_of_roots; ++i) {
477 // This does not need a read barrier because this is called by GC.
478 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100479 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000480 // entry got deleted in a previous sweep.
Vladimir Markod355acf2019-03-21 17:09:40 +0000481 } else if (object->IsString<kDefaultVerifyFlags>()) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000482 mirror::Object* new_object = visitor->IsMarked(object);
483 // We know the string is marked because it's a strongly-interned string that
484 // is always alive. The IsMarked implementation of the CMS collector returns
485 // null for newly allocated objects, but we know those haven't moved. Therefore,
486 // only update the entry if we get a different non-null string.
487 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
488 // out of the weak access/creation pause. b/32167580
489 if (new_object != nullptr && new_object != object) {
490 DCHECK(new_object->IsString());
491 roots[i] = GcRoot<mirror::Object>(new_object);
492 }
493 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100494 ProcessWeakClass(
495 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000496 }
497 }
498 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000499 // Walk over inline caches to clear entries containing unloaded classes.
500 for (ProfilingInfo* info : profiling_infos_) {
501 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
502 InlineCache* cache = &info->cache_[i];
503 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100504 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000505 }
506 }
507 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000508}
509
Orion Hodson607624f2018-05-11 10:10:46 +0100510void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Nicolas Geoffrayae982f92018-12-08 12:31:10 +0000511 if (IsInZygoteExecSpace(code_ptr)) {
512 // No need to free, this is shared memory.
513 return;
514 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100515 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000516 // Notify native debugger that we are about to remove the code.
517 // It does nothing if we are not using native debugger.
David Srbeckyafc60cd2018-12-05 11:59:31 +0000518 RemoveNativeDebugInfoForJit(Thread::Current(), code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000519 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100520 private_region_.FreeData(GetRootTable(code_ptr));
Vladimir Marko2196c652017-11-30 16:16:07 +0000521 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100522
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100523 private_region_.FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100524}
525
Mingyao Yang063fc772016-08-02 11:02:54 -0700526void JitCodeCache::FreeAllMethodHeaders(
527 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700528 // We need to remove entries in method_headers from CHA dependencies
529 // first since once we do FreeCode() below, the memory can be reused
530 // so it's possible for the same method_header to start representing
531 // different compile code.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100532 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000533 {
534 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
535 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
536 ->RemoveDependentsWithMethodHeaders(method_headers);
537 }
538
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100539 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700540 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100541 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700542 }
543}
544
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100545void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800546 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700547 // We use a set to first collect all method_headers whose code need to be
548 // removed. We need to free the underlying code after we remove CHA dependencies
549 // for entries in this set. And it's more efficient to iterate through
550 // the CHA dependency map just once with an unordered_set.
551 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000552 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100553 MutexLock mu(self, *Locks::jit_lock_);
Mingyao Yang063fc772016-08-02 11:02:54 -0700554 // We do not check if a code cache GC is in progress, as this method comes
555 // with the classlinker_classes_lock_ held, and suspending ourselves could
556 // lead to a deadlock.
557 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100558 ScopedCodeCacheWrite scc(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000559 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
560 it->second.RemoveMethodsIn(alloc);
561 if (it->second.GetMethods().empty()) {
562 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
563 it = jni_stubs_map_.erase(it);
564 } else {
565 it->first.UpdateShorty(it->second.GetMethods().front());
566 ++it;
567 }
568 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700569 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
570 if (alloc.ContainsUnsafe(it->second)) {
571 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
572 it = method_code_map_.erase(it);
573 } else {
574 ++it;
575 }
576 }
577 }
578 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
579 if (alloc.ContainsUnsafe(it->first)) {
580 // Note that the code has already been pushed to method_headers in the loop
581 // above and is going to be removed in FreeCode() below.
582 it = osr_code_map_.erase(it);
583 } else {
584 ++it;
585 }
586 }
587 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
588 ProfilingInfo* info = *it;
589 if (alloc.ContainsUnsafe(info->GetMethod())) {
590 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100591 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Mingyao Yang063fc772016-08-02 11:02:54 -0700592 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000593 } else {
594 ++it;
595 }
596 }
597 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700598 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100599}
600
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000601bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
602 return kUseReadBarrier
603 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000604 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000605}
606
607void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
608 if (IsWeakAccessEnabled(self)) {
609 return;
610 }
611 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100612 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000613 while (!IsWeakAccessEnabled(self)) {
614 inline_cache_cond_.Wait(self);
615 }
616}
617
618void JitCodeCache::BroadcastForInlineCacheAccess() {
619 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100620 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000621 inline_cache_cond_.Broadcast(self);
622}
623
624void JitCodeCache::AllowInlineCacheAccess() {
625 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000626 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000627 BroadcastForInlineCacheAccess();
628}
629
630void JitCodeCache::DisallowInlineCacheAccess() {
631 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000632 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000633}
634
635void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
636 Handle<mirror::ObjectArray<mirror::Class>> array) {
637 WaitUntilInlineCacheAccessible(Thread::Current());
638 // Note that we don't need to lock `lock_` here, the compiler calling
639 // this method has already ensured the inline cache will not be deleted.
640 for (size_t in_cache = 0, in_array = 0;
641 in_cache < InlineCache::kIndividualCacheSize;
642 ++in_cache) {
643 mirror::Class* object = ic.classes_[in_cache].Read();
644 if (object != nullptr) {
645 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000646 }
647 }
648}
649
David Srbeckye36e7f22018-11-14 14:21:23 +0000650static void ClearMethodCounter(ArtMethod* method, bool was_warm)
651 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf044c222017-05-31 15:27:54 -0700652 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100653 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700654 }
655 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
656 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100657 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
658 // the warmup threshold is 1.
659 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
660 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700661}
662
Alex Light33b7b5d2018-08-07 19:13:51 +0000663void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
664 while (collection_in_progress_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100665 Locks::jit_lock_->Unlock(self);
Alex Light33b7b5d2018-08-07 19:13:51 +0000666 {
667 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100668 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000669 WaitForPotentialCollectionToComplete(self);
670 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100671 Locks::jit_lock_->Lock(self);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100672 }
673}
674
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100675uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100676 JitMemoryRegion* region,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100677 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000678 uint8_t* stack_map,
679 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100680 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000681 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100682 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000683 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100684 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700685 bool has_should_deoptimize_flag,
686 const ArenaSet<ArtMethod*>&
687 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000688 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000689
690 if (!method->IsNative()) {
691 // We need to do this before grabbing the lock_ because it needs to be able to see the string
692 // InternTable. Native methods do not have roots.
693 DCheckRootsAreValid(roots);
694 }
695
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100696 MutexLock mu(self, *Locks::jit_lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000697 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
698 // finish.
699 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100700 const uint8_t* code_ptr = region->AllocateCode(
701 code, code_size, stack_map, has_should_deoptimize_flag);
702 if (code_ptr == nullptr) {
703 return nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100704 }
Nicolas Geoffray349845a2019-06-19 13:13:10 +0100705 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
706
707 number_of_compilations_++;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100708
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000709 // We need to update the entry point in the runnable state for the instrumentation.
710 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000711 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
712 // compiled code is considered invalidated by some class linking, but below we still make the
713 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
714 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -0700715 MutexLock cha_mu(self, *Locks::cha_lock_);
716 bool single_impl_still_valid = true;
717 for (ArtMethod* single_impl : cha_single_implementation_list) {
718 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700719 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
720 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700721 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700722 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700723 break;
724 }
725 }
726
727 // Discard the code if any single-implementation assumptions are now invalid.
Orion Hodson31492522019-06-18 12:13:49 +0100728 if (UNLIKELY(!single_impl_still_valid)) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700729 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
Orion Hodson31492522019-06-18 12:13:49 +0100730 ScopedCodeCacheWrite ccw(*region);
731 uintptr_t allocation = FromCodeToAllocation(code_ptr);
732 region->FreeCode(reinterpret_cast<uint8_t*>(allocation));
Mingyao Yang063fc772016-08-02 11:02:54 -0700733 return nullptr;
734 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000735 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800736 << "Should not be using cha on debuggable apps/runs!";
737
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100738 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mingyao Yang063fc772016-08-02 11:02:54 -0700739 for (ArtMethod* single_impl : cha_single_implementation_list) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100740 class_linker->GetClassHierarchyAnalysis()->AddDependency(single_impl, method, method_header);
Mingyao Yang063fc772016-08-02 11:02:54 -0700741 }
742
Vladimir Marko2196c652017-11-30 16:16:07 +0000743 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000744 auto it = jni_stubs_map_.find(JniStubKey(method));
745 DCHECK(it != jni_stubs_map_.end())
746 << "Entry inserted in NotifyCompilationOf() should be alive.";
747 JniStubData* data = &it->second;
748 DCHECK(ContainsElement(data->GetMethods(), method))
749 << "Entry inserted in NotifyCompilationOf() should contain this method.";
750 data->SetCode(code_ptr);
751 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
752 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100753 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
754 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
755 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000756 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100757 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000758 // Fill the root table before updating the entry point.
759 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
760 DCHECK_LE(roots_data, stack_map);
761 FillRootTable(roots_data, roots);
762 {
763 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +0100764 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +0000765 }
766 method_code_map_.Put(code_ptr, method);
767 if (osr) {
768 number_of_osr_compilations_++;
769 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +0100770 } else if (class_linker->IsQuickResolutionStub(
771 method->GetEntryPointFromQuickCompiledCode())) {
772 // This situation currently only occurs in the jit-zygote mode.
David Srbecky3db3d372019-04-17 18:19:17 +0100773 DCHECK(Runtime::Current()->IsUsingApexBootImageLocation());
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100774 DCHECK(!garbage_collect_code_);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100775 // TODO(ngeoffray): In most cases, the zygote will not have a profiling
776 // info for a compiled method. Use a map instead.
777 if (method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
778 // Save the entrypoint, so it can be fetched later once the class is
779 // initialized.
780 method->GetProfilingInfo(kRuntimePointerSize)->SetSavedEntryPoint(
781 method_header->GetEntryPoint());
782 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000783 } else {
784 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
785 method, method_header->GetEntryPoint());
786 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000787 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000788 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100789 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700790 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000791 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
792 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
793 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700794 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
795 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000796 histogram_code_memory_use_.AddValue(code_size);
797 if (code_size > kCodeSizeLogThreshold) {
798 LOG(INFO) << "JIT allocated "
799 << PrettySize(code_size)
800 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700801 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000802 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000803 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100804
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100805 return reinterpret_cast<uint8_t*>(method_header);
806}
807
808size_t JitCodeCache::CodeCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100809 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000810 return CodeCacheSizeLocked();
811}
812
Orion Hodsoneced6922017-06-01 10:54:28 +0100813bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000814 // This function is used only for testing and only with non-native methods.
815 CHECK(!method->IsNative());
816
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100817 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100818
Vladimir Marko2196c652017-11-30 16:16:07 +0000819 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
820 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100821
822 if (!in_cache) {
823 return false;
824 }
825
David Srbeckye36e7f22018-11-14 14:21:23 +0000826 method->SetCounter(0);
Orion Hodsoneced6922017-06-01 10:54:28 +0100827 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
828 method, GetQuickToInterpreterBridge());
829 VLOG(jit)
830 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
831 << ArtMethod::PrettyMethod(method) << "@" << method
832 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
833 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
834 return true;
835}
836
Vladimir Marko2196c652017-11-30 16:16:07 +0000837bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
838 if (LIKELY(!method->IsNative())) {
839 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
840 if (info != nullptr) {
841 RemoveElement(profiling_infos_, info);
842 }
843 method->SetProfilingInfo(nullptr);
844 }
845
846 bool in_cache = false;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100847 ScopedCodeCacheWrite ccw(private_region_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000848 if (UNLIKELY(method->IsNative())) {
849 auto it = jni_stubs_map_.find(JniStubKey(method));
850 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
851 in_cache = true;
852 if (it->second.GetMethods().empty()) {
853 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100854 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +0000855 }
856 jni_stubs_map_.erase(it);
857 } else {
858 it->first.UpdateShorty(it->second.GetMethods().front());
859 }
860 }
861 } else {
862 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
863 if (it->second == method) {
864 in_cache = true;
865 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +0100866 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +0000867 }
868 it = method_code_map_.erase(it);
869 } else {
870 ++it;
871 }
872 }
873
874 auto osr_it = osr_code_map_.find(method);
875 if (osr_it != osr_code_map_.end()) {
876 osr_code_map_.erase(osr_it);
877 }
878 }
879
880 return in_cache;
881}
882
Alex Lightdba61482016-12-21 08:20:29 -0800883// This notifies the code cache that the given method has been redefined and that it should remove
884// any cached information it has on the method. All threads must be suspended before calling this
885// method. The compiled code for the method (if there is any) must not be in any threads call stack.
886void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100887 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700888 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800889}
890
891// This invalidates old_method. Once this function returns one can no longer use old_method to
892// execute code unless it is fixed up. This fixup will happen later in the process of installing a
893// class redefinition.
894// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
895// shouldn't be used since it is no longer logically in the jit code cache.
896// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
897void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100898 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000899 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000900 // Update methods in jni_stubs_map_.
901 for (auto& entry : jni_stubs_map_) {
902 JniStubData& data = entry.second;
903 data.MoveObsoleteMethod(old_method, new_method);
904 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000905 return;
906 }
Alex Lightdba61482016-12-21 08:20:29 -0800907 // Update ProfilingInfo to the new one and remove it from the old_method.
908 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
909 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
910 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
911 old_method->SetProfilingInfo(nullptr);
912 // Since the JIT should be paused and all threads suspended by the time this is called these
913 // checks should always pass.
914 DCHECK(!info->IsInUseByCompiler());
915 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -0700916 // Get rid of the old saved entrypoint if it is there.
917 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -0800918 info->method_ = new_method;
919 }
920 // Update method_code_map_ to point to the new method.
921 for (auto& it : method_code_map_) {
922 if (it.second == old_method) {
923 it.second = new_method;
924 }
925 }
926 // Update osr_code_map_ to point to the new method.
927 auto code_map = osr_code_map_.find(old_method);
928 if (code_map != osr_code_map_.end()) {
929 osr_code_map_.Put(new_method, code_map->second);
930 osr_code_map_.erase(old_method);
931 }
932}
933
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000934void JitCodeCache::ClearEntryPointsInZygoteExecSpace() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100935 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000936 // Iterate over profiling infos to know which methods may have been JITted. Note that
937 // to be JITted, a method must have a profiling info.
938 for (ProfilingInfo* info : profiling_infos_) {
939 ArtMethod* method = info->GetMethod();
940 if (IsInZygoteExecSpace(method->GetEntryPointFromQuickCompiledCode())) {
941 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
942 }
943 // If zygote does method tracing, or in some configuration where
944 // the JIT zygote does GC, we also need to clear the saved entry point
945 // in the profiling info.
946 if (IsInZygoteExecSpace(info->GetSavedEntryPoint())) {
947 info->SetSavedEntryPoint(nullptr);
948 }
949 }
950}
951
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000952size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100953 return private_region_.GetUsedMemoryForCode();
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100954}
955
956size_t JitCodeCache::DataCacheSize() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100957 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000958 return DataCacheSizeLocked();
959}
960
961size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100962 return private_region_.GetUsedMemoryForData();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800963}
964
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000965void JitCodeCache::ClearData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100966 JitMemoryRegion* region,
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000967 uint8_t* stack_map_data,
968 uint8_t* roots_data) {
969 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100970 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100971 region->FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000972}
973
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000974size_t JitCodeCache::ReserveData(Thread* self,
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100975 JitMemoryRegion* region,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000976 size_t stack_map_size,
977 size_t number_of_roots,
978 ArtMethod* method,
979 uint8_t** stack_map_data,
980 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000981 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +0100982 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100983 uint8_t* result = nullptr;
984
985 {
986 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100987 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100988 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100989 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100990 }
991
992 if (result == nullptr) {
993 // Retry.
994 GarbageCollectCache(self);
995 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +0100996 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100997 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray7f7539b2019-06-06 16:20:54 +0100998 result = region->AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100999 }
1000
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001001 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001002 histogram_stack_map_memory_use_.AddValue(size);
1003 if (size > kStackMapSizeLogThreshold) {
1004 LOG(INFO) << "JIT allocated "
1005 << PrettySize(size)
1006 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001007 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001008 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001009 if (result != nullptr) {
1010 *roots_data = result;
1011 *stack_map_data = result + table_size;
1012 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001013 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001014 } else {
1015 *roots_data = nullptr;
1016 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001017 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001018 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001019}
1020
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001021class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001022 public:
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001023 MarkCodeClosure(JitCodeCache* code_cache, CodeCacheBitmap* bitmap, Barrier* barrier)
1024 : code_cache_(code_cache), bitmap_(bitmap), barrier_(barrier) {}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001025
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001026 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001027 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001028 DCHECK(thread == Thread::Current() || thread->IsSuspended());
Andreas Gampec7d878d2018-11-19 18:42:06 +00001029 StackVisitor::WalkStack(
1030 [&](const art::StackVisitor* stack_visitor) {
1031 const OatQuickMethodHeader* method_header =
1032 stack_visitor->GetCurrentOatQuickMethodHeader();
1033 if (method_header == nullptr) {
1034 return true;
1035 }
1036 const void* code = method_header->GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001037 if (code_cache_->ContainsPc(code) && !code_cache_->IsInZygoteExecSpace(code)) {
Andreas Gampec7d878d2018-11-19 18:42:06 +00001038 // Use the atomic set version, as multiple threads are executing this code.
1039 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1040 }
1041 return true;
1042 },
1043 thread,
1044 /* context= */ nullptr,
1045 art::StackVisitor::StackWalkKind::kSkipInlinedFrames);
1046
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001047 if (kIsDebugBuild) {
1048 // The stack walking code queries the side instrumentation stack if it
1049 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1050 // must have been seen. We sanity check this below.
1051 for (const instrumentation::InstrumentationStackFrame& frame
1052 : *thread->GetInstrumentationStack()) {
1053 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1054 // its stack frame, it is not the method owning return_pc_. We just pass null to
1055 // LookupMethodHeader: the method is only checked against in debug builds.
1056 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001057 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001058 if (method_header != nullptr) {
1059 const void* code = method_header->GetCode();
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001060 CHECK(bitmap_->Test(FromCodeToAllocation(code)));
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001061 }
1062 }
1063 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001064 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001065 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001066
1067 private:
1068 JitCodeCache* const code_cache_;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001069 CodeCacheBitmap* const bitmap_;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001070 Barrier* const barrier_;
1071};
1072
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001073void JitCodeCache::NotifyCollectionDone(Thread* self) {
1074 collection_in_progress_ = false;
1075 lock_cond_.Broadcast(self);
1076}
1077
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001078void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1079 Barrier barrier(0);
1080 size_t threads_running_checkpoint = 0;
Nicolas Geoffrayb9f1af52018-11-16 10:30:29 +00001081 MarkCodeClosure closure(this, GetLiveBitmap(), &barrier);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001082 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1083 // Now that we have run our checkpoint, move to a suspended state and wait
1084 // for other threads to run the checkpoint.
1085 ScopedThreadSuspension sts(self, kSuspended);
1086 if (threads_running_checkpoint != 0) {
1087 barrier.Increment(self, threads_running_checkpoint);
1088 }
1089}
1090
Nicolas Geoffray35122442016-03-02 12:05:30 +00001091bool JitCodeCache::ShouldDoFullCollection() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001092 if (private_region_.GetCurrentCapacity() == private_region_.GetMaxCapacity()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001093 // Always do a full collection when the code cache is full.
1094 return true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001095 } else if (private_region_.GetCurrentCapacity() < kReservedCapacity) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001096 // Always do partial collection when the code cache size is below the reserved
1097 // capacity.
1098 return false;
1099 } else if (last_collection_increased_code_cache_) {
1100 // This time do a full collection.
1101 return true;
1102 } else {
1103 // This time do a partial collection.
1104 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001105 }
1106}
1107
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001108void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001109 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001110 // Wait for an existing collection, or let everyone know we are starting one.
1111 {
1112 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001113 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001114 if (!garbage_collect_code_) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001115 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001116 return;
1117 } else if (WaitForPotentialCollectionToComplete(self)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001118 return;
1119 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001120 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001121 live_bitmap_.reset(CodeCacheBitmap::Create(
1122 "code-cache-bitmap",
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001123 reinterpret_cast<uintptr_t>(private_region_.GetExecPages()->Begin()),
1124 reinterpret_cast<uintptr_t>(
1125 private_region_.GetExecPages()->Begin() + private_region_.GetCurrentCapacity() / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001126 collection_in_progress_ = true;
1127 }
1128 }
1129
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001130 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001131 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001132 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001133
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001134 bool do_full_collection = false;
1135 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001136 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001137 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001138 }
1139
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001140 VLOG(jit) << "Do "
1141 << (do_full_collection ? "full" : "partial")
1142 << " code cache collection, code="
1143 << PrettySize(CodeCacheSize())
1144 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001145
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001146 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001147
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001148 VLOG(jit) << "After code cache collection, code="
1149 << PrettySize(CodeCacheSize())
1150 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001151
1152 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001153 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001154
1155 // Increase the code cache only when we do partial collections.
1156 // TODO: base this strategy on how full the code cache is?
1157 if (do_full_collection) {
1158 last_collection_increased_code_cache_ = false;
1159 } else {
1160 last_collection_increased_code_cache_ = true;
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001161 private_region_.IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001162 }
1163
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001164 bool next_collection_will_be_full = ShouldDoFullCollection();
1165
1166 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001167 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001168 // Save the entry point of methods we have compiled, and update the entry
1169 // point of those methods to the interpreter. If the method is invoked, the
1170 // interpreter will update its entry point to the compiled code and call it.
1171 for (ProfilingInfo* info : profiling_infos_) {
1172 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001173 if (!IsInZygoteDataSpace(info) && ContainsPc(entry_point)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001174 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001175 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001176 // class of the method. We may be concurrently running a GC which makes accessing
1177 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1178 // checked that the current entry point is JIT compiled code.
1179 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001180 }
1181 }
1182
Vladimir Marko2196c652017-11-30 16:16:07 +00001183 // Change entry points of native methods back to the GenericJNI entrypoint.
1184 for (const auto& entry : jni_stubs_map_) {
1185 const JniStubData& data = entry.second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001186 if (!data.IsCompiled() || IsInZygoteExecSpace(data.GetCode())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001187 continue;
1188 }
1189 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1190 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1191 const OatQuickMethodHeader* method_header =
1192 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1193 for (ArtMethod* method : data.GetMethods()) {
1194 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1195 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1196 method->SetCounter(new_counter);
1197 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1198 }
1199 }
1200 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001201 }
1202 live_bitmap_.reset(nullptr);
1203 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001204 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001205 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001206 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001207}
1208
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001209void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001210 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001211 std::unordered_set<OatQuickMethodHeader*> method_headers;
1212 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001213 MutexLock mu(self, *Locks::jit_lock_);
1214 ScopedCodeCacheWrite scc(private_region_);
Mingyao Yang063fc772016-08-02 11:02:54 -07001215 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001216 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1217 JniStubData* data = &it->second;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001218 if (IsInZygoteExecSpace(data->GetCode()) ||
1219 !data->IsCompiled() ||
1220 GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001221 ++it;
1222 } else {
1223 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1224 it = jni_stubs_map_.erase(it);
1225 }
1226 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001227 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1228 const void* code_ptr = it->first;
1229 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001230 if (IsInZygoteExecSpace(code_ptr) || GetLiveBitmap()->Test(allocation)) {
Mingyao Yang063fc772016-08-02 11:02:54 -07001231 ++it;
1232 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001233 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1234 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001235 it = method_code_map_.erase(it);
1236 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001237 }
1238 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001239 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001240}
1241
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001242bool JitCodeCache::GetGarbageCollectCode() {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001243 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001244 return garbage_collect_code_;
1245}
1246
1247void JitCodeCache::SetGarbageCollectCode(bool value) {
1248 Thread* self = Thread::Current();
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001249 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray226805d2018-12-14 10:59:02 +00001250 if (garbage_collect_code_ != value) {
1251 if (garbage_collect_code_) {
1252 // When dynamically disabling the garbage collection, we neee
1253 // to make sure that a potential current collection is finished, and also
1254 // clear the saved entry point in profiling infos to avoid dangling pointers.
1255 WaitForPotentialCollectionToComplete(self);
1256 for (ProfilingInfo* info : profiling_infos_) {
1257 info->SetSavedEntryPoint(nullptr);
1258 }
1259 }
1260 // Update the flag while holding the lock to ensure no thread will try to GC.
1261 garbage_collect_code_ = value;
1262 }
1263}
1264
Nicolas Geoffray35122442016-03-02 12:05:30 +00001265void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001266 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001267 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001268 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001269 if (collect_profiling_info) {
1270 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1271 // Also remove the saved entry point from the ProfilingInfo objects.
1272 for (ProfilingInfo* info : profiling_infos_) {
1273 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001274 if (!ContainsPc(ptr) && !info->IsInUseByCompiler() && !IsInZygoteDataSpace(info)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001275 info->GetMethod()->SetProfilingInfo(nullptr);
1276 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001277
1278 if (info->GetSavedEntryPoint() != nullptr) {
1279 info->SetSavedEntryPoint(nullptr);
1280 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001281 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001282 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001283 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001284 }
1285 } else if (kIsDebugBuild) {
1286 // Sanity check that the profiling infos do not have a dangling entry point.
1287 for (ProfilingInfo* info : profiling_infos_) {
David Srbecky605a5fe2019-04-24 14:05:21 +01001288 DCHECK(!Runtime::Current()->IsZygote());
1289 const void* entry_point = info->GetSavedEntryPoint();
1290 DCHECK(entry_point == nullptr || IsInZygoteExecSpace(entry_point));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001291 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001292 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001293
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001294 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1295 // an entry point is either:
1296 // - an osr compiled code, that will be removed if not in a thread call stack.
1297 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001298 for (const auto& entry : jni_stubs_map_) {
1299 const JniStubData& data = entry.second;
1300 const void* code_ptr = data.GetCode();
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001301 if (IsInZygoteExecSpace(code_ptr)) {
1302 continue;
1303 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001304 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1305 for (ArtMethod* method : data.GetMethods()) {
1306 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1307 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1308 break;
1309 }
1310 }
1311 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001312 for (const auto& it : method_code_map_) {
1313 ArtMethod* method = it.second;
1314 const void* code_ptr = it.first;
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001315 if (IsInZygoteExecSpace(code_ptr)) {
1316 continue;
1317 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001318 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1319 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1320 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1321 }
1322 }
1323
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001324 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001325 // on thread stacks).
1326 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001327 }
1328
1329 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001330 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001331
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001332 // At this point, mutator threads are still running, and entrypoints of methods can
1333 // change. We do know they cannot change to a code cache entry that is not marked,
1334 // therefore we can safely remove those entries.
1335 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001336
Nicolas Geoffray35122442016-03-02 12:05:30 +00001337 if (collect_profiling_info) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001338 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001339 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001340 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001341 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001342 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001343 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1344 // that the compiled code would not get revived. As mutator threads run concurrently,
1345 // they may have revived the compiled code, and now we are in the situation where
1346 // a method has compiled code but no ProfilingInfo.
1347 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1348 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001349 if (ContainsPc(ptr) &&
1350 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001351 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001352 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001353 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001354 private_region_.FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001355 return true;
1356 }
1357 return false;
1358 });
1359 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001360 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001361}
1362
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001363OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001364 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1365 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001366 // On Thumb-2, the pc is offset by one.
1367 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001368 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001369 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1370 return nullptr;
1371 }
1372
Vladimir Marko2196c652017-11-30 16:16:07 +00001373 if (!kIsDebugBuild) {
1374 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1375 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001376 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001377
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001378 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001379 OatQuickMethodHeader* method_header = nullptr;
1380 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1381 if (method != nullptr && UNLIKELY(method->IsNative())) {
1382 auto it = jni_stubs_map_.find(JniStubKey(method));
1383 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1384 return nullptr;
1385 }
1386 const void* code_ptr = it->second.GetCode();
1387 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1388 if (!method_header->Contains(pc)) {
1389 return nullptr;
1390 }
1391 } else {
1392 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1393 if (it != method_code_map_.begin()) {
1394 --it;
1395 const void* code_ptr = it->first;
1396 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1397 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1398 found_method = it->second;
1399 }
1400 }
1401 if (method_header == nullptr && method == nullptr) {
1402 // Scan all compiled JNI stubs as well. This slow search is used only
1403 // for checks in debug build, for release builds the `method` is not null.
1404 for (auto&& entry : jni_stubs_map_) {
1405 const JniStubData& data = entry.second;
1406 if (data.IsCompiled() &&
1407 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1408 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1409 }
1410 }
1411 }
1412 if (method_header == nullptr) {
1413 return nullptr;
1414 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001415 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001416
1417 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Vladimir Markoeab02482019-05-09 10:28:17 +01001418 DCHECK_EQ(found_method, method)
1419 << ArtMethod::PrettyMethod(method) << " "
1420 << ArtMethod::PrettyMethod(found_method) << " "
David Sehr709b0702016-10-13 09:12:37 -07001421 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001422 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001423 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001424}
1425
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001426OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001427 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001428 auto it = osr_code_map_.find(method);
1429 if (it == osr_code_map_.end()) {
1430 return nullptr;
1431 }
1432 return OatQuickMethodHeader::FromCodePointer(it->second);
1433}
1434
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001435ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1436 ArtMethod* method,
1437 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001438 bool retry_allocation)
1439 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1440 NO_THREAD_SAFETY_ANALYSIS {
1441 ProfilingInfo* info = nullptr;
1442 if (!retry_allocation) {
1443 // If we are allocating for the interpreter, just try to lock, to avoid
1444 // lock contention with the JIT.
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001445 if (Locks::jit_lock_->ExclusiveTryLock(self)) {
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001446 info = AddProfilingInfoInternal(self, method, entries);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001447 Locks::jit_lock_->ExclusiveUnlock(self);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001448 }
1449 } else {
1450 {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001451 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001452 info = AddProfilingInfoInternal(self, method, entries);
1453 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001454
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001455 if (info == nullptr) {
1456 GarbageCollectCache(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001457 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001458 info = AddProfilingInfoInternal(self, method, entries);
1459 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001460 }
1461 return info;
1462}
1463
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001464ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001465 ArtMethod* method,
1466 const std::vector<uint32_t>& entries) {
1467 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001468 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001469 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001470
1471 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001472 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001473 if (info != nullptr) {
1474 return info;
1475 }
1476
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001477 uint8_t* data = private_region_.AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001478 if (data == nullptr) {
1479 return nullptr;
1480 }
1481 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001482
1483 // Make sure other threads see the data in the profiling info object before the
1484 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001485 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001486
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001487 method->SetProfilingInfo(info);
1488 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001489 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001490 return info;
1491}
1492
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001493void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) {
1494 return private_region_.MoreCore(mspace, increment);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001495}
1496
Calin Juravle99629622016-04-19 16:33:46 +01001497void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001498 std::vector<ProfileMethodInfo>& methods) {
Nicolas Geoffray1afdfe62018-11-21 09:38:10 +00001499 Thread* self = Thread::Current();
1500 WaitUntilInlineCacheAccessible(self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001501 MutexLock mu(self, *Locks::jit_lock_);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001502 ScopedTrace trace(__FUNCTION__);
Calin Juravlea39fd982017-05-18 10:15:52 -07001503 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001504 for (const ProfilingInfo* info : profiling_infos_) {
1505 ArtMethod* method = info->GetMethod();
1506 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001507 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1508 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001509 // Skip dex files which are not profiled.
1510 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001511 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001512 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001513
1514 // If the method didn't reach the compilation threshold don't save the inline caches.
1515 // They might be incomplete and cause unnecessary deoptimizations.
1516 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1517 if (method->GetCounter() < jit_compile_threshold) {
1518 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001519 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001520 continue;
1521 }
1522
Calin Juravle940eb0c2017-01-30 19:30:44 -08001523 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001524 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001525 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001526 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001527 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001528 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1529 mirror::Class* cls = cache.classes_[k].Read();
1530 if (cls == nullptr) {
1531 break;
1532 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001533
Calin Juravle13439f02017-02-21 01:17:21 -08001534 // Check if the receiver is in the boot class path or if it's in the
1535 // same class loader as the caller. If not, skip it, as there is not
1536 // much we can do during AOT.
1537 if (!cls->IsBootStrapClassLoaded() &&
1538 caller->GetClassLoader() != cls->GetClassLoader()) {
1539 is_missing_types = true;
1540 continue;
1541 }
1542
Calin Juravle4ca70a32017-02-21 16:22:24 -08001543 const DexFile* class_dex_file = nullptr;
1544 dex::TypeIndex type_index;
1545
1546 if (cls->GetDexCache() == nullptr) {
1547 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001548 // Make a best effort to find the type index in the method's dex file.
1549 // We could search all open dex files but that might turn expensive
1550 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001551 class_dex_file = dex_file;
1552 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1553 } else {
1554 class_dex_file = &(cls->GetDexFile());
1555 type_index = cls->GetDexTypeIndex();
1556 }
1557 if (!type_index.IsValid()) {
1558 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001559 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001560 continue;
1561 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001562 if (ContainsElement(dex_base_locations,
1563 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001564 // Only consider classes from the same apk (including multidex).
1565 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001566 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001567 } else {
1568 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001569 }
1570 }
1571 if (!profile_classes.empty()) {
1572 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001573 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001574 }
1575 }
1576 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001577 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001578 }
1579}
1580
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001581bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001582 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001583 return osr_code_map_.find(method) != osr_code_map_.end();
1584}
1585
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001586bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr, bool prejit) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001587 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001588 return false;
1589 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001590
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001591 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1592 if (class_linker->IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001593 if (!prejit) {
1594 // Unless we're pre-jitting, we currently don't save the JIT compiled code if we cannot
1595 // update the entrypoint due to having the resolution stub.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001596 VLOG(jit) << "Not compiling "
1597 << method->PrettyMethod()
1598 << " because it has the resolution stub";
1599 // Give it a new chance to be hot.
1600 ClearMethodCounter(method, /*was_warm=*/ false);
1601 return false;
1602 }
Nicolas Geoffrayd03e8dd2019-04-10 23:13:20 +01001603 }
1604
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001605 MutexLock mu(self, *Locks::jit_lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001606 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1607 return false;
1608 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001609
Vladimir Marko2196c652017-11-30 16:16:07 +00001610 if (UNLIKELY(method->IsNative())) {
1611 JniStubKey key(method);
1612 auto it = jni_stubs_map_.find(key);
1613 bool new_compilation = false;
1614 if (it == jni_stubs_map_.end()) {
1615 // Create a new entry to mark the stub as being compiled.
1616 it = jni_stubs_map_.Put(key, JniStubData{});
1617 new_compilation = true;
1618 }
1619 JniStubData* data = &it->second;
1620 data->AddMethod(method);
1621 if (data->IsCompiled()) {
1622 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1623 const void* entrypoint = method_header->GetEntryPoint();
1624 // Update also entrypoints of other methods held by the JniStubData.
1625 // We could simply update the entrypoint of `method` but if the last JIT GC has
1626 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1627 // as well change them back as this stub shall not be collected anyway and this
1628 // can avoid a few expensive GenericJNI calls.
1629 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1630 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001631 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1632 // `m` might be in the process of being deleted.
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01001633 if (!class_linker->IsQuickResolutionStub(m->GetEntryPointFromQuickCompiledCode())) {
1634 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
1635 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001636 }
1637 if (collection_in_progress_) {
David Srbeckyc45b5892019-04-24 10:32:04 +01001638 if (!IsInZygoteExecSpace(data->GetCode())) {
1639 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1640 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001641 }
1642 }
1643 return new_compilation;
1644 } else {
1645 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1646 if (info == nullptr) {
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001647 // When prejitting, we don't allocate a profiling info.
1648 if (!prejit) {
1649 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1650 // Because the counter is not atomic, there are some rare cases where we may not hit the
1651 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1652 ClearMethodCounter(method, /*was_warm=*/ false);
1653 return false;
1654 }
1655 } else {
1656 if (info->IsMethodBeingCompiled(osr)) {
1657 return false;
1658 }
1659 info->SetIsMethodBeingCompiled(true, osr);
Vladimir Marko2196c652017-11-30 16:16:07 +00001660 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001661 return true;
1662 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001663}
1664
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001665ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001666 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001667 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001668 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001669 if (!info->IncrementInlineUse()) {
1670 // Overflow of inlining uses, just bail.
1671 return nullptr;
1672 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001673 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001674 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001675}
1676
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001677void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001678 MutexLock mu(self, *Locks::jit_lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001679 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001680 DCHECK(info != nullptr);
1681 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001682}
1683
Vladimir Marko2196c652017-11-30 16:16:07 +00001684void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1685 DCHECK_EQ(Thread::Current(), self);
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001686 MutexLock mu(self, *Locks::jit_lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +00001687 if (UNLIKELY(method->IsNative())) {
1688 auto it = jni_stubs_map_.find(JniStubKey(method));
1689 DCHECK(it != jni_stubs_map_.end());
1690 JniStubData* data = &it->second;
1691 DCHECK(ContainsElement(data->GetMethods(), method));
1692 if (UNLIKELY(!data->IsCompiled())) {
1693 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1694 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1695 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1696 } else {
1697 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +01001698 if (info != nullptr) {
1699 DCHECK(info->IsMethodBeingCompiled(osr));
1700 info->SetIsMethodBeingCompiled(false, osr);
1701 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001702 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001703}
1704
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001705void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1706 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001707 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001708 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001709 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001710 if ((profiling_info != nullptr) &&
1711 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07001712 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
1713 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001714 // Prevent future uses of the compiled code.
1715 profiling_info->SetSavedEntryPoint(nullptr);
1716 }
1717
Alex Light2d441b12018-06-08 15:33:21 -07001718 // Clear the method counter if we are running jitted code since we might want to jit this again in
1719 // the future.
1720 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001721 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001722 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001723 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1724 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001725 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001726 } else {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001727 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001728 auto it = osr_code_map_.find(method);
1729 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1730 // Remove the OSR method, to avoid using it again.
1731 osr_code_map_.erase(it);
1732 }
1733 }
1734}
1735
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001736void JitCodeCache::Dump(std::ostream& os) {
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001737 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
1738 os << "Current JIT code cache size: " << PrettySize(private_region_.GetUsedMemoryForCode())
1739 << "\n"
1740 << "Current JIT data cache size: " << PrettySize(private_region_.GetUsedMemoryForData())
1741 << "\n"
David Srbeckyafc60cd2018-12-05 11:59:31 +00001742 << "Current JIT mini-debug-info size: " << PrettySize(GetJitMiniDebugInfoMemUsage()) << "\n"
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001743 << "Current JIT capacity: " << PrettySize(private_region_.GetCurrentCapacity()) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001744 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001745 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1746 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1747 << "Total number of JIT compilations for on stack replacement: "
1748 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001749 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001750 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1751 histogram_code_memory_use_.PrintMemoryUse(os);
1752 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001753}
1754
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001755void JitCodeCache::PostForkChildAction(bool is_system_server, bool is_zygote) {
Nicolas Geoffrayce9ed362018-11-29 03:19:28 +00001756 if (is_zygote) {
1757 // Don't transition if this is for a child zygote.
1758 return;
1759 }
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001760 MutexLock mu(Thread::Current(), *Locks::jit_lock_);
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001761
Nicolas Geoffray2a905b22019-06-06 09:04:07 +01001762 shared_region_ = std::move(private_region_);
1763
1764 // Reset all statistics to be specific to this process.
1765 number_of_compilations_ = 0;
1766 number_of_osr_compilations_ = 0;
1767 number_of_collections_ = 0;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001768
1769 size_t initial_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheInitialCapacity();
1770 size_t max_capacity = Runtime::Current()->GetJITOptions()->GetCodeCacheMaxCapacity();
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001771 std::string error_msg;
Nicolas Geoffray9c54e182019-06-18 10:42:52 +01001772 if (!private_region_.Initialize(initial_capacity,
1773 max_capacity,
1774 /* rwx_memory_allowed= */ !is_system_server,
1775 is_zygote,
1776 &error_msg)) {
1777 LOG(WARNING) << "Could not create private region after zygote fork: " << error_msg;
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001778 }
Nicolas Geoffray7a2c7c22018-11-20 10:03:13 +00001779}
1780
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001781} // namespace jit
1782} // namespace art