blob: a15a9be6f539bace51d51e9add0be71907fb5bc0 [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
Orion Hodson1d3fd082018-09-28 09:38:35 +010021#include "android-base/unique_fd.h"
22
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 Geoffray1dad3f62015-10-23 14:59:54 +010049#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080050#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070051#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070052#include "object_callbacks.h"
David Sehr82d046e2018-04-23 08:14:19 -070053#include "profile/profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070055#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000056#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010057#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080058
Orion Hodson1d3fd082018-09-28 09:38:35 +010059using android::base::unique_fd;
60
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080061namespace art {
62namespace jit {
63
Nicolas Geoffray933330a2016-03-16 14:20:06 +000064static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
65static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
66
Orion Hodson1d3fd082018-09-28 09:38:35 +010067static constexpr int kProtR = PROT_READ;
68static constexpr int kProtRW = PROT_READ | PROT_WRITE;
69static constexpr int kProtRWX = PROT_READ | PROT_WRITE | PROT_EXEC;
70static constexpr int kProtRX = PROT_READ | PROT_EXEC;
71
72namespace {
73
74// Translate an address belonging to one memory map into an address in a second. This is useful
75// when there are two virtual memory ranges for the same physical memory range.
76template <typename T>
77T* TranslateAddress(T* src_ptr, const MemMap& src, const MemMap& dst) {
78 CHECK(src.HasAddress(src_ptr));
79 uint8_t* const raw_src_ptr = reinterpret_cast<uint8_t*>(src_ptr);
80 return reinterpret_cast<T*>(raw_src_ptr - src.Begin() + dst.Begin());
81}
82
83} // namespace
84
Vladimir Marko2196c652017-11-30 16:16:07 +000085class JitCodeCache::JniStubKey {
86 public:
87 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
88 : shorty_(method->GetShorty()),
89 is_static_(method->IsStatic()),
90 is_fast_native_(method->IsFastNative()),
91 is_critical_native_(method->IsCriticalNative()),
92 is_synchronized_(method->IsSynchronized()) {
93 DCHECK(!(is_fast_native_ && is_critical_native_));
94 }
95
96 bool operator<(const JniStubKey& rhs) const {
97 if (is_static_ != rhs.is_static_) {
98 return rhs.is_static_;
99 }
100 if (is_synchronized_ != rhs.is_synchronized_) {
101 return rhs.is_synchronized_;
102 }
103 if (is_fast_native_ != rhs.is_fast_native_) {
104 return rhs.is_fast_native_;
105 }
106 if (is_critical_native_ != rhs.is_critical_native_) {
107 return rhs.is_critical_native_;
108 }
109 return strcmp(shorty_, rhs.shorty_) < 0;
110 }
111
112 // Update the shorty to point to another method's shorty. Call this function when removing
113 // the method that references the old shorty from JniCodeData and not removing the entire
114 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
115 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
116 const char* shorty = method->GetShorty();
117 DCHECK_STREQ(shorty_, shorty);
118 shorty_ = shorty;
119 }
120
121 private:
122 // The shorty points to a DexFile data and may need to change
123 // to point to the same shorty in a different DexFile.
124 mutable const char* shorty_;
125
126 const bool is_static_;
127 const bool is_fast_native_;
128 const bool is_critical_native_;
129 const bool is_synchronized_;
130};
131
132class JitCodeCache::JniStubData {
133 public:
134 JniStubData() : code_(nullptr), methods_() {}
135
136 void SetCode(const void* code) {
137 DCHECK(code != nullptr);
138 code_ = code;
139 }
140
141 const void* GetCode() const {
142 return code_;
143 }
144
145 bool IsCompiled() const {
146 return GetCode() != nullptr;
147 }
148
149 void AddMethod(ArtMethod* method) {
150 if (!ContainsElement(methods_, method)) {
151 methods_.push_back(method);
152 }
153 }
154
155 const std::vector<ArtMethod*>& GetMethods() const {
156 return methods_;
157 }
158
159 void RemoveMethodsIn(const LinearAlloc& alloc) {
160 auto kept_end = std::remove_if(
161 methods_.begin(),
162 methods_.end(),
163 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
164 methods_.erase(kept_end, methods_.end());
165 }
166
167 bool RemoveMethod(ArtMethod* method) {
168 auto it = std::find(methods_.begin(), methods_.end(), method);
169 if (it != methods_.end()) {
170 methods_.erase(it);
171 return true;
172 } else {
173 return false;
174 }
175 }
176
177 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
178 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
179 }
180
181 private:
182 const void* code_;
183 std::vector<ArtMethod*> methods_;
184};
185
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000186JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
187 size_t max_capacity,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700188 bool used_only_for_profile_data,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100189 bool rwx_memory_allowed,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000190 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800191 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100192 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000193
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000194 // We need to have 32 bit offsets from method headers in code cache which point to things
195 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
196 // Ensure we're below 1 GB to be safe.
197 if (max_capacity > 1 * GB) {
198 std::ostringstream oss;
199 oss << "Maxium code cache capacity is limited to 1 GB, "
200 << PrettySize(max_capacity) << " is too big";
201 *error_msg = oss.str();
202 return nullptr;
203 }
204
Orion Hodson563ada22018-09-04 11:28:31 +0100205 // Register for membarrier expedited sync core if JIT will be generating code.
206 if (!used_only_for_profile_data) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100207 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
208 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
209 // flushed and it's used when adding code to the JIT. The memory used by the new code may
210 // have just been released and, in theory, the old code could still be in a pipeline.
211 VLOG(jit) << "Kernel does not support membarrier sync-core";
212 }
Orion Hodson563ada22018-09-04 11:28:31 +0100213 }
214
Orion Hodson1d3fd082018-09-28 09:38:35 +0100215 // File descriptor enabling dual-view mapping of code section.
216 unique_fd mem_fd;
217
218 // Bionic supports memfd_create, but the call may fail on older kernels.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700219 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
Orion Hodson1d3fd082018-09-28 09:38:35 +0100220 if (mem_fd.get() < 0) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100221 std::ostringstream oss;
222 oss << "Failed to initialize dual view JIT. memfd_create() error: " << strerror(errno);
223 if (!rwx_memory_allowed) {
224 // Without using RWX page permissions, the JIT can not fallback to single mapping as it
225 // requires tranitioning the code pages to RWX for updates.
226 *error_msg = oss.str();
227 return nullptr;
228 }
229 VLOG(jit) << oss.str();
Orion Hodson1d3fd082018-09-28 09:38:35 +0100230 }
231
232 if (mem_fd.get() >= 0 && ftruncate(mem_fd, max_capacity) != 0) {
233 std::ostringstream oss;
234 oss << "Failed to initialize memory file: " << strerror(errno);
235 *error_msg = oss.str();
236 return nullptr;
237 }
238
239 // Data cache will be half of the initial allocation.
240 // Code cache will be the other half of the initial allocation.
241 // TODO: Make this variable?
242
243 // Align both capacities to page size, as that's the unit mspaces use.
244 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
245 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
246 const size_t data_capacity = max_capacity / 2;
247 const size_t exec_capacity = used_only_for_profile_data ? 0 : max_capacity - data_capacity;
248 DCHECK_LE(data_capacity + exec_capacity, max_capacity);
Calin Juravle016fcbe22018-05-03 19:47:35 -0700249
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800250 std::string error_str;
251 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000252 // Map in low 4gb to simplify accessing root tables for x86_64.
253 // We could do PC-relative addressing to avoid this problem, but that
254 // would require reserving code and data area before submitting, which
255 // means more windows for the code memory to be RWX.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100256 int base_flags;
257 MemMap data_pages;
258 if (mem_fd.get() >= 0) {
259 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
260 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
261 // enable dual mapping - we'll create a second mapping using the descriptor below. The
262 // mappings will look like:
263 //
264 // VA PA
265 //
266 // +---------------+
267 // | non exec code |\
268 // +---------------+ \
269 // : :\ \
270 // +---------------+.\.+---------------+
271 // | exec code | \| code |
272 // +---------------+...+---------------+
273 // | data | | data |
274 // +---------------+...+---------------+
275 //
276 // In this configuration code updates are written to the non-executable view of the code
277 // cache, and the executable view of the code cache has fixed RX memory protections.
278 //
279 // This memory needs to be mapped shared as the code portions will have two mappings.
280 base_flags = MAP_SHARED;
281 data_pages = MemMap::MapFile(
282 data_capacity + exec_capacity,
283 kProtRW,
284 base_flags,
285 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700286 /* start= */ 0,
287 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100288 "data-code-cache",
289 &error_str);
290 } else {
291 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
292 // for data and JIT code pages. The mappings will look like:
293 //
294 // VA PA
295 //
296 // +---------------+...+---------------+
297 // | exec code | | code |
298 // +---------------+...+---------------+
299 // | data | | data |
300 // +---------------+...+---------------+
301 //
302 // In this configuration code updates are written to the executable view of the code cache,
303 // and the executable view of the code cache transitions RX to RWX for the update and then
304 // back to RX after the update.
305 base_flags = MAP_PRIVATE | MAP_ANON;
306 data_pages = MemMap::MapAnonymous(
307 "data-code-cache",
Orion Hodson1d3fd082018-09-28 09:38:35 +0100308 data_capacity + exec_capacity,
309 kProtRW,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700310 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100311 &error_str);
312 }
313
314 if (!data_pages.IsValid()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800315 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700316 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800317 *error_msg = oss.str();
318 return nullptr;
319 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100320
Orion Hodson1d3fd082018-09-28 09:38:35 +0100321 MemMap exec_pages;
322 MemMap non_exec_pages;
323 if (exec_capacity > 0) {
324 uint8_t* const divider = data_pages.Begin() + data_capacity;
325 // Set initial permission for executable view to catch any SELinux permission problems early
326 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
327 // executable as there is no code in the cache yet.
328 exec_pages = data_pages.RemapAtEnd(divider,
329 "jit-code-cache",
330 kProtRX,
331 base_flags | MAP_FIXED,
332 mem_fd.get(),
333 (mem_fd.get() >= 0) ? data_capacity : 0,
334 &error_str);
335 if (!exec_pages.IsValid()) {
336 std::ostringstream oss;
337 oss << "Failed to create read execute code cache: " << error_str << " size=" << max_capacity;
338 *error_msg = oss.str();
339 return nullptr;
340 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100341
Orion Hodson1d3fd082018-09-28 09:38:35 +0100342 if (mem_fd.get() >= 0) {
343 // For dual view, create the secondary view of code memory used for updating code. This view
344 // is never executable.
345 non_exec_pages = MemMap::MapFile(exec_capacity,
346 kProtR,
347 base_flags,
348 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700349 /* start= */ data_capacity,
350 /* low_4GB= */ false,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100351 "jit-code-cache-rw",
352 &error_str);
353 if (!non_exec_pages.IsValid()) {
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100354 static const char* kFailedNxView = "Failed to map non-executable view of JIT code cache";
355 if (rwx_memory_allowed) {
356 // Log and continue as single view JIT (requires RWX memory).
357 VLOG(jit) << kFailedNxView;
358 } else {
359 *error_msg = kFailedNxView;
360 return nullptr;
361 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100362 }
363 }
364 } else {
365 // Profiling only. No memory for code required.
366 DCHECK(used_only_for_profile_data);
David Sehrd1dbb742017-07-17 11:20:38 -0700367 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100368
369 const size_t initial_data_capacity = initial_capacity / 2;
370 const size_t initial_exec_capacity =
371 (exec_capacity == 0) ? 0 : (initial_capacity - initial_data_capacity);
372
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100373 return new JitCodeCache(
Orion Hodson1d3fd082018-09-28 09:38:35 +0100374 std::move(data_pages),
375 std::move(exec_pages),
376 std::move(non_exec_pages),
377 initial_data_capacity,
378 initial_exec_capacity,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100379 max_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800380}
381
Orion Hodson1d3fd082018-09-28 09:38:35 +0100382JitCodeCache::JitCodeCache(MemMap&& data_pages,
383 MemMap&& exec_pages,
384 MemMap&& non_exec_pages,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000385 size_t initial_data_capacity,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100386 size_t initial_exec_capacity,
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100387 size_t max_capacity)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100388 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000389 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100390 collection_in_progress_(false),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100391 data_pages_(std::move(data_pages)),
392 exec_pages_(std::move(exec_pages)),
393 non_exec_pages_(std::move(non_exec_pages)),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000394 max_capacity_(max_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100395 current_capacity_(initial_exec_capacity + initial_data_capacity),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000396 data_end_(initial_data_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100397 exec_end_(initial_exec_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000398 last_collection_increased_code_cache_(false),
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100399 garbage_collect_code_(true),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000400 used_memory_for_data_(0),
401 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000402 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000403 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000404 number_of_collections_(0),
405 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
406 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000407 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
408 is_weak_access_enabled_(true),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100409 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100410
Orion Hodson1d3fd082018-09-28 09:38:35 +0100411 DCHECK_GE(max_capacity, initial_exec_capacity + initial_data_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100412
Orion Hodson1d3fd082018-09-28 09:38:35 +0100413 // Initialize the data heap
414 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
415 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
416
417 // Initialize the code heap
418 MemMap* code_heap = nullptr;
419 if (non_exec_pages_.IsValid()) {
420 code_heap = &non_exec_pages_;
421 } else if (exec_pages_.IsValid()) {
422 code_heap = &exec_pages_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100423 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100424 if (code_heap != nullptr) {
425 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
426 // heap, will take and initialize pages in create_mspace_with_base().
427 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
428 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
429 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
430 SetFootprintLimit(current_capacity_);
431 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
432 // perform the update and there are no other times write access is required.
433 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
434 } else {
435 exec_mspace_ = nullptr;
436 SetFootprintLimit(current_capacity_);
437 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100438
Orion Hodsonad28f5e2018-10-17 09:08:17 +0100439 // With 'perf', we want a 1-1 mapping between an address and a method.
440 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
441 // so we will just disable jit-gc if we are doing that.
442 garbage_collect_code_ = !Jit::ShouldGenerateDebugInfo() &&
443 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
444
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000445 VLOG(jit) << "Created jit code cache: initial data size="
446 << PrettySize(initial_data_capacity)
447 << ", initial code size="
Orion Hodson1d3fd082018-09-28 09:38:35 +0100448 << PrettySize(initial_exec_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800449}
450
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000451JitCodeCache::~JitCodeCache() {}
452
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100453bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100454 return exec_pages_.Begin() <= ptr && ptr < exec_pages_.End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800455}
456
Alex Light2d441b12018-06-08 15:33:21 -0700457bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
458 ScopedObjectAccess soa(art::Thread::Current());
459 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
460 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
461 return true;
462 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
463 return FindCompiledCodeForInstrumentation(method) != nullptr;
464 }
465 return false;
466}
467
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000468bool JitCodeCache::ContainsMethod(ArtMethod* method) {
469 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000470 if (UNLIKELY(method->IsNative())) {
471 auto it = jni_stubs_map_.find(JniStubKey(method));
472 if (it != jni_stubs_map_.end() &&
473 it->second.IsCompiled() &&
474 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000475 return true;
476 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000477 } else {
478 for (const auto& it : method_code_map_) {
479 if (it.second == method) {
480 return true;
481 }
482 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000483 }
484 return false;
485}
486
Vladimir Marko2196c652017-11-30 16:16:07 +0000487const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
488 DCHECK(method->IsNative());
489 MutexLock mu(Thread::Current(), lock_);
490 auto it = jni_stubs_map_.find(JniStubKey(method));
491 if (it != jni_stubs_map_.end()) {
492 JniStubData& data = it->second;
493 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
494 return data.GetCode();
495 }
496 }
497 return nullptr;
498}
499
Alex Light2d441b12018-06-08 15:33:21 -0700500const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700501 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
502 // find the instrumentation entrypoint.
503 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700504 return nullptr;
505 }
506 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
507 if (info == nullptr) {
508 return nullptr;
509 }
510 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
511 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
512 // nullptr.
513 return info->GetSavedEntryPoint();
514}
515
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800516class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100517 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700518 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100519 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700520 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800521 ScopedTrace trace("mprotect all");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100522 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
523 if (updatable_pages != nullptr) {
524 int prot = code_cache_->HasDualCodeMapping() ? kProtRW : kProtRWX;
525 CheckedCall(mprotect, "Cache +W", updatable_pages->Begin(), updatable_pages->Size(), prot);
526 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800527 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700528
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100529 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800530 ScopedTrace trace("mprotect code");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100531 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
532 if (updatable_pages != nullptr) {
533 int prot = code_cache_->HasDualCodeMapping() ? kProtR : kProtRX;
534 CheckedCall(mprotect, "Cache -W", updatable_pages->Begin(), updatable_pages->Size(), prot);
535 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100536 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700537
David Sehrd1dbb742017-07-17 11:20:38 -0700538 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700539 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100540
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100541 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
542};
543
544uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100545 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000546 uint8_t* stack_map,
547 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100548 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000549 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100550 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000551 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100552 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700553 bool has_should_deoptimize_flag,
554 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100555 uint8_t* result = CommitCodeInternal(self,
556 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000557 stack_map,
558 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100559 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000560 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100561 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000562 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700563 roots,
564 has_should_deoptimize_flag,
565 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100566 if (result == nullptr) {
567 // Retry.
568 GarbageCollectCache(self);
569 result = CommitCodeInternal(self,
570 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000571 stack_map,
572 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100573 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000574 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100575 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000576 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700577 roots,
578 has_should_deoptimize_flag,
579 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100580 }
581 return result;
582}
583
584bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
585 bool in_collection = false;
586 while (collection_in_progress_) {
587 in_collection = true;
588 lock_cond_.Wait(self);
589 }
590 return in_collection;
591}
592
593static uintptr_t FromCodeToAllocation(const void* code) {
594 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
595 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
596}
597
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000598static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
599 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
600}
601
602static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
603 // The length of the table is stored just before the stack map (and therefore at the end of
604 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
605 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
606}
607
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800608static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
609 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
610 // pointer.
611 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
612}
613
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000614static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
615 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
616}
617
Vladimir Markoac3ac682018-09-20 11:01:43 +0100618static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700619 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
620 if (!kIsDebugBuild) {
621 return;
622 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700623 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100624 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700625 // Ensure the string is strongly interned. b/32995596
626 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100627 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700628 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
629 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
630 }
631 }
632}
633
634void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100635 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000636 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100637 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000638 // Put all roots in `roots_data`.
639 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100640 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000641 gc_roots[i] = GcRoot<mirror::Object>(object);
642 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000643}
644
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100645static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000646 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
647 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
648 uint32_t roots = GetNumberOfRoots(data);
649 if (number_of_roots != nullptr) {
650 *number_of_roots = roots;
651 }
652 return data - ComputeRootTableSize(roots);
653}
654
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100655// Use a sentinel for marking entries in the JIT table that have been cleared.
656// This helps diagnosing in case the compiled code tries to wrongly access such
657// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700658static mirror::Class* const weak_sentinel =
659 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100660
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000661// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100662static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
663 IsMarkedVisitor* visitor,
664 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000665 REQUIRES_SHARED(Locks::mutator_lock_) {
666 // This does not need a read barrier because this is called by GC.
667 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100668 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700669 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000670 // Look at the classloader of the class to know if it has been unloaded.
671 // This does not need a read barrier because this is called by GC.
672 mirror::Object* class_loader =
673 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
674 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
675 // The class loader is live, update the entry if the class has moved.
676 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
677 // Note that new_object can be null for CMS and newly allocated objects.
678 if (new_cls != nullptr && new_cls != cls) {
679 *root_ptr = GcRoot<mirror::Class>(new_cls);
680 }
681 } else {
682 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100683 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000684 }
685 }
686}
687
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000688void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
689 MutexLock mu(Thread::Current(), lock_);
690 for (const auto& entry : method_code_map_) {
691 uint32_t number_of_roots = 0;
692 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
693 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
694 for (uint32_t i = 0; i < number_of_roots; ++i) {
695 // This does not need a read barrier because this is called by GC.
696 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100697 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000698 // entry got deleted in a previous sweep.
699 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
700 mirror::Object* new_object = visitor->IsMarked(object);
701 // We know the string is marked because it's a strongly-interned string that
702 // is always alive. The IsMarked implementation of the CMS collector returns
703 // null for newly allocated objects, but we know those haven't moved. Therefore,
704 // only update the entry if we get a different non-null string.
705 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
706 // out of the weak access/creation pause. b/32167580
707 if (new_object != nullptr && new_object != object) {
708 DCHECK(new_object->IsString());
709 roots[i] = GcRoot<mirror::Object>(new_object);
710 }
711 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100712 ProcessWeakClass(
713 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000714 }
715 }
716 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000717 // Walk over inline caches to clear entries containing unloaded classes.
718 for (ProfilingInfo* info : profiling_infos_) {
719 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
720 InlineCache* cache = &info->cache_[i];
721 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100722 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000723 }
724 }
725 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000726}
727
Orion Hodson607624f2018-05-11 10:10:46 +0100728void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100729 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000730 // Notify native debugger that we are about to remove the code.
731 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000732 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000733 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000734 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
735 FreeData(GetRootTable(code_ptr));
736 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100737
738 uint8_t* code_allocation = reinterpret_cast<uint8_t*>(allocation);
739 if (HasDualCodeMapping()) {
740 code_allocation = TranslateAddress(code_allocation, exec_pages_, non_exec_pages_);
741 }
742
743 FreeCode(code_allocation);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100744}
745
Mingyao Yang063fc772016-08-02 11:02:54 -0700746void JitCodeCache::FreeAllMethodHeaders(
747 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700748 // We need to remove entries in method_headers from CHA dependencies
749 // first since once we do FreeCode() below, the memory can be reused
750 // so it's possible for the same method_header to start representing
751 // different compile code.
752 MutexLock mu(Thread::Current(), lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000753 {
754 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
755 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
756 ->RemoveDependentsWithMethodHeaders(method_headers);
757 }
758
Calin Juravle016fcbe22018-05-03 19:47:35 -0700759 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700760 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100761 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700762 }
763}
764
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100765void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800766 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700767 // We use a set to first collect all method_headers whose code need to be
768 // removed. We need to free the underlying code after we remove CHA dependencies
769 // for entries in this set. And it's more efficient to iterate through
770 // the CHA dependency map just once with an unordered_set.
771 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000772 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700773 MutexLock mu(self, lock_);
774 // We do not check if a code cache GC is in progress, as this method comes
775 // with the classlinker_classes_lock_ held, and suspending ourselves could
776 // lead to a deadlock.
777 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700778 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000779 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
780 it->second.RemoveMethodsIn(alloc);
781 if (it->second.GetMethods().empty()) {
782 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
783 it = jni_stubs_map_.erase(it);
784 } else {
785 it->first.UpdateShorty(it->second.GetMethods().front());
786 ++it;
787 }
788 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700789 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
790 if (alloc.ContainsUnsafe(it->second)) {
791 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
792 it = method_code_map_.erase(it);
793 } else {
794 ++it;
795 }
796 }
797 }
798 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
799 if (alloc.ContainsUnsafe(it->first)) {
800 // Note that the code has already been pushed to method_headers in the loop
801 // above and is going to be removed in FreeCode() below.
802 it = osr_code_map_.erase(it);
803 } else {
804 ++it;
805 }
806 }
807 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
808 ProfilingInfo* info = *it;
809 if (alloc.ContainsUnsafe(info->GetMethod())) {
810 info->GetMethod()->SetProfilingInfo(nullptr);
811 FreeData(reinterpret_cast<uint8_t*>(info));
812 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000813 } else {
814 ++it;
815 }
816 }
817 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700818 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100819}
820
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000821bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
822 return kUseReadBarrier
823 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000824 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000825}
826
827void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
828 if (IsWeakAccessEnabled(self)) {
829 return;
830 }
831 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000832 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000833 while (!IsWeakAccessEnabled(self)) {
834 inline_cache_cond_.Wait(self);
835 }
836}
837
838void JitCodeCache::BroadcastForInlineCacheAccess() {
839 Thread* self = Thread::Current();
840 MutexLock mu(self, lock_);
841 inline_cache_cond_.Broadcast(self);
842}
843
844void JitCodeCache::AllowInlineCacheAccess() {
845 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000846 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000847 BroadcastForInlineCacheAccess();
848}
849
850void JitCodeCache::DisallowInlineCacheAccess() {
851 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000852 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000853}
854
855void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
856 Handle<mirror::ObjectArray<mirror::Class>> array) {
857 WaitUntilInlineCacheAccessible(Thread::Current());
858 // Note that we don't need to lock `lock_` here, the compiler calling
859 // this method has already ensured the inline cache will not be deleted.
860 for (size_t in_cache = 0, in_array = 0;
861 in_cache < InlineCache::kIndividualCacheSize;
862 ++in_cache) {
863 mirror::Class* object = ic.classes_[in_cache].Read();
864 if (object != nullptr) {
865 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000866 }
867 }
868}
869
Mathieu Chartierf044c222017-05-31 15:27:54 -0700870static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
871 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100872 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700873 }
874 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
875 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100876 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
877 // the warmup threshold is 1.
878 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
879 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700880}
881
Alex Light33b7b5d2018-08-07 19:13:51 +0000882void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
883 while (collection_in_progress_) {
884 lock_.Unlock(self);
885 {
886 ScopedThreadSuspension sts(self, kSuspended);
887 MutexLock mu(self, lock_);
888 WaitForPotentialCollectionToComplete(self);
889 }
890 lock_.Lock(self);
891 }
892}
893
Orion Hodson1d3fd082018-09-28 09:38:35 +0100894const MemMap* JitCodeCache::GetUpdatableCodeMapping() const {
895 if (HasDualCodeMapping()) {
896 return &non_exec_pages_;
897 } else if (HasCodeMapping()) {
898 return &exec_pages_;
899 } else {
900 return nullptr;
901 }
902}
903
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100904uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
905 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000906 uint8_t* stack_map,
907 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100908 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000909 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100910 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000911 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100912 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700913 bool has_should_deoptimize_flag,
914 const ArenaSet<ArtMethod*>&
915 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000916 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000917
918 if (!method->IsNative()) {
919 // We need to do this before grabbing the lock_ because it needs to be able to see the string
920 // InternTable. Native methods do not have roots.
921 DCheckRootsAreValid(roots);
922 }
923
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100924 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100925 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100926
Alex Light33b7b5d2018-08-07 19:13:51 +0000927 MutexLock mu(self, lock_);
928 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
929 // finish.
930 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100931 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000932 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100933
934 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
935 // Ensure the header ends up at expected instruction alignment.
936 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
937 size_t total_size = header_size + code_size;
938
939 // AllocateCode allocates memory in non-executable region for alignment header and code. The
940 // header size may include alignment padding.
941 uint8_t* nox_memory = AllocateCode(total_size);
942 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +0000943 return nullptr;
944 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000945
Orion Hodson1d3fd082018-09-28 09:38:35 +0100946 // code_ptr points to non-executable code.
947 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +0000948 std::copy(code, code + code_size, code_ptr);
949 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100950
951 // From here code_ptr points to executable code.
952 if (HasDualCodeMapping()) {
953 code_ptr = TranslateAddress(code_ptr, non_exec_pages_, exec_pages_);
954 }
955
Alex Light33b7b5d2018-08-07 19:13:51 +0000956 new (method_header) OatQuickMethodHeader(
957 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
958 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100959
960 DCHECK(!Runtime::Current()->IsAotCompiler());
961 if (has_should_deoptimize_flag) {
962 method_header->SetHasShouldDeoptimizeFlag();
963 }
964
965 // Update method_header pointer to executable code region.
966 if (HasDualCodeMapping()) {
967 method_header = TranslateAddress(method_header, non_exec_pages_, exec_pages_);
968 }
969
970 // Both instruction and data caches need flushing to the point of unification where both share
971 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
972 // newly added code are written out to the point of unification. Flushing the instruction
973 // cache ensures the newly written code will be fetched from the point of unification before
974 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
975 // prevent stale code from residing in the instruction cache.
976 //
977 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
978 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
979 // operation. This is a kernel bug that we need to work around until affected devices
980 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +0000981 //
982 // For reference, this behavior is caused by this commit:
983 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +0100984 //
985 if (HasDualCodeMapping()) {
986 // Flush the data cache lines associated with the non-executable copy of the code just added.
987 FlushDataCache(nox_memory, nox_memory + total_size);
988 }
989 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
990 // flushed is for the executable mapping of the code just added.
Orion Hodson38d29fd2018-09-07 12:58:37 +0100991 FlushInstructionCache(code_ptr, code_ptr + code_size);
Orion Hodsonf2331362018-07-11 15:14:10 +0100992
993 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
994 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
995 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
996 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
997 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
998 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +0100999 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
1000 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
1001 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +01001002 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +01001003
Nicolas Geoffray0a522232016-01-19 09:34:58 +00001004 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001005 }
Orion Hodson1d3fd082018-09-28 09:38:35 +01001006
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001007 // We need to update the entry point in the runnable state for the instrumentation.
1008 {
Alex Light33b7b5d2018-08-07 19:13:51 +00001009 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
1010 // compiled code is considered invalidated by some class linking, but below we still make the
1011 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
1012 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -07001013 MutexLock cha_mu(self, *Locks::cha_lock_);
1014 bool single_impl_still_valid = true;
1015 for (ArtMethod* single_impl : cha_single_implementation_list) {
1016 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001017 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
1018 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -07001019 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001020 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -07001021 break;
1022 }
1023 }
1024
1025 // Discard the code if any single-implementation assumptions are now invalid.
1026 if (!single_impl_still_valid) {
1027 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
1028 return nullptr;
1029 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00001030 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -08001031 << "Should not be using cha on debuggable apps/runs!";
1032
Mingyao Yang063fc772016-08-02 11:02:54 -07001033 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07001034 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -07001035 single_impl, method, method_header);
1036 }
1037
Vladimir Marko2196c652017-11-30 16:16:07 +00001038 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001039 auto it = jni_stubs_map_.find(JniStubKey(method));
1040 DCHECK(it != jni_stubs_map_.end())
1041 << "Entry inserted in NotifyCompilationOf() should be alive.";
1042 JniStubData* data = &it->second;
1043 DCHECK(ContainsElement(data->GetMethods(), method))
1044 << "Entry inserted in NotifyCompilationOf() should contain this method.";
1045 data->SetCode(code_ptr);
1046 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
1047 for (ArtMethod* m : data->GetMethods()) {
1048 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
1049 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001050 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001051 // Fill the root table before updating the entry point.
1052 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
1053 DCHECK_LE(roots_data, stack_map);
1054 FillRootTable(roots_data, roots);
1055 {
1056 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001057 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +00001058 }
1059 method_code_map_.Put(code_ptr, method);
1060 if (osr) {
1061 number_of_osr_compilations_++;
1062 osr_code_map_.Put(method, code_ptr);
1063 } else {
1064 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1065 method, method_header->GetEntryPoint());
1066 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001067 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001068 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001069 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001070 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001071 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1072 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1073 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001074 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1075 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001076 histogram_code_memory_use_.AddValue(code_size);
1077 if (code_size > kCodeSizeLogThreshold) {
1078 LOG(INFO) << "JIT allocated "
1079 << PrettySize(code_size)
1080 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001081 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001082 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001083 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001084
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001085 return reinterpret_cast<uint8_t*>(method_header);
1086}
1087
1088size_t JitCodeCache::CodeCacheSize() {
1089 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001090 return CodeCacheSizeLocked();
1091}
1092
Orion Hodsoneced6922017-06-01 10:54:28 +01001093bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001094 // This function is used only for testing and only with non-native methods.
1095 CHECK(!method->IsNative());
1096
Orion Hodsoneced6922017-06-01 10:54:28 +01001097 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +01001098
Vladimir Marko2196c652017-11-30 16:16:07 +00001099 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
1100 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +01001101
1102 if (!in_cache) {
1103 return false;
1104 }
1105
Orion Hodsoneced6922017-06-01 10:54:28 +01001106 method->ClearCounter();
1107 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1108 method, GetQuickToInterpreterBridge());
1109 VLOG(jit)
1110 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1111 << ArtMethod::PrettyMethod(method) << "@" << method
1112 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1113 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1114 return true;
1115}
1116
Vladimir Marko2196c652017-11-30 16:16:07 +00001117bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
1118 if (LIKELY(!method->IsNative())) {
1119 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1120 if (info != nullptr) {
1121 RemoveElement(profiling_infos_, info);
1122 }
1123 method->SetProfilingInfo(nullptr);
1124 }
1125
1126 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -07001127 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +00001128 if (UNLIKELY(method->IsNative())) {
1129 auto it = jni_stubs_map_.find(JniStubKey(method));
1130 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
1131 in_cache = true;
1132 if (it->second.GetMethods().empty()) {
1133 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001134 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +00001135 }
1136 jni_stubs_map_.erase(it);
1137 } else {
1138 it->first.UpdateShorty(it->second.GetMethods().front());
1139 }
1140 }
1141 } else {
1142 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1143 if (it->second == method) {
1144 in_cache = true;
1145 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001146 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +00001147 }
1148 it = method_code_map_.erase(it);
1149 } else {
1150 ++it;
1151 }
1152 }
1153
1154 auto osr_it = osr_code_map_.find(method);
1155 if (osr_it != osr_code_map_.end()) {
1156 osr_code_map_.erase(osr_it);
1157 }
1158 }
1159
1160 return in_cache;
1161}
1162
Alex Lightdba61482016-12-21 08:20:29 -08001163// This notifies the code cache that the given method has been redefined and that it should remove
1164// any cached information it has on the method. All threads must be suspended before calling this
1165// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1166void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1167 MutexLock mu(Thread::Current(), lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001168 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -08001169}
1170
1171// This invalidates old_method. Once this function returns one can no longer use old_method to
1172// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1173// class redefinition.
1174// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1175// shouldn't be used since it is no longer logically in the jit code cache.
1176// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1177void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001178 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +00001179 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001180 // Update methods in jni_stubs_map_.
1181 for (auto& entry : jni_stubs_map_) {
1182 JniStubData& data = entry.second;
1183 data.MoveObsoleteMethod(old_method, new_method);
1184 }
Alex Lighteee0bd42017-02-14 15:31:45 +00001185 return;
1186 }
Alex Lightdba61482016-12-21 08:20:29 -08001187 // Update ProfilingInfo to the new one and remove it from the old_method.
1188 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1189 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1190 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1191 old_method->SetProfilingInfo(nullptr);
1192 // Since the JIT should be paused and all threads suspended by the time this is called these
1193 // checks should always pass.
1194 DCHECK(!info->IsInUseByCompiler());
1195 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001196 // Get rid of the old saved entrypoint if it is there.
1197 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001198 info->method_ = new_method;
1199 }
1200 // Update method_code_map_ to point to the new method.
1201 for (auto& it : method_code_map_) {
1202 if (it.second == old_method) {
1203 it.second = new_method;
1204 }
1205 }
1206 // Update osr_code_map_ to point to the new method.
1207 auto code_map = osr_code_map_.find(old_method);
1208 if (code_map != osr_code_map_.end()) {
1209 osr_code_map_.Put(new_method, code_map->second);
1210 osr_code_map_.erase(old_method);
1211 }
1212}
1213
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001214size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001215 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001216}
1217
1218size_t JitCodeCache::DataCacheSize() {
1219 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001220 return DataCacheSizeLocked();
1221}
1222
1223size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001224 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001225}
1226
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001227void JitCodeCache::ClearData(Thread* self,
1228 uint8_t* stack_map_data,
1229 uint8_t* roots_data) {
1230 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001231 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001232 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001233}
1234
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001235size_t JitCodeCache::ReserveData(Thread* self,
1236 size_t stack_map_size,
1237 size_t number_of_roots,
1238 ArtMethod* method,
1239 uint8_t** stack_map_data,
1240 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001241 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001242 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001243 uint8_t* result = nullptr;
1244
1245 {
1246 ScopedThreadSuspension sts(self, kSuspended);
1247 MutexLock mu(self, lock_);
1248 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001249 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001250 }
1251
1252 if (result == nullptr) {
1253 // Retry.
1254 GarbageCollectCache(self);
1255 ScopedThreadSuspension sts(self, kSuspended);
1256 MutexLock mu(self, lock_);
1257 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001258 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001259 }
1260
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001261 MutexLock mu(self, lock_);
1262 histogram_stack_map_memory_use_.AddValue(size);
1263 if (size > kStackMapSizeLogThreshold) {
1264 LOG(INFO) << "JIT allocated "
1265 << PrettySize(size)
1266 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001267 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001268 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001269 if (result != nullptr) {
1270 *roots_data = result;
1271 *stack_map_data = result + table_size;
1272 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001273 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001274 } else {
1275 *roots_data = nullptr;
1276 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001277 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001278 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001279}
1280
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001281class MarkCodeVisitor final : public StackVisitor {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001282 public:
1283 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1284 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1285 code_cache_(code_cache_in),
1286 bitmap_(code_cache_->GetLiveBitmap()) {}
1287
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001288 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001289 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1290 if (method_header == nullptr) {
1291 return true;
1292 }
1293 const void* code = method_header->GetCode();
1294 if (code_cache_->ContainsPc(code)) {
1295 // Use the atomic set version, as multiple threads are executing this code.
1296 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1297 }
1298 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001299 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001300
1301 private:
1302 JitCodeCache* const code_cache_;
1303 CodeCacheBitmap* const bitmap_;
1304};
1305
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001306class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001307 public:
1308 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1309 : code_cache_(code_cache), barrier_(barrier) {}
1310
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001311 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001312 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001313 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1314 MarkCodeVisitor visitor(thread, code_cache_);
1315 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001316 if (kIsDebugBuild) {
1317 // The stack walking code queries the side instrumentation stack if it
1318 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1319 // must have been seen. We sanity check this below.
1320 for (const instrumentation::InstrumentationStackFrame& frame
1321 : *thread->GetInstrumentationStack()) {
1322 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1323 // its stack frame, it is not the method owning return_pc_. We just pass null to
1324 // LookupMethodHeader: the method is only checked against in debug builds.
1325 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001326 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001327 if (method_header != nullptr) {
1328 const void* code = method_header->GetCode();
1329 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1330 }
1331 }
1332 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001333 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001334 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001335
1336 private:
1337 JitCodeCache* const code_cache_;
1338 Barrier* const barrier_;
1339};
1340
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001341void JitCodeCache::NotifyCollectionDone(Thread* self) {
1342 collection_in_progress_ = false;
1343 lock_cond_.Broadcast(self);
1344}
1345
1346void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1347 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001348 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001349 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1350 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001351 if (HasCodeMapping()) {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001352 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001353 mspace_set_footprint_limit(exec_mspace_, per_space_footprint);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001354 }
1355}
1356
1357bool JitCodeCache::IncreaseCodeCacheCapacity() {
1358 if (current_capacity_ == max_capacity_) {
1359 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001360 }
1361
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001362 // Double the capacity if we're below 1MB, or increase it by 1MB if
1363 // we're above.
1364 if (current_capacity_ < 1 * MB) {
1365 current_capacity_ *= 2;
1366 } else {
1367 current_capacity_ += 1 * MB;
1368 }
1369 if (current_capacity_ > max_capacity_) {
1370 current_capacity_ = max_capacity_;
1371 }
1372
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001373 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001374
1375 SetFootprintLimit(current_capacity_);
1376
1377 return true;
1378}
1379
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001380void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1381 Barrier barrier(0);
1382 size_t threads_running_checkpoint = 0;
1383 MarkCodeClosure closure(this, &barrier);
1384 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1385 // Now that we have run our checkpoint, move to a suspended state and wait
1386 // for other threads to run the checkpoint.
1387 ScopedThreadSuspension sts(self, kSuspended);
1388 if (threads_running_checkpoint != 0) {
1389 barrier.Increment(self, threads_running_checkpoint);
1390 }
1391}
1392
Nicolas Geoffray35122442016-03-02 12:05:30 +00001393bool JitCodeCache::ShouldDoFullCollection() {
1394 if (current_capacity_ == max_capacity_) {
1395 // Always do a full collection when the code cache is full.
1396 return true;
1397 } else if (current_capacity_ < kReservedCapacity) {
1398 // Always do partial collection when the code cache size is below the reserved
1399 // capacity.
1400 return false;
1401 } else if (last_collection_increased_code_cache_) {
1402 // This time do a full collection.
1403 return true;
1404 } else {
1405 // This time do a partial collection.
1406 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001407 }
1408}
1409
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001410void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001411 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001412 if (!garbage_collect_code_) {
1413 MutexLock mu(self, lock_);
1414 IncreaseCodeCacheCapacity();
1415 return;
1416 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001417
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001418 // Wait for an existing collection, or let everyone know we are starting one.
1419 {
1420 ScopedThreadSuspension sts(self, kSuspended);
1421 MutexLock mu(self, lock_);
1422 if (WaitForPotentialCollectionToComplete(self)) {
1423 return;
1424 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001425 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001426 live_bitmap_.reset(CodeCacheBitmap::Create(
1427 "code-cache-bitmap",
Orion Hodson1d3fd082018-09-28 09:38:35 +01001428 reinterpret_cast<uintptr_t>(exec_pages_.Begin()),
1429 reinterpret_cast<uintptr_t>(exec_pages_.Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001430 collection_in_progress_ = true;
1431 }
1432 }
1433
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001434 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001435 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001436 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001437
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001438 bool do_full_collection = false;
1439 {
1440 MutexLock mu(self, lock_);
1441 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001442 }
1443
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001444 VLOG(jit) << "Do "
1445 << (do_full_collection ? "full" : "partial")
1446 << " code cache collection, code="
1447 << PrettySize(CodeCacheSize())
1448 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001449
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001450 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001451
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001452 VLOG(jit) << "After code cache collection, code="
1453 << PrettySize(CodeCacheSize())
1454 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001455
1456 {
1457 MutexLock mu(self, lock_);
1458
1459 // Increase the code cache only when we do partial collections.
1460 // TODO: base this strategy on how full the code cache is?
1461 if (do_full_collection) {
1462 last_collection_increased_code_cache_ = false;
1463 } else {
1464 last_collection_increased_code_cache_ = true;
1465 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001466 }
1467
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001468 bool next_collection_will_be_full = ShouldDoFullCollection();
1469
1470 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001471 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001472 // Save the entry point of methods we have compiled, and update the entry
1473 // point of those methods to the interpreter. If the method is invoked, the
1474 // interpreter will update its entry point to the compiled code and call it.
1475 for (ProfilingInfo* info : profiling_infos_) {
1476 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1477 if (ContainsPc(entry_point)) {
1478 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001479 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001480 // class of the method. We may be concurrently running a GC which makes accessing
1481 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1482 // checked that the current entry point is JIT compiled code.
1483 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001484 }
1485 }
1486
1487 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001488
1489 // Change entry points of native methods back to the GenericJNI entrypoint.
1490 for (const auto& entry : jni_stubs_map_) {
1491 const JniStubData& data = entry.second;
1492 if (!data.IsCompiled()) {
1493 continue;
1494 }
1495 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1496 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1497 const OatQuickMethodHeader* method_header =
1498 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1499 for (ArtMethod* method : data.GetMethods()) {
1500 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1501 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1502 method->SetCounter(new_counter);
1503 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1504 }
1505 }
1506 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001507 }
1508 live_bitmap_.reset(nullptr);
1509 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001510 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001511 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001512 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001513}
1514
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001515void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001516 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001517 std::unordered_set<OatQuickMethodHeader*> method_headers;
1518 {
1519 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001520 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001521 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001522 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1523 JniStubData* data = &it->second;
1524 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1525 ++it;
1526 } else {
1527 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1528 it = jni_stubs_map_.erase(it);
1529 }
1530 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001531 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1532 const void* code_ptr = it->first;
1533 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1534 if (GetLiveBitmap()->Test(allocation)) {
1535 ++it;
1536 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001537 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1538 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001539 it = method_code_map_.erase(it);
1540 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001541 }
1542 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001543 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001544}
1545
1546void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001547 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001548 {
1549 MutexLock mu(self, lock_);
1550 if (collect_profiling_info) {
1551 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1552 // Also remove the saved entry point from the ProfilingInfo objects.
1553 for (ProfilingInfo* info : profiling_infos_) {
1554 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001555 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001556 info->GetMethod()->SetProfilingInfo(nullptr);
1557 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001558
1559 if (info->GetSavedEntryPoint() != nullptr) {
1560 info->SetSavedEntryPoint(nullptr);
1561 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001562 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001563 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001564 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001565 }
1566 } else if (kIsDebugBuild) {
1567 // Sanity check that the profiling infos do not have a dangling entry point.
1568 for (ProfilingInfo* info : profiling_infos_) {
1569 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001570 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001571 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001572
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001573 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1574 // an entry point is either:
1575 // - an osr compiled code, that will be removed if not in a thread call stack.
1576 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001577 for (const auto& entry : jni_stubs_map_) {
1578 const JniStubData& data = entry.second;
1579 const void* code_ptr = data.GetCode();
1580 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1581 for (ArtMethod* method : data.GetMethods()) {
1582 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1583 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1584 break;
1585 }
1586 }
1587 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001588 for (const auto& it : method_code_map_) {
1589 ArtMethod* method = it.second;
1590 const void* code_ptr = it.first;
1591 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1592 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1593 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1594 }
1595 }
1596
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001597 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001598 // on thread stacks).
1599 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001600 }
1601
1602 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001603 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001604
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001605 // At this point, mutator threads are still running, and entrypoints of methods can
1606 // change. We do know they cannot change to a code cache entry that is not marked,
1607 // therefore we can safely remove those entries.
1608 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001609
Nicolas Geoffray35122442016-03-02 12:05:30 +00001610 if (collect_profiling_info) {
1611 MutexLock mu(self, lock_);
1612 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001613 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001614 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001615 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001616 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1617 // that the compiled code would not get revived. As mutator threads run concurrently,
1618 // they may have revived the compiled code, and now we are in the situation where
1619 // a method has compiled code but no ProfilingInfo.
1620 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1621 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001622 if (ContainsPc(ptr) &&
1623 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001624 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001625 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001626 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001627 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001628 return true;
1629 }
1630 return false;
1631 });
1632 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001633 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001634 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001635}
1636
Nicolas Geoffray35122442016-03-02 12:05:30 +00001637bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001638 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001639 // Check that methods we have compiled do have a ProfilingInfo object. We would
1640 // have memory leaks of compiled code otherwise.
1641 for (const auto& it : method_code_map_) {
1642 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001643 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001644 const void* code_ptr = it.first;
1645 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1646 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1647 // If the code is not dead, then we have a problem. Note that this can even
1648 // happen just after a collection, as mutator threads are running in parallel
1649 // and could deoptimize an existing compiled code.
1650 return false;
1651 }
1652 }
1653 }
1654 return true;
1655}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001656
1657OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001658 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1659 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001660 // On Thumb-2, the pc is offset by one.
1661 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001662 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001663 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1664 return nullptr;
1665 }
1666
Vladimir Marko2196c652017-11-30 16:16:07 +00001667 if (!kIsDebugBuild) {
1668 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1669 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001670 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001671
Vladimir Marko2196c652017-11-30 16:16:07 +00001672 MutexLock mu(Thread::Current(), lock_);
1673 OatQuickMethodHeader* method_header = nullptr;
1674 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1675 if (method != nullptr && UNLIKELY(method->IsNative())) {
1676 auto it = jni_stubs_map_.find(JniStubKey(method));
1677 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1678 return nullptr;
1679 }
1680 const void* code_ptr = it->second.GetCode();
1681 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1682 if (!method_header->Contains(pc)) {
1683 return nullptr;
1684 }
1685 } else {
1686 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1687 if (it != method_code_map_.begin()) {
1688 --it;
1689 const void* code_ptr = it->first;
1690 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1691 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1692 found_method = it->second;
1693 }
1694 }
1695 if (method_header == nullptr && method == nullptr) {
1696 // Scan all compiled JNI stubs as well. This slow search is used only
1697 // for checks in debug build, for release builds the `method` is not null.
1698 for (auto&& entry : jni_stubs_map_) {
1699 const JniStubData& data = entry.second;
1700 if (data.IsCompiled() &&
1701 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1702 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1703 }
1704 }
1705 }
1706 if (method_header == nullptr) {
1707 return nullptr;
1708 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001709 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001710
1711 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001712 // When we are walking the stack to redefine classes and creating obsolete methods it is
1713 // possible that we might have updated the method_code_map by making this method obsolete in a
1714 // previous frame. Therefore we should just check that the non-obsolete version of this method
1715 // is the one we expect. We change to the non-obsolete versions in the error message since the
1716 // obsolete version of the method might not be fully initialized yet. This situation can only
1717 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001718 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001719 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001720 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001721 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001722 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001723 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001724 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001725 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001726}
1727
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001728OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1729 MutexLock mu(Thread::Current(), lock_);
1730 auto it = osr_code_map_.find(method);
1731 if (it == osr_code_map_.end()) {
1732 return nullptr;
1733 }
1734 return OatQuickMethodHeader::FromCodePointer(it->second);
1735}
1736
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001737ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1738 ArtMethod* method,
1739 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001740 bool retry_allocation)
1741 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1742 NO_THREAD_SAFETY_ANALYSIS {
1743 ProfilingInfo* info = nullptr;
1744 if (!retry_allocation) {
1745 // If we are allocating for the interpreter, just try to lock, to avoid
1746 // lock contention with the JIT.
1747 if (lock_.ExclusiveTryLock(self)) {
1748 info = AddProfilingInfoInternal(self, method, entries);
1749 lock_.ExclusiveUnlock(self);
1750 }
1751 } else {
1752 {
1753 MutexLock mu(self, lock_);
1754 info = AddProfilingInfoInternal(self, method, entries);
1755 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001756
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001757 if (info == nullptr) {
1758 GarbageCollectCache(self);
1759 MutexLock mu(self, lock_);
1760 info = AddProfilingInfoInternal(self, method, entries);
1761 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001762 }
1763 return info;
1764}
1765
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001766ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001767 ArtMethod* method,
1768 const std::vector<uint32_t>& entries) {
1769 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001770 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001771 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001772
1773 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001774 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001775 if (info != nullptr) {
1776 return info;
1777 }
1778
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001779 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001780 if (data == nullptr) {
1781 return nullptr;
1782 }
1783 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001784
1785 // Make sure other threads see the data in the profiling info object before the
1786 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001787 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001788
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001789 method->SetProfilingInfo(info);
1790 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001791 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001792 return info;
1793}
1794
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001795// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1796// is already held.
1797void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
Orion Hodson1d3fd082018-09-28 09:38:35 +01001798 if (mspace == exec_mspace_) {
1799 DCHECK(exec_mspace_ != nullptr);
1800 const MemMap* const code_pages = GetUpdatableCodeMapping();
1801 void* result = code_pages->Begin() + exec_end_;
1802 exec_end_ += increment;
1803 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001804 } else {
1805 DCHECK_EQ(data_mspace_, mspace);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001806 void* result = data_pages_.Begin() + data_end_;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001807 data_end_ += increment;
Orion Hodson1d3fd082018-09-28 09:38:35 +01001808 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001809 }
1810}
1811
Calin Juravle99629622016-04-19 16:33:46 +01001812void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001813 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001814 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001815 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001816 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001817 for (const ProfilingInfo* info : profiling_infos_) {
1818 ArtMethod* method = info->GetMethod();
1819 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001820 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1821 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001822 // Skip dex files which are not profiled.
1823 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001824 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001825 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001826
1827 // If the method didn't reach the compilation threshold don't save the inline caches.
1828 // They might be incomplete and cause unnecessary deoptimizations.
1829 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1830 if (method->GetCounter() < jit_compile_threshold) {
1831 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001832 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001833 continue;
1834 }
1835
Calin Juravle940eb0c2017-01-30 19:30:44 -08001836 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001837 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001838 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001839 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001840 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001841 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1842 mirror::Class* cls = cache.classes_[k].Read();
1843 if (cls == nullptr) {
1844 break;
1845 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001846
Calin Juravle13439f02017-02-21 01:17:21 -08001847 // Check if the receiver is in the boot class path or if it's in the
1848 // same class loader as the caller. If not, skip it, as there is not
1849 // much we can do during AOT.
1850 if (!cls->IsBootStrapClassLoaded() &&
1851 caller->GetClassLoader() != cls->GetClassLoader()) {
1852 is_missing_types = true;
1853 continue;
1854 }
1855
Calin Juravle4ca70a32017-02-21 16:22:24 -08001856 const DexFile* class_dex_file = nullptr;
1857 dex::TypeIndex type_index;
1858
1859 if (cls->GetDexCache() == nullptr) {
1860 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001861 // Make a best effort to find the type index in the method's dex file.
1862 // We could search all open dex files but that might turn expensive
1863 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001864 class_dex_file = dex_file;
1865 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1866 } else {
1867 class_dex_file = &(cls->GetDexFile());
1868 type_index = cls->GetDexTypeIndex();
1869 }
1870 if (!type_index.IsValid()) {
1871 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001872 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001873 continue;
1874 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001875 if (ContainsElement(dex_base_locations,
1876 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001877 // Only consider classes from the same apk (including multidex).
1878 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001879 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001880 } else {
1881 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001882 }
1883 }
1884 if (!profile_classes.empty()) {
1885 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001886 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001887 }
1888 }
1889 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001890 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001891 }
1892}
1893
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001894bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1895 MutexLock mu(Thread::Current(), lock_);
1896 return osr_code_map_.find(method) != osr_code_map_.end();
1897}
1898
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001899bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1900 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001901 return false;
1902 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001903
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001904 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001905 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1906 return false;
1907 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001908
Vladimir Marko2196c652017-11-30 16:16:07 +00001909 if (UNLIKELY(method->IsNative())) {
1910 JniStubKey key(method);
1911 auto it = jni_stubs_map_.find(key);
1912 bool new_compilation = false;
1913 if (it == jni_stubs_map_.end()) {
1914 // Create a new entry to mark the stub as being compiled.
1915 it = jni_stubs_map_.Put(key, JniStubData{});
1916 new_compilation = true;
1917 }
1918 JniStubData* data = &it->second;
1919 data->AddMethod(method);
1920 if (data->IsCompiled()) {
1921 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1922 const void* entrypoint = method_header->GetEntryPoint();
1923 // Update also entrypoints of other methods held by the JniStubData.
1924 // We could simply update the entrypoint of `method` but if the last JIT GC has
1925 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1926 // as well change them back as this stub shall not be collected anyway and this
1927 // can avoid a few expensive GenericJNI calls.
1928 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1929 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001930 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1931 // `m` might be in the process of being deleted.
1932 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001933 }
1934 if (collection_in_progress_) {
1935 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1936 }
1937 }
1938 return new_compilation;
1939 } else {
1940 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1941 if (info == nullptr) {
1942 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1943 // Because the counter is not atomic, there are some rare cases where we may not hit the
1944 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001945 ClearMethodCounter(method, /*was_warm=*/ false);
Vladimir Marko2196c652017-11-30 16:16:07 +00001946 return false;
1947 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001948
Vladimir Marko2196c652017-11-30 16:16:07 +00001949 if (info->IsMethodBeingCompiled(osr)) {
1950 return false;
1951 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001952
Vladimir Marko2196c652017-11-30 16:16:07 +00001953 info->SetIsMethodBeingCompiled(true, osr);
1954 return true;
1955 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001956}
1957
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001958ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001959 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001960 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001961 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001962 if (!info->IncrementInlineUse()) {
1963 // Overflow of inlining uses, just bail.
1964 return nullptr;
1965 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001966 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001967 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001968}
1969
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001970void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001971 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001972 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001973 DCHECK(info != nullptr);
1974 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001975}
1976
Vladimir Marko2196c652017-11-30 16:16:07 +00001977void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1978 DCHECK_EQ(Thread::Current(), self);
1979 MutexLock mu(self, lock_);
1980 if (UNLIKELY(method->IsNative())) {
1981 auto it = jni_stubs_map_.find(JniStubKey(method));
1982 DCHECK(it != jni_stubs_map_.end());
1983 JniStubData* data = &it->second;
1984 DCHECK(ContainsElement(data->GetMethods(), method));
1985 if (UNLIKELY(!data->IsCompiled())) {
1986 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1987 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1988 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1989 } else {
1990 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1991 DCHECK(info->IsMethodBeingCompiled(osr));
1992 info->SetIsMethodBeingCompiled(false, osr);
1993 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001994}
1995
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001996size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1997 MutexLock mu(Thread::Current(), lock_);
1998 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1999}
2000
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002001void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
2002 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00002003 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07002004 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07002005 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002006 if ((profiling_info != nullptr) &&
2007 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07002008 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
2009 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002010 // Prevent future uses of the compiled code.
2011 profiling_info->SetSavedEntryPoint(nullptr);
2012 }
2013
Alex Light2d441b12018-06-08 15:33:21 -07002014 // Clear the method counter if we are running jitted code since we might want to jit this again in
2015 // the future.
2016 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07002017 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07002018 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002019 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
2020 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002021 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002022 } else {
2023 MutexLock mu(Thread::Current(), lock_);
2024 auto it = osr_code_map_.find(method);
2025 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
2026 // Remove the OSR method, to avoid using it again.
2027 osr_code_map_.erase(it);
2028 }
2029 }
2030}
2031
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002032uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
2033 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
2034 uint8_t* result = reinterpret_cast<uint8_t*>(
Orion Hodson1d3fd082018-09-28 09:38:35 +01002035 mspace_memalign(exec_mspace_, alignment, code_size));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002036 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
2037 // Ensure the header ends up at expected instruction alignment.
2038 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
2039 used_memory_for_code_ += mspace_usable_size(result);
2040 return result;
2041}
2042
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002043void JitCodeCache::FreeCode(uint8_t* code) {
2044 used_memory_for_code_ -= mspace_usable_size(code);
Orion Hodson1d3fd082018-09-28 09:38:35 +01002045 mspace_free(exec_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002046}
2047
2048uint8_t* JitCodeCache::AllocateData(size_t data_size) {
2049 void* result = mspace_malloc(data_mspace_, data_size);
2050 used_memory_for_data_ += mspace_usable_size(result);
2051 return reinterpret_cast<uint8_t*>(result);
2052}
2053
2054void JitCodeCache::FreeData(uint8_t* data) {
2055 used_memory_for_data_ -= mspace_usable_size(data);
2056 mspace_free(data_mspace_, data);
2057}
2058
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002059void JitCodeCache::Dump(std::ostream& os) {
2060 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00002061 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002062 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
2063 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00002064 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002065 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00002066 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002067 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
2068 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
2069 << "Total number of JIT compilations for on stack replacement: "
2070 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002071 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00002072 histogram_stack_map_memory_use_.PrintMemoryUse(os);
2073 histogram_code_memory_use_.PrintMemoryUse(os);
2074 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002075}
2076
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002077} // namespace jit
2078} // namespace art