blob: 8239602b50b86997ea78457c4dcaf3dfaedaf4cb [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,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000188 bool generate_debug_info,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700189 bool used_only_for_profile_data,
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 Geoffraya25dce92016-01-12 16:41:10 +0000194 // With 'perf', we want a 1-1 mapping between an address and a method.
Alex Light2d441b12018-06-08 15:33:21 -0700195 // We aren't able to keep method pointers live during the instrumentation method entry trampoline
196 // so we will just disable jit-gc if we are doing that.
197 bool garbage_collect_code = !generate_debug_info &&
198 !Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000199
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000200 // We need to have 32 bit offsets from method headers in code cache which point to things
201 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
202 // Ensure we're below 1 GB to be safe.
203 if (max_capacity > 1 * GB) {
204 std::ostringstream oss;
205 oss << "Maxium code cache capacity is limited to 1 GB, "
206 << PrettySize(max_capacity) << " is too big";
207 *error_msg = oss.str();
208 return nullptr;
209 }
210
Orion Hodson563ada22018-09-04 11:28:31 +0100211 // Register for membarrier expedited sync core if JIT will be generating code.
212 if (!used_only_for_profile_data) {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100213 if (art::membarrier(art::MembarrierCommand::kRegisterPrivateExpeditedSyncCore) != 0) {
214 // MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE ensures that CPU instruction pipelines are
215 // flushed and it's used when adding code to the JIT. The memory used by the new code may
216 // have just been released and, in theory, the old code could still be in a pipeline.
217 VLOG(jit) << "Kernel does not support membarrier sync-core";
218 }
Orion Hodson563ada22018-09-04 11:28:31 +0100219 }
220
Orion Hodson1d3fd082018-09-28 09:38:35 +0100221 // File descriptor enabling dual-view mapping of code section.
222 unique_fd mem_fd;
223
224 // Bionic supports memfd_create, but the call may fail on older kernels.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700225 mem_fd = unique_fd(art::memfd_create("/jit-cache", /* flags= */ 0));
Orion Hodson1d3fd082018-09-28 09:38:35 +0100226 if (mem_fd.get() < 0) {
227 VLOG(jit) << "Failed to initialize dual view JIT. memfd_create() error: "
228 << strerror(errno);
229 }
230
231 if (mem_fd.get() >= 0 && ftruncate(mem_fd, max_capacity) != 0) {
232 std::ostringstream oss;
233 oss << "Failed to initialize memory file: " << strerror(errno);
234 *error_msg = oss.str();
235 return nullptr;
236 }
237
238 // Data cache will be half of the initial allocation.
239 // Code cache will be the other half of the initial allocation.
240 // TODO: Make this variable?
241
242 // Align both capacities to page size, as that's the unit mspaces use.
243 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
244 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
245 const size_t data_capacity = max_capacity / 2;
246 const size_t exec_capacity = used_only_for_profile_data ? 0 : max_capacity - data_capacity;
247 DCHECK_LE(data_capacity + exec_capacity, max_capacity);
Calin Juravle016fcbe22018-05-03 19:47:35 -0700248
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800249 std::string error_str;
250 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000251 // Map in low 4gb to simplify accessing root tables for x86_64.
252 // We could do PC-relative addressing to avoid this problem, but that
253 // would require reserving code and data area before submitting, which
254 // means more windows for the code memory to be RWX.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100255 int base_flags;
256 MemMap data_pages;
257 if (mem_fd.get() >= 0) {
258 // Dual view of JIT code cache case. Create an initial mapping of data pages large enough
259 // for data and non-writable view of JIT code pages. We use the memory file descriptor to
260 // enable dual mapping - we'll create a second mapping using the descriptor below. The
261 // mappings will look like:
262 //
263 // VA PA
264 //
265 // +---------------+
266 // | non exec code |\
267 // +---------------+ \
268 // : :\ \
269 // +---------------+.\.+---------------+
270 // | exec code | \| code |
271 // +---------------+...+---------------+
272 // | data | | data |
273 // +---------------+...+---------------+
274 //
275 // In this configuration code updates are written to the non-executable view of the code
276 // cache, and the executable view of the code cache has fixed RX memory protections.
277 //
278 // This memory needs to be mapped shared as the code portions will have two mappings.
279 base_flags = MAP_SHARED;
280 data_pages = MemMap::MapFile(
281 data_capacity + exec_capacity,
282 kProtRW,
283 base_flags,
284 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700285 /* start= */ 0,
286 /* low_4gb= */ true,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100287 "data-code-cache",
288 &error_str);
289 } else {
290 // Single view of JIT code cache case. Create an initial mapping of data pages large enough
291 // for data and JIT code pages. The mappings will look like:
292 //
293 // VA PA
294 //
295 // +---------------+...+---------------+
296 // | exec code | | code |
297 // +---------------+...+---------------+
298 // | data | | data |
299 // +---------------+...+---------------+
300 //
301 // In this configuration code updates are written to the executable view of the code cache,
302 // and the executable view of the code cache transitions RX to RWX for the update and then
303 // back to RX after the update.
304 base_flags = MAP_PRIVATE | MAP_ANON;
305 data_pages = MemMap::MapAnonymous(
306 "data-code-cache",
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700307 /* addr= */ nullptr,
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,
311 /* reuse= */ false,
312 /* reservation= */ nullptr,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100313 &error_str);
314 }
315
316 if (!data_pages.IsValid()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800317 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700318 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800319 *error_msg = oss.str();
320 return nullptr;
321 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100322
Orion Hodson1d3fd082018-09-28 09:38:35 +0100323 MemMap exec_pages;
324 MemMap non_exec_pages;
325 if (exec_capacity > 0) {
326 uint8_t* const divider = data_pages.Begin() + data_capacity;
327 // Set initial permission for executable view to catch any SELinux permission problems early
328 // (for processes that cannot map WX pages). Otherwise, this region does not need to be
329 // executable as there is no code in the cache yet.
330 exec_pages = data_pages.RemapAtEnd(divider,
331 "jit-code-cache",
332 kProtRX,
333 base_flags | MAP_FIXED,
334 mem_fd.get(),
335 (mem_fd.get() >= 0) ? data_capacity : 0,
336 &error_str);
337 if (!exec_pages.IsValid()) {
338 std::ostringstream oss;
339 oss << "Failed to create read execute code cache: " << error_str << " size=" << max_capacity;
340 *error_msg = oss.str();
341 return nullptr;
342 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100343
Orion Hodson1d3fd082018-09-28 09:38:35 +0100344 if (mem_fd.get() >= 0) {
345 // For dual view, create the secondary view of code memory used for updating code. This view
346 // is never executable.
347 non_exec_pages = MemMap::MapFile(exec_capacity,
348 kProtR,
349 base_flags,
350 mem_fd,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700351 /* start= */ data_capacity,
352 /* low_4GB= */ false,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100353 "jit-code-cache-rw",
354 &error_str);
355 if (!non_exec_pages.IsValid()) {
356 // Log and continue as single view JIT.
357 VLOG(jit) << "Failed to map non-executable view of JIT code cache";
358 }
359 }
360 } else {
361 // Profiling only. No memory for code required.
362 DCHECK(used_only_for_profile_data);
David Sehrd1dbb742017-07-17 11:20:38 -0700363 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100364
365 const size_t initial_data_capacity = initial_capacity / 2;
366 const size_t initial_exec_capacity =
367 (exec_capacity == 0) ? 0 : (initial_capacity - initial_data_capacity);
368
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100369 return new JitCodeCache(
Orion Hodson1d3fd082018-09-28 09:38:35 +0100370 std::move(data_pages),
371 std::move(exec_pages),
372 std::move(non_exec_pages),
373 initial_data_capacity,
374 initial_exec_capacity,
Calin Juravle016fcbe22018-05-03 19:47:35 -0700375 max_capacity,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100376 garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800377}
378
Orion Hodson1d3fd082018-09-28 09:38:35 +0100379JitCodeCache::JitCodeCache(MemMap&& data_pages,
380 MemMap&& exec_pages,
381 MemMap&& non_exec_pages,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000382 size_t initial_data_capacity,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100383 size_t initial_exec_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000384 size_t max_capacity,
Orion Hodson1d3fd082018-09-28 09:38:35 +0100385 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100386 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000387 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100388 collection_in_progress_(false),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100389 data_pages_(std::move(data_pages)),
390 exec_pages_(std::move(exec_pages)),
391 non_exec_pages_(std::move(non_exec_pages)),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000392 max_capacity_(max_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100393 current_capacity_(initial_exec_capacity + initial_data_capacity),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000394 data_end_(initial_data_capacity),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100395 exec_end_(initial_exec_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000396 last_collection_increased_code_cache_(false),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000397 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000398 used_memory_for_data_(0),
399 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000400 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000401 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000402 number_of_collections_(0),
403 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
404 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000405 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
406 is_weak_access_enabled_(true),
Orion Hodson1d3fd082018-09-28 09:38:35 +0100407 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408
Orion Hodson1d3fd082018-09-28 09:38:35 +0100409 DCHECK_GE(max_capacity, initial_exec_capacity + initial_data_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100410
Orion Hodson1d3fd082018-09-28 09:38:35 +0100411 // Initialize the data heap
412 data_mspace_ = create_mspace_with_base(data_pages_.Begin(), data_end_, false /*locked*/);
413 CHECK(data_mspace_ != nullptr) << "create_mspace_with_base (data) failed";
414
415 // Initialize the code heap
416 MemMap* code_heap = nullptr;
417 if (non_exec_pages_.IsValid()) {
418 code_heap = &non_exec_pages_;
419 } else if (exec_pages_.IsValid()) {
420 code_heap = &exec_pages_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100421 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100422 if (code_heap != nullptr) {
423 // Make all pages reserved for the code heap writable. The mspace allocator, that manages the
424 // heap, will take and initialize pages in create_mspace_with_base().
425 CheckedCall(mprotect, "create code heap", code_heap->Begin(), code_heap->Size(), kProtRW);
426 exec_mspace_ = create_mspace_with_base(code_heap->Begin(), exec_end_, false /*locked*/);
427 CHECK(exec_mspace_ != nullptr) << "create_mspace_with_base (exec) failed";
428 SetFootprintLimit(current_capacity_);
429 // Protect pages containing heap metadata. Updates to the code heap toggle write permission to
430 // perform the update and there are no other times write access is required.
431 CheckedCall(mprotect, "protect code heap", code_heap->Begin(), code_heap->Size(), kProtR);
432 } else {
433 exec_mspace_ = nullptr;
434 SetFootprintLimit(current_capacity_);
435 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100436
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000437 VLOG(jit) << "Created jit code cache: initial data size="
438 << PrettySize(initial_data_capacity)
439 << ", initial code size="
Orion Hodson1d3fd082018-09-28 09:38:35 +0100440 << PrettySize(initial_exec_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800441}
442
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000443JitCodeCache::~JitCodeCache() {}
444
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100445bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodson1d3fd082018-09-28 09:38:35 +0100446 return exec_pages_.Begin() <= ptr && ptr < exec_pages_.End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800447}
448
Alex Light2d441b12018-06-08 15:33:21 -0700449bool JitCodeCache::WillExecuteJitCode(ArtMethod* method) {
450 ScopedObjectAccess soa(art::Thread::Current());
451 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
452 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
453 return true;
454 } else if (method->GetEntryPointFromQuickCompiledCode() == GetQuickInstrumentationEntryPoint()) {
455 return FindCompiledCodeForInstrumentation(method) != nullptr;
456 }
457 return false;
458}
459
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000460bool JitCodeCache::ContainsMethod(ArtMethod* method) {
461 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000462 if (UNLIKELY(method->IsNative())) {
463 auto it = jni_stubs_map_.find(JniStubKey(method));
464 if (it != jni_stubs_map_.end() &&
465 it->second.IsCompiled() &&
466 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000467 return true;
468 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000469 } else {
470 for (const auto& it : method_code_map_) {
471 if (it.second == method) {
472 return true;
473 }
474 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000475 }
476 return false;
477}
478
Vladimir Marko2196c652017-11-30 16:16:07 +0000479const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
480 DCHECK(method->IsNative());
481 MutexLock mu(Thread::Current(), lock_);
482 auto it = jni_stubs_map_.find(JniStubKey(method));
483 if (it != jni_stubs_map_.end()) {
484 JniStubData& data = it->second;
485 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
486 return data.GetCode();
487 }
488 }
489 return nullptr;
490}
491
Alex Light2d441b12018-06-08 15:33:21 -0700492const void* JitCodeCache::FindCompiledCodeForInstrumentation(ArtMethod* method) {
Alex Light839f53a2018-07-10 15:46:14 -0700493 // If jit-gc is still on we use the SavedEntryPoint field for doing that and so cannot use it to
494 // find the instrumentation entrypoint.
495 if (LIKELY(GetGarbageCollectCode())) {
Alex Light2d441b12018-06-08 15:33:21 -0700496 return nullptr;
497 }
498 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
499 if (info == nullptr) {
500 return nullptr;
501 }
502 // When GC is disabled for trampoline tracing we will use SavedEntrypoint to hold the actual
503 // jit-compiled version of the method. If jit-gc is disabled for other reasons this will just be
504 // nullptr.
505 return info->GetSavedEntryPoint();
506}
507
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800508class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100509 public:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700510 explicit ScopedCodeCacheWrite(const JitCodeCache* const code_cache)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100511 : ScopedTrace("ScopedCodeCacheWrite"),
Calin Juravle016fcbe22018-05-03 19:47:35 -0700512 code_cache_(code_cache) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800513 ScopedTrace trace("mprotect all");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100514 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
515 if (updatable_pages != nullptr) {
516 int prot = code_cache_->HasDualCodeMapping() ? kProtRW : kProtRWX;
517 CheckedCall(mprotect, "Cache +W", updatable_pages->Begin(), updatable_pages->Size(), prot);
518 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800519 }
Calin Juravle016fcbe22018-05-03 19:47:35 -0700520
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100521 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800522 ScopedTrace trace("mprotect code");
Orion Hodson1d3fd082018-09-28 09:38:35 +0100523 const MemMap* const updatable_pages = code_cache_->GetUpdatableCodeMapping();
524 if (updatable_pages != nullptr) {
525 int prot = code_cache_->HasDualCodeMapping() ? kProtR : kProtRX;
526 CheckedCall(mprotect, "Cache -W", updatable_pages->Begin(), updatable_pages->Size(), prot);
527 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100528 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700529
David Sehrd1dbb742017-07-17 11:20:38 -0700530 private:
Calin Juravle016fcbe22018-05-03 19:47:35 -0700531 const JitCodeCache* const code_cache_;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100532
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100533 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
534};
535
536uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100537 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000538 uint8_t* stack_map,
539 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100540 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000541 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100542 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000543 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100544 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700545 bool has_should_deoptimize_flag,
546 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100547 uint8_t* result = CommitCodeInternal(self,
548 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000549 stack_map,
550 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100551 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000552 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100553 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000554 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700555 roots,
556 has_should_deoptimize_flag,
557 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100558 if (result == nullptr) {
559 // Retry.
560 GarbageCollectCache(self);
561 result = CommitCodeInternal(self,
562 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000563 stack_map,
564 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100565 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000566 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100567 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000568 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700569 roots,
570 has_should_deoptimize_flag,
571 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100572 }
573 return result;
574}
575
576bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
577 bool in_collection = false;
578 while (collection_in_progress_) {
579 in_collection = true;
580 lock_cond_.Wait(self);
581 }
582 return in_collection;
583}
584
585static uintptr_t FromCodeToAllocation(const void* code) {
586 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
587 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
588}
589
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000590static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
591 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
592}
593
594static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
595 // The length of the table is stored just before the stack map (and therefore at the end of
596 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
597 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
598}
599
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800600static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
601 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
602 // pointer.
603 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
604}
605
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000606static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
607 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
608}
609
Vladimir Markoac3ac682018-09-20 11:01:43 +0100610static void DCheckRootsAreValid(const std::vector<Handle<mirror::Object>>& roots)
Alex Light3e36a9c2018-06-19 09:45:05 -0700611 REQUIRES(!Locks::intern_table_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
612 if (!kIsDebugBuild) {
613 return;
614 }
Alex Light3e36a9c2018-06-19 09:45:05 -0700615 // Put all roots in `roots_data`.
Vladimir Markoac3ac682018-09-20 11:01:43 +0100616 for (Handle<mirror::Object> object : roots) {
Alex Light3e36a9c2018-06-19 09:45:05 -0700617 // Ensure the string is strongly interned. b/32995596
618 if (object->IsString()) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100619 ObjPtr<mirror::String> str = object->AsString();
Alex Light3e36a9c2018-06-19 09:45:05 -0700620 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
621 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
622 }
623 }
624}
625
626void JitCodeCache::FillRootTable(uint8_t* roots_data,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100627 const std::vector<Handle<mirror::Object>>& roots) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000628 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Vladimir Markoac3ac682018-09-20 11:01:43 +0100629 const uint32_t length = roots.size();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000630 // Put all roots in `roots_data`.
631 for (uint32_t i = 0; i < length; ++i) {
Vladimir Markoac3ac682018-09-20 11:01:43 +0100632 ObjPtr<mirror::Object> object = roots[i].Get();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000633 gc_roots[i] = GcRoot<mirror::Object>(object);
634 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000635}
636
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100637static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000638 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
639 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
640 uint32_t roots = GetNumberOfRoots(data);
641 if (number_of_roots != nullptr) {
642 *number_of_roots = roots;
643 }
644 return data - ComputeRootTableSize(roots);
645}
646
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100647// Use a sentinel for marking entries in the JIT table that have been cleared.
648// This helps diagnosing in case the compiled code tries to wrongly access such
649// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700650static mirror::Class* const weak_sentinel =
651 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100652
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000653// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100654static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
655 IsMarkedVisitor* visitor,
656 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000657 REQUIRES_SHARED(Locks::mutator_lock_) {
658 // This does not need a read barrier because this is called by GC.
659 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100660 if (cls != nullptr && cls != weak_sentinel) {
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700661 DCHECK((cls->IsClass<kDefaultVerifyFlags>()));
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000662 // Look at the classloader of the class to know if it has been unloaded.
663 // This does not need a read barrier because this is called by GC.
664 mirror::Object* class_loader =
665 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
666 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
667 // The class loader is live, update the entry if the class has moved.
668 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
669 // Note that new_object can be null for CMS and newly allocated objects.
670 if (new_cls != nullptr && new_cls != cls) {
671 *root_ptr = GcRoot<mirror::Class>(new_cls);
672 }
673 } else {
674 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100675 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000676 }
677 }
678}
679
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000680void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
681 MutexLock mu(Thread::Current(), lock_);
682 for (const auto& entry : method_code_map_) {
683 uint32_t number_of_roots = 0;
684 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
685 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
686 for (uint32_t i = 0; i < number_of_roots; ++i) {
687 // This does not need a read barrier because this is called by GC.
688 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100689 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000690 // entry got deleted in a previous sweep.
691 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
692 mirror::Object* new_object = visitor->IsMarked(object);
693 // We know the string is marked because it's a strongly-interned string that
694 // is always alive. The IsMarked implementation of the CMS collector returns
695 // null for newly allocated objects, but we know those haven't moved. Therefore,
696 // only update the entry if we get a different non-null string.
697 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
698 // out of the weak access/creation pause. b/32167580
699 if (new_object != nullptr && new_object != object) {
700 DCHECK(new_object->IsString());
701 roots[i] = GcRoot<mirror::Object>(new_object);
702 }
703 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100704 ProcessWeakClass(
705 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000706 }
707 }
708 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000709 // Walk over inline caches to clear entries containing unloaded classes.
710 for (ProfilingInfo* info : profiling_infos_) {
711 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
712 InlineCache* cache = &info->cache_[i];
713 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100714 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000715 }
716 }
717 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000718}
719
Orion Hodson607624f2018-05-11 10:10:46 +0100720void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100721 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000722 // Notify native debugger that we are about to remove the code.
723 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000724 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000725 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000726 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
727 FreeData(GetRootTable(code_ptr));
728 } // else this is a JNI stub without any data.
Orion Hodson1d3fd082018-09-28 09:38:35 +0100729
730 uint8_t* code_allocation = reinterpret_cast<uint8_t*>(allocation);
731 if (HasDualCodeMapping()) {
732 code_allocation = TranslateAddress(code_allocation, exec_pages_, non_exec_pages_);
733 }
734
735 FreeCode(code_allocation);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100736}
737
Mingyao Yang063fc772016-08-02 11:02:54 -0700738void JitCodeCache::FreeAllMethodHeaders(
739 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700740 // We need to remove entries in method_headers from CHA dependencies
741 // first since once we do FreeCode() below, the memory can be reused
742 // so it's possible for the same method_header to start representing
743 // different compile code.
744 MutexLock mu(Thread::Current(), lock_);
Alex Light33b7b5d2018-08-07 19:13:51 +0000745 {
746 MutexLock mu2(Thread::Current(), *Locks::cha_lock_);
747 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
748 ->RemoveDependentsWithMethodHeaders(method_headers);
749 }
750
Calin Juravle016fcbe22018-05-03 19:47:35 -0700751 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700752 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodson607624f2018-05-11 10:10:46 +0100753 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700754 }
755}
756
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100757void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800758 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700759 // We use a set to first collect all method_headers whose code need to be
760 // removed. We need to free the underlying code after we remove CHA dependencies
761 // for entries in this set. And it's more efficient to iterate through
762 // the CHA dependency map just once with an unordered_set.
763 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000764 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700765 MutexLock mu(self, lock_);
766 // We do not check if a code cache GC is in progress, as this method comes
767 // with the classlinker_classes_lock_ held, and suspending ourselves could
768 // lead to a deadlock.
769 {
Calin Juravle016fcbe22018-05-03 19:47:35 -0700770 ScopedCodeCacheWrite scc(this);
Vladimir Marko2196c652017-11-30 16:16:07 +0000771 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
772 it->second.RemoveMethodsIn(alloc);
773 if (it->second.GetMethods().empty()) {
774 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
775 it = jni_stubs_map_.erase(it);
776 } else {
777 it->first.UpdateShorty(it->second.GetMethods().front());
778 ++it;
779 }
780 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700781 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
782 if (alloc.ContainsUnsafe(it->second)) {
783 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
784 it = method_code_map_.erase(it);
785 } else {
786 ++it;
787 }
788 }
789 }
790 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
791 if (alloc.ContainsUnsafe(it->first)) {
792 // Note that the code has already been pushed to method_headers in the loop
793 // above and is going to be removed in FreeCode() below.
794 it = osr_code_map_.erase(it);
795 } else {
796 ++it;
797 }
798 }
799 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
800 ProfilingInfo* info = *it;
801 if (alloc.ContainsUnsafe(info->GetMethod())) {
802 info->GetMethod()->SetProfilingInfo(nullptr);
803 FreeData(reinterpret_cast<uint8_t*>(info));
804 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000805 } else {
806 ++it;
807 }
808 }
809 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700810 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100811}
812
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000813bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
814 return kUseReadBarrier
815 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000816 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000817}
818
819void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
820 if (IsWeakAccessEnabled(self)) {
821 return;
822 }
823 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000824 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000825 while (!IsWeakAccessEnabled(self)) {
826 inline_cache_cond_.Wait(self);
827 }
828}
829
830void JitCodeCache::BroadcastForInlineCacheAccess() {
831 Thread* self = Thread::Current();
832 MutexLock mu(self, lock_);
833 inline_cache_cond_.Broadcast(self);
834}
835
836void JitCodeCache::AllowInlineCacheAccess() {
837 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000838 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000839 BroadcastForInlineCacheAccess();
840}
841
842void JitCodeCache::DisallowInlineCacheAccess() {
843 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000844 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000845}
846
847void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
848 Handle<mirror::ObjectArray<mirror::Class>> array) {
849 WaitUntilInlineCacheAccessible(Thread::Current());
850 // Note that we don't need to lock `lock_` here, the compiler calling
851 // this method has already ensured the inline cache will not be deleted.
852 for (size_t in_cache = 0, in_array = 0;
853 in_cache < InlineCache::kIndividualCacheSize;
854 ++in_cache) {
855 mirror::Class* object = ic.classes_[in_cache].Read();
856 if (object != nullptr) {
857 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000858 }
859 }
860}
861
Mathieu Chartierf044c222017-05-31 15:27:54 -0700862static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
863 if (was_warm) {
Vladimir Markoc945e0d2018-07-18 17:26:45 +0100864 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700865 }
866 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
867 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100868 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
869 // the warmup threshold is 1.
870 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
871 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700872}
873
Alex Light33b7b5d2018-08-07 19:13:51 +0000874void JitCodeCache::WaitForPotentialCollectionToCompleteRunnable(Thread* self) {
875 while (collection_in_progress_) {
876 lock_.Unlock(self);
877 {
878 ScopedThreadSuspension sts(self, kSuspended);
879 MutexLock mu(self, lock_);
880 WaitForPotentialCollectionToComplete(self);
881 }
882 lock_.Lock(self);
883 }
884}
885
Orion Hodson1d3fd082018-09-28 09:38:35 +0100886const MemMap* JitCodeCache::GetUpdatableCodeMapping() const {
887 if (HasDualCodeMapping()) {
888 return &non_exec_pages_;
889 } else if (HasCodeMapping()) {
890 return &exec_pages_;
891 } else {
892 return nullptr;
893 }
894}
895
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100896uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
897 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000898 uint8_t* stack_map,
899 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100900 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000901 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100902 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000903 bool osr,
Vladimir Markoac3ac682018-09-20 11:01:43 +0100904 const std::vector<Handle<mirror::Object>>& roots,
Mingyao Yang063fc772016-08-02 11:02:54 -0700905 bool has_should_deoptimize_flag,
906 const ArenaSet<ArtMethod*>&
907 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000908 DCHECK(!method->IsNative() || !osr);
Alex Light33b7b5d2018-08-07 19:13:51 +0000909
910 if (!method->IsNative()) {
911 // We need to do this before grabbing the lock_ because it needs to be able to see the string
912 // InternTable. Native methods do not have roots.
913 DCheckRootsAreValid(roots);
914 }
915
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100916 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100917 uint8_t* code_ptr = nullptr;
Orion Hodson1d3fd082018-09-28 09:38:35 +0100918
Alex Light33b7b5d2018-08-07 19:13:51 +0000919 MutexLock mu(self, lock_);
920 // We need to make sure that there will be no jit-gcs going on and wait for any ongoing one to
921 // finish.
922 WaitForPotentialCollectionToCompleteRunnable(self);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100923 {
Alex Light33b7b5d2018-08-07 19:13:51 +0000924 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100925
926 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
927 // Ensure the header ends up at expected instruction alignment.
928 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
929 size_t total_size = header_size + code_size;
930
931 // AllocateCode allocates memory in non-executable region for alignment header and code. The
932 // header size may include alignment padding.
933 uint8_t* nox_memory = AllocateCode(total_size);
934 if (nox_memory == nullptr) {
Alex Light33b7b5d2018-08-07 19:13:51 +0000935 return nullptr;
936 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000937
Orion Hodson1d3fd082018-09-28 09:38:35 +0100938 // code_ptr points to non-executable code.
939 code_ptr = nox_memory + header_size;
Alex Light33b7b5d2018-08-07 19:13:51 +0000940 std::copy(code, code + code_size, code_ptr);
941 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100942
943 // From here code_ptr points to executable code.
944 if (HasDualCodeMapping()) {
945 code_ptr = TranslateAddress(code_ptr, non_exec_pages_, exec_pages_);
946 }
947
Alex Light33b7b5d2018-08-07 19:13:51 +0000948 new (method_header) OatQuickMethodHeader(
949 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
950 code_size);
Orion Hodson1d3fd082018-09-28 09:38:35 +0100951
952 DCHECK(!Runtime::Current()->IsAotCompiler());
953 if (has_should_deoptimize_flag) {
954 method_header->SetHasShouldDeoptimizeFlag();
955 }
956
957 // Update method_header pointer to executable code region.
958 if (HasDualCodeMapping()) {
959 method_header = TranslateAddress(method_header, non_exec_pages_, exec_pages_);
960 }
961
962 // Both instruction and data caches need flushing to the point of unification where both share
963 // a common view of memory. Flushing the data cache ensures the dirty cachelines from the
964 // newly added code are written out to the point of unification. Flushing the instruction
965 // cache ensures the newly written code will be fetched from the point of unification before
966 // use. Memory in the code cache is re-cycled as code is added and removed. The flushes
967 // prevent stale code from residing in the instruction cache.
968 //
969 // Caches are flushed before write permission is removed because some ARMv8 Qualcomm kernels
970 // may trigger a segfault if a page fault occurs when requesting a cache maintenance
971 // operation. This is a kernel bug that we need to work around until affected devices
972 // (e.g. Nexus 5X and 6P) stop being supported or their kernels are fixed.
Alex Light33b7b5d2018-08-07 19:13:51 +0000973 //
974 // For reference, this behavior is caused by this commit:
975 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Orion Hodson1d3fd082018-09-28 09:38:35 +0100976 //
977 if (HasDualCodeMapping()) {
978 // Flush the data cache lines associated with the non-executable copy of the code just added.
979 FlushDataCache(nox_memory, nox_memory + total_size);
980 }
981 // FlushInstructionCache() flushes both data and instruction caches lines. The cacheline range
982 // flushed is for the executable mapping of the code just added.
Orion Hodson38d29fd2018-09-07 12:58:37 +0100983 FlushInstructionCache(code_ptr, code_ptr + code_size);
Orion Hodsonf2331362018-07-11 15:14:10 +0100984
985 // Ensure CPU instruction pipelines are flushed for all cores. This is necessary for
986 // correctness as code may still be in instruction pipelines despite the i-cache flush. It is
987 // not safe to assume that changing permissions with mprotect (RX->RWX->RX) will cause a TLB
988 // shootdown (incidentally invalidating the CPU pipelines by sending an IPI to all cores to
989 // notify them of the TLB invalidation). Some architectures, notably ARM and ARM64, have
990 // hardware support that broadcasts TLB invalidations and so their kernels have no software
Orion Hodson1d3fd082018-09-28 09:38:35 +0100991 // based TLB shootdown. The sync-core flavor of membarrier was introduced in Linux 4.16 to
992 // address this (see mbarrier(2)). The membarrier here will fail on prior kernels and on
993 // platforms lacking the appropriate support.
Orion Hodson563ada22018-09-04 11:28:31 +0100994 art::membarrier(art::MembarrierCommand::kPrivateExpeditedSyncCore);
Orion Hodson38d29fd2018-09-07 12:58:37 +0100995
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000996 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100997 }
Orion Hodson1d3fd082018-09-28 09:38:35 +0100998
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000999 // We need to update the entry point in the runnable state for the instrumentation.
1000 {
Alex Light33b7b5d2018-08-07 19:13:51 +00001001 // The following needs to be guarded by cha_lock_ also. Otherwise it's possible that the
1002 // compiled code is considered invalidated by some class linking, but below we still make the
1003 // compiled code valid for the method. Need cha_lock_ for checking all single-implementation
1004 // flags and register dependencies.
Mingyao Yang063fc772016-08-02 11:02:54 -07001005 MutexLock cha_mu(self, *Locks::cha_lock_);
1006 bool single_impl_still_valid = true;
1007 for (ArtMethod* single_impl : cha_single_implementation_list) {
1008 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001009 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
1010 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -07001011 single_impl_still_valid = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001012 ClearMethodCounter(method, /*was_warm=*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -07001013 break;
1014 }
1015 }
1016
1017 // Discard the code if any single-implementation assumptions are now invalid.
1018 if (!single_impl_still_valid) {
1019 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
1020 return nullptr;
1021 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00001022 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -08001023 << "Should not be using cha on debuggable apps/runs!";
1024
Mingyao Yang063fc772016-08-02 11:02:54 -07001025 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07001026 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -07001027 single_impl, method, method_header);
1028 }
1029
Vladimir Marko2196c652017-11-30 16:16:07 +00001030 if (UNLIKELY(method->IsNative())) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001031 auto it = jni_stubs_map_.find(JniStubKey(method));
1032 DCHECK(it != jni_stubs_map_.end())
1033 << "Entry inserted in NotifyCompilationOf() should be alive.";
1034 JniStubData* data = &it->second;
1035 DCHECK(ContainsElement(data->GetMethods(), method))
1036 << "Entry inserted in NotifyCompilationOf() should contain this method.";
1037 data->SetCode(code_ptr);
1038 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
1039 for (ArtMethod* m : data->GetMethods()) {
1040 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
1041 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001042 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001043 // Fill the root table before updating the entry point.
1044 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
1045 DCHECK_LE(roots_data, stack_map);
1046 FillRootTable(roots_data, roots);
1047 {
1048 // Flush data cache, as compiled code references literals in it.
Orion Hodson38d29fd2018-09-07 12:58:37 +01001049 FlushDataCache(roots_data, roots_data + data_size);
Vladimir Marko2196c652017-11-30 16:16:07 +00001050 }
1051 method_code_map_.Put(code_ptr, method);
1052 if (osr) {
1053 number_of_osr_compilations_++;
1054 osr_code_map_.Put(method, code_ptr);
1055 } else {
1056 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1057 method, method_header->GetEntryPoint());
1058 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001059 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001060 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001061 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -07001062 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001063 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1064 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
1065 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -07001066 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
1067 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001068 histogram_code_memory_use_.AddValue(code_size);
1069 if (code_size > kCodeSizeLogThreshold) {
1070 LOG(INFO) << "JIT allocated "
1071 << PrettySize(code_size)
1072 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -07001073 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001074 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001075 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001076
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001077 return reinterpret_cast<uint8_t*>(method_header);
1078}
1079
1080size_t JitCodeCache::CodeCacheSize() {
1081 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001082 return CodeCacheSizeLocked();
1083}
1084
Orion Hodsoneced6922017-06-01 10:54:28 +01001085bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001086 // This function is used only for testing and only with non-native methods.
1087 CHECK(!method->IsNative());
1088
Orion Hodsoneced6922017-06-01 10:54:28 +01001089 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +01001090
Vladimir Marko2196c652017-11-30 16:16:07 +00001091 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
1092 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +01001093
1094 if (!in_cache) {
1095 return false;
1096 }
1097
Orion Hodsoneced6922017-06-01 10:54:28 +01001098 method->ClearCounter();
1099 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1100 method, GetQuickToInterpreterBridge());
1101 VLOG(jit)
1102 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1103 << ArtMethod::PrettyMethod(method) << "@" << method
1104 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1105 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1106 return true;
1107}
1108
Vladimir Marko2196c652017-11-30 16:16:07 +00001109bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
1110 if (LIKELY(!method->IsNative())) {
1111 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1112 if (info != nullptr) {
1113 RemoveElement(profiling_infos_, info);
1114 }
1115 method->SetProfilingInfo(nullptr);
1116 }
1117
1118 bool in_cache = false;
Calin Juravle016fcbe22018-05-03 19:47:35 -07001119 ScopedCodeCacheWrite ccw(this);
Vladimir Marko2196c652017-11-30 16:16:07 +00001120 if (UNLIKELY(method->IsNative())) {
1121 auto it = jni_stubs_map_.find(JniStubKey(method));
1122 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
1123 in_cache = true;
1124 if (it->second.GetMethods().empty()) {
1125 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001126 FreeCodeAndData(it->second.GetCode());
Vladimir Marko2196c652017-11-30 16:16:07 +00001127 }
1128 jni_stubs_map_.erase(it);
1129 } else {
1130 it->first.UpdateShorty(it->second.GetMethods().front());
1131 }
1132 }
1133 } else {
1134 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1135 if (it->second == method) {
1136 in_cache = true;
1137 if (release_memory) {
Orion Hodson607624f2018-05-11 10:10:46 +01001138 FreeCodeAndData(it->first);
Vladimir Marko2196c652017-11-30 16:16:07 +00001139 }
1140 it = method_code_map_.erase(it);
1141 } else {
1142 ++it;
1143 }
1144 }
1145
1146 auto osr_it = osr_code_map_.find(method);
1147 if (osr_it != osr_code_map_.end()) {
1148 osr_code_map_.erase(osr_it);
1149 }
1150 }
1151
1152 return in_cache;
1153}
1154
Alex Lightdba61482016-12-21 08:20:29 -08001155// This notifies the code cache that the given method has been redefined and that it should remove
1156// any cached information it has on the method. All threads must be suspended before calling this
1157// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1158void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1159 MutexLock mu(Thread::Current(), lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001160 RemoveMethodLocked(method, /* release_memory= */ true);
Alex Lightdba61482016-12-21 08:20:29 -08001161}
1162
1163// This invalidates old_method. Once this function returns one can no longer use old_method to
1164// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1165// class redefinition.
1166// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1167// shouldn't be used since it is no longer logically in the jit code cache.
1168// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1169void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001170 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +00001171 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001172 // Update methods in jni_stubs_map_.
1173 for (auto& entry : jni_stubs_map_) {
1174 JniStubData& data = entry.second;
1175 data.MoveObsoleteMethod(old_method, new_method);
1176 }
Alex Lighteee0bd42017-02-14 15:31:45 +00001177 return;
1178 }
Alex Lightdba61482016-12-21 08:20:29 -08001179 // Update ProfilingInfo to the new one and remove it from the old_method.
1180 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1181 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1182 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1183 old_method->SetProfilingInfo(nullptr);
1184 // Since the JIT should be paused and all threads suspended by the time this is called these
1185 // checks should always pass.
1186 DCHECK(!info->IsInUseByCompiler());
1187 new_method->SetProfilingInfo(info);
Alex Light2d441b12018-06-08 15:33:21 -07001188 // Get rid of the old saved entrypoint if it is there.
1189 info->SetSavedEntryPoint(nullptr);
Alex Lightdba61482016-12-21 08:20:29 -08001190 info->method_ = new_method;
1191 }
1192 // Update method_code_map_ to point to the new method.
1193 for (auto& it : method_code_map_) {
1194 if (it.second == old_method) {
1195 it.second = new_method;
1196 }
1197 }
1198 // Update osr_code_map_ to point to the new method.
1199 auto code_map = osr_code_map_.find(old_method);
1200 if (code_map != osr_code_map_.end()) {
1201 osr_code_map_.Put(new_method, code_map->second);
1202 osr_code_map_.erase(old_method);
1203 }
1204}
1205
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001206size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001207 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001208}
1209
1210size_t JitCodeCache::DataCacheSize() {
1211 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001212 return DataCacheSizeLocked();
1213}
1214
1215size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001216 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001217}
1218
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001219void JitCodeCache::ClearData(Thread* self,
1220 uint8_t* stack_map_data,
1221 uint8_t* roots_data) {
1222 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001223 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001224 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001225}
1226
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001227size_t JitCodeCache::ReserveData(Thread* self,
1228 size_t stack_map_size,
1229 size_t number_of_roots,
1230 ArtMethod* method,
1231 uint8_t** stack_map_data,
1232 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001233 size_t table_size = ComputeRootTableSize(number_of_roots);
David Srbecky8cd54542018-07-15 23:58:44 +01001234 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001235 uint8_t* result = nullptr;
1236
1237 {
1238 ScopedThreadSuspension sts(self, kSuspended);
1239 MutexLock mu(self, lock_);
1240 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001241 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001242 }
1243
1244 if (result == nullptr) {
1245 // Retry.
1246 GarbageCollectCache(self);
1247 ScopedThreadSuspension sts(self, kSuspended);
1248 MutexLock mu(self, lock_);
1249 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001250 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001251 }
1252
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001253 MutexLock mu(self, lock_);
1254 histogram_stack_map_memory_use_.AddValue(size);
1255 if (size > kStackMapSizeLogThreshold) {
1256 LOG(INFO) << "JIT allocated "
1257 << PrettySize(size)
1258 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001259 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001260 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001261 if (result != nullptr) {
1262 *roots_data = result;
1263 *stack_map_data = result + table_size;
1264 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001265 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001266 } else {
1267 *roots_data = nullptr;
1268 *stack_map_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001269 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001270 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001271}
1272
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001273class MarkCodeVisitor final : public StackVisitor {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001274 public:
1275 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1276 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1277 code_cache_(code_cache_in),
1278 bitmap_(code_cache_->GetLiveBitmap()) {}
1279
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001280 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001281 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1282 if (method_header == nullptr) {
1283 return true;
1284 }
1285 const void* code = method_header->GetCode();
1286 if (code_cache_->ContainsPc(code)) {
1287 // Use the atomic set version, as multiple threads are executing this code.
1288 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1289 }
1290 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001291 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001292
1293 private:
1294 JitCodeCache* const code_cache_;
1295 CodeCacheBitmap* const bitmap_;
1296};
1297
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001298class MarkCodeClosure final : public Closure {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001299 public:
1300 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1301 : code_cache_(code_cache), barrier_(barrier) {}
1302
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001303 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001304 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001305 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1306 MarkCodeVisitor visitor(thread, code_cache_);
1307 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001308 if (kIsDebugBuild) {
1309 // The stack walking code queries the side instrumentation stack if it
1310 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1311 // must have been seen. We sanity check this below.
1312 for (const instrumentation::InstrumentationStackFrame& frame
1313 : *thread->GetInstrumentationStack()) {
1314 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1315 // its stack frame, it is not the method owning return_pc_. We just pass null to
1316 // LookupMethodHeader: the method is only checked against in debug builds.
1317 OatQuickMethodHeader* method_header =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001318 code_cache_->LookupMethodHeader(frame.return_pc_, /* method= */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001319 if (method_header != nullptr) {
1320 const void* code = method_header->GetCode();
1321 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1322 }
1323 }
1324 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001325 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001326 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001327
1328 private:
1329 JitCodeCache* const code_cache_;
1330 Barrier* const barrier_;
1331};
1332
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001333void JitCodeCache::NotifyCollectionDone(Thread* self) {
1334 collection_in_progress_ = false;
1335 lock_cond_.Broadcast(self);
1336}
1337
1338void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1339 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001340 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001341 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1342 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001343 if (HasCodeMapping()) {
Calin Juravle016fcbe22018-05-03 19:47:35 -07001344 ScopedCodeCacheWrite scc(this);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001345 mspace_set_footprint_limit(exec_mspace_, per_space_footprint);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001346 }
1347}
1348
1349bool JitCodeCache::IncreaseCodeCacheCapacity() {
1350 if (current_capacity_ == max_capacity_) {
1351 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001352 }
1353
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001354 // Double the capacity if we're below 1MB, or increase it by 1MB if
1355 // we're above.
1356 if (current_capacity_ < 1 * MB) {
1357 current_capacity_ *= 2;
1358 } else {
1359 current_capacity_ += 1 * MB;
1360 }
1361 if (current_capacity_ > max_capacity_) {
1362 current_capacity_ = max_capacity_;
1363 }
1364
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001365 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001366
1367 SetFootprintLimit(current_capacity_);
1368
1369 return true;
1370}
1371
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001372void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1373 Barrier barrier(0);
1374 size_t threads_running_checkpoint = 0;
1375 MarkCodeClosure closure(this, &barrier);
1376 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1377 // Now that we have run our checkpoint, move to a suspended state and wait
1378 // for other threads to run the checkpoint.
1379 ScopedThreadSuspension sts(self, kSuspended);
1380 if (threads_running_checkpoint != 0) {
1381 barrier.Increment(self, threads_running_checkpoint);
1382 }
1383}
1384
Nicolas Geoffray35122442016-03-02 12:05:30 +00001385bool JitCodeCache::ShouldDoFullCollection() {
1386 if (current_capacity_ == max_capacity_) {
1387 // Always do a full collection when the code cache is full.
1388 return true;
1389 } else if (current_capacity_ < kReservedCapacity) {
1390 // Always do partial collection when the code cache size is below the reserved
1391 // capacity.
1392 return false;
1393 } else if (last_collection_increased_code_cache_) {
1394 // This time do a full collection.
1395 return true;
1396 } else {
1397 // This time do a partial collection.
1398 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001399 }
1400}
1401
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001402void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001403 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001404 if (!garbage_collect_code_) {
1405 MutexLock mu(self, lock_);
1406 IncreaseCodeCacheCapacity();
1407 return;
1408 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001409
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001410 // Wait for an existing collection, or let everyone know we are starting one.
1411 {
1412 ScopedThreadSuspension sts(self, kSuspended);
1413 MutexLock mu(self, lock_);
1414 if (WaitForPotentialCollectionToComplete(self)) {
1415 return;
1416 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001417 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001418 live_bitmap_.reset(CodeCacheBitmap::Create(
1419 "code-cache-bitmap",
Orion Hodson1d3fd082018-09-28 09:38:35 +01001420 reinterpret_cast<uintptr_t>(exec_pages_.Begin()),
1421 reinterpret_cast<uintptr_t>(exec_pages_.Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001422 collection_in_progress_ = true;
1423 }
1424 }
1425
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001426 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001427 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001428 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001429
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001430 bool do_full_collection = false;
1431 {
1432 MutexLock mu(self, lock_);
1433 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001434 }
1435
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001436 VLOG(jit) << "Do "
1437 << (do_full_collection ? "full" : "partial")
1438 << " code cache collection, code="
1439 << PrettySize(CodeCacheSize())
1440 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001441
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001442 DoCollection(self, /* collect_profiling_info= */ do_full_collection);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001443
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001444 VLOG(jit) << "After code cache collection, code="
1445 << PrettySize(CodeCacheSize())
1446 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001447
1448 {
1449 MutexLock mu(self, lock_);
1450
1451 // Increase the code cache only when we do partial collections.
1452 // TODO: base this strategy on how full the code cache is?
1453 if (do_full_collection) {
1454 last_collection_increased_code_cache_ = false;
1455 } else {
1456 last_collection_increased_code_cache_ = true;
1457 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001458 }
1459
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001460 bool next_collection_will_be_full = ShouldDoFullCollection();
1461
1462 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001463 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001464 // Save the entry point of methods we have compiled, and update the entry
1465 // point of those methods to the interpreter. If the method is invoked, the
1466 // interpreter will update its entry point to the compiled code and call it.
1467 for (ProfilingInfo* info : profiling_infos_) {
1468 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1469 if (ContainsPc(entry_point)) {
1470 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001471 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001472 // class of the method. We may be concurrently running a GC which makes accessing
1473 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1474 // checked that the current entry point is JIT compiled code.
1475 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001476 }
1477 }
1478
1479 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001480
1481 // Change entry points of native methods back to the GenericJNI entrypoint.
1482 for (const auto& entry : jni_stubs_map_) {
1483 const JniStubData& data = entry.second;
1484 if (!data.IsCompiled()) {
1485 continue;
1486 }
1487 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1488 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1489 const OatQuickMethodHeader* method_header =
1490 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1491 for (ArtMethod* method : data.GetMethods()) {
1492 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1493 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1494 method->SetCounter(new_counter);
1495 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1496 }
1497 }
1498 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001499 }
1500 live_bitmap_.reset(nullptr);
1501 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001502 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001503 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001504 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001505}
1506
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001507void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001508 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001509 std::unordered_set<OatQuickMethodHeader*> method_headers;
1510 {
1511 MutexLock mu(self, lock_);
Calin Juravle016fcbe22018-05-03 19:47:35 -07001512 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001513 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001514 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1515 JniStubData* data = &it->second;
1516 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1517 ++it;
1518 } else {
1519 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1520 it = jni_stubs_map_.erase(it);
1521 }
1522 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001523 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1524 const void* code_ptr = it->first;
1525 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1526 if (GetLiveBitmap()->Test(allocation)) {
1527 ++it;
1528 } else {
Alex Light2d441b12018-06-08 15:33:21 -07001529 OatQuickMethodHeader* header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1530 method_headers.insert(header);
Mingyao Yang063fc772016-08-02 11:02:54 -07001531 it = method_code_map_.erase(it);
1532 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001533 }
1534 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001535 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001536}
1537
1538void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001539 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001540 {
1541 MutexLock mu(self, lock_);
1542 if (collect_profiling_info) {
1543 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1544 // Also remove the saved entry point from the ProfilingInfo objects.
1545 for (ProfilingInfo* info : profiling_infos_) {
1546 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001547 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001548 info->GetMethod()->SetProfilingInfo(nullptr);
1549 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001550
1551 if (info->GetSavedEntryPoint() != nullptr) {
1552 info->SetSavedEntryPoint(nullptr);
1553 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001554 // give it a chance to be hot again.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001555 ClearMethodCounter(info->GetMethod(), /*was_warm=*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001556 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001557 }
1558 } else if (kIsDebugBuild) {
1559 // Sanity check that the profiling infos do not have a dangling entry point.
1560 for (ProfilingInfo* info : profiling_infos_) {
1561 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001562 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001563 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001564
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001565 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1566 // an entry point is either:
1567 // - an osr compiled code, that will be removed if not in a thread call stack.
1568 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001569 for (const auto& entry : jni_stubs_map_) {
1570 const JniStubData& data = entry.second;
1571 const void* code_ptr = data.GetCode();
1572 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1573 for (ArtMethod* method : data.GetMethods()) {
1574 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1575 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1576 break;
1577 }
1578 }
1579 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001580 for (const auto& it : method_code_map_) {
1581 ArtMethod* method = it.second;
1582 const void* code_ptr = it.first;
1583 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1584 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1585 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1586 }
1587 }
1588
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001589 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001590 // on thread stacks).
1591 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001592 }
1593
1594 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001595 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001596
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001597 // At this point, mutator threads are still running, and entrypoints of methods can
1598 // change. We do know they cannot change to a code cache entry that is not marked,
1599 // therefore we can safely remove those entries.
1600 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001601
Nicolas Geoffray35122442016-03-02 12:05:30 +00001602 if (collect_profiling_info) {
1603 MutexLock mu(self, lock_);
1604 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001605 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001606 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001607 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001608 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1609 // that the compiled code would not get revived. As mutator threads run concurrently,
1610 // they may have revived the compiled code, and now we are in the situation where
1611 // a method has compiled code but no ProfilingInfo.
1612 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1613 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001614 if (ContainsPc(ptr) &&
1615 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001616 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001617 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001618 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001619 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001620 return true;
1621 }
1622 return false;
1623 });
1624 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001625 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001626 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001627}
1628
Nicolas Geoffray35122442016-03-02 12:05:30 +00001629bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001630 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001631 // Check that methods we have compiled do have a ProfilingInfo object. We would
1632 // have memory leaks of compiled code otherwise.
1633 for (const auto& it : method_code_map_) {
1634 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001635 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001636 const void* code_ptr = it.first;
1637 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1638 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1639 // If the code is not dead, then we have a problem. Note that this can even
1640 // happen just after a collection, as mutator threads are running in parallel
1641 // and could deoptimize an existing compiled code.
1642 return false;
1643 }
1644 }
1645 }
1646 return true;
1647}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001648
1649OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001650 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1651 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001652 // On Thumb-2, the pc is offset by one.
1653 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001654 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001655 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1656 return nullptr;
1657 }
1658
Vladimir Marko2196c652017-11-30 16:16:07 +00001659 if (!kIsDebugBuild) {
1660 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1661 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001662 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001663
Vladimir Marko2196c652017-11-30 16:16:07 +00001664 MutexLock mu(Thread::Current(), lock_);
1665 OatQuickMethodHeader* method_header = nullptr;
1666 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1667 if (method != nullptr && UNLIKELY(method->IsNative())) {
1668 auto it = jni_stubs_map_.find(JniStubKey(method));
1669 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1670 return nullptr;
1671 }
1672 const void* code_ptr = it->second.GetCode();
1673 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1674 if (!method_header->Contains(pc)) {
1675 return nullptr;
1676 }
1677 } else {
1678 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1679 if (it != method_code_map_.begin()) {
1680 --it;
1681 const void* code_ptr = it->first;
1682 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1683 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1684 found_method = it->second;
1685 }
1686 }
1687 if (method_header == nullptr && method == nullptr) {
1688 // Scan all compiled JNI stubs as well. This slow search is used only
1689 // for checks in debug build, for release builds the `method` is not null.
1690 for (auto&& entry : jni_stubs_map_) {
1691 const JniStubData& data = entry.second;
1692 if (data.IsCompiled() &&
1693 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1694 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1695 }
1696 }
1697 }
1698 if (method_header == nullptr) {
1699 return nullptr;
1700 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001701 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001702
1703 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001704 // When we are walking the stack to redefine classes and creating obsolete methods it is
1705 // possible that we might have updated the method_code_map by making this method obsolete in a
1706 // previous frame. Therefore we should just check that the non-obsolete version of this method
1707 // is the one we expect. We change to the non-obsolete versions in the error message since the
1708 // obsolete version of the method might not be fully initialized yet. This situation can only
1709 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001710 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001711 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001712 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001713 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001714 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001715 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001716 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001717 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001718}
1719
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001720OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1721 MutexLock mu(Thread::Current(), lock_);
1722 auto it = osr_code_map_.find(method);
1723 if (it == osr_code_map_.end()) {
1724 return nullptr;
1725 }
1726 return OatQuickMethodHeader::FromCodePointer(it->second);
1727}
1728
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001729ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1730 ArtMethod* method,
1731 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001732 bool retry_allocation)
1733 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1734 NO_THREAD_SAFETY_ANALYSIS {
1735 ProfilingInfo* info = nullptr;
1736 if (!retry_allocation) {
1737 // If we are allocating for the interpreter, just try to lock, to avoid
1738 // lock contention with the JIT.
1739 if (lock_.ExclusiveTryLock(self)) {
1740 info = AddProfilingInfoInternal(self, method, entries);
1741 lock_.ExclusiveUnlock(self);
1742 }
1743 } else {
1744 {
1745 MutexLock mu(self, lock_);
1746 info = AddProfilingInfoInternal(self, method, entries);
1747 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001748
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001749 if (info == nullptr) {
1750 GarbageCollectCache(self);
1751 MutexLock mu(self, lock_);
1752 info = AddProfilingInfoInternal(self, method, entries);
1753 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001754 }
1755 return info;
1756}
1757
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001758ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001759 ArtMethod* method,
1760 const std::vector<uint32_t>& entries) {
1761 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001762 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001763 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001764
1765 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001766 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001767 if (info != nullptr) {
1768 return info;
1769 }
1770
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001771 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001772 if (data == nullptr) {
1773 return nullptr;
1774 }
1775 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001776
1777 // Make sure other threads see the data in the profiling info object before the
1778 // store in the ArtMethod's ProfilingInfo pointer.
Orion Hodson27b96762018-03-13 16:06:57 +00001779 std::atomic_thread_fence(std::memory_order_release);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001780
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001781 method->SetProfilingInfo(info);
1782 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001783 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001784 return info;
1785}
1786
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001787// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1788// is already held.
1789void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
Orion Hodson1d3fd082018-09-28 09:38:35 +01001790 if (mspace == exec_mspace_) {
1791 DCHECK(exec_mspace_ != nullptr);
1792 const MemMap* const code_pages = GetUpdatableCodeMapping();
1793 void* result = code_pages->Begin() + exec_end_;
1794 exec_end_ += increment;
1795 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001796 } else {
1797 DCHECK_EQ(data_mspace_, mspace);
Orion Hodson1d3fd082018-09-28 09:38:35 +01001798 void* result = data_pages_.Begin() + data_end_;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001799 data_end_ += increment;
Orion Hodson1d3fd082018-09-28 09:38:35 +01001800 return result;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001801 }
1802}
1803
Calin Juravle99629622016-04-19 16:33:46 +01001804void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001805 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001806 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001807 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001808 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001809 for (const ProfilingInfo* info : profiling_infos_) {
1810 ArtMethod* method = info->GetMethod();
1811 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001812 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1813 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001814 // Skip dex files which are not profiled.
1815 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001816 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001817 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001818
1819 // If the method didn't reach the compilation threshold don't save the inline caches.
1820 // They might be incomplete and cause unnecessary deoptimizations.
1821 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1822 if (method->GetCounter() < jit_compile_threshold) {
1823 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001824 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001825 continue;
1826 }
1827
Calin Juravle940eb0c2017-01-30 19:30:44 -08001828 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001829 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001830 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001831 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001832 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001833 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1834 mirror::Class* cls = cache.classes_[k].Read();
1835 if (cls == nullptr) {
1836 break;
1837 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001838
Calin Juravle13439f02017-02-21 01:17:21 -08001839 // Check if the receiver is in the boot class path or if it's in the
1840 // same class loader as the caller. If not, skip it, as there is not
1841 // much we can do during AOT.
1842 if (!cls->IsBootStrapClassLoaded() &&
1843 caller->GetClassLoader() != cls->GetClassLoader()) {
1844 is_missing_types = true;
1845 continue;
1846 }
1847
Calin Juravle4ca70a32017-02-21 16:22:24 -08001848 const DexFile* class_dex_file = nullptr;
1849 dex::TypeIndex type_index;
1850
1851 if (cls->GetDexCache() == nullptr) {
1852 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001853 // Make a best effort to find the type index in the method's dex file.
1854 // We could search all open dex files but that might turn expensive
1855 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001856 class_dex_file = dex_file;
1857 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1858 } else {
1859 class_dex_file = &(cls->GetDexFile());
1860 type_index = cls->GetDexTypeIndex();
1861 }
1862 if (!type_index.IsValid()) {
1863 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001864 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001865 continue;
1866 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001867 if (ContainsElement(dex_base_locations,
1868 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001869 // Only consider classes from the same apk (including multidex).
1870 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001871 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001872 } else {
1873 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001874 }
1875 }
1876 if (!profile_classes.empty()) {
1877 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001878 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001879 }
1880 }
1881 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001882 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001883 }
1884}
1885
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001886bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1887 MutexLock mu(Thread::Current(), lock_);
1888 return osr_code_map_.find(method) != osr_code_map_.end();
1889}
1890
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001891bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1892 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001893 return false;
1894 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001895
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001896 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001897 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1898 return false;
1899 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001900
Vladimir Marko2196c652017-11-30 16:16:07 +00001901 if (UNLIKELY(method->IsNative())) {
1902 JniStubKey key(method);
1903 auto it = jni_stubs_map_.find(key);
1904 bool new_compilation = false;
1905 if (it == jni_stubs_map_.end()) {
1906 // Create a new entry to mark the stub as being compiled.
1907 it = jni_stubs_map_.Put(key, JniStubData{});
1908 new_compilation = true;
1909 }
1910 JniStubData* data = &it->second;
1911 data->AddMethod(method);
1912 if (data->IsCompiled()) {
1913 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1914 const void* entrypoint = method_header->GetEntryPoint();
1915 // Update also entrypoints of other methods held by the JniStubData.
1916 // We could simply update the entrypoint of `method` but if the last JIT GC has
1917 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1918 // as well change them back as this stub shall not be collected anyway and this
1919 // can avoid a few expensive GenericJNI calls.
1920 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1921 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001922 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1923 // `m` might be in the process of being deleted.
1924 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001925 }
1926 if (collection_in_progress_) {
1927 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1928 }
1929 }
1930 return new_compilation;
1931 } else {
1932 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1933 if (info == nullptr) {
1934 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1935 // Because the counter is not atomic, there are some rare cases where we may not hit the
1936 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001937 ClearMethodCounter(method, /*was_warm=*/ false);
Vladimir Marko2196c652017-11-30 16:16:07 +00001938 return false;
1939 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001940
Vladimir Marko2196c652017-11-30 16:16:07 +00001941 if (info->IsMethodBeingCompiled(osr)) {
1942 return false;
1943 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001944
Vladimir Marko2196c652017-11-30 16:16:07 +00001945 info->SetIsMethodBeingCompiled(true, osr);
1946 return true;
1947 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001948}
1949
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001950ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001951 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001952 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001953 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001954 if (!info->IncrementInlineUse()) {
1955 // Overflow of inlining uses, just bail.
1956 return nullptr;
1957 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001958 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001959 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001960}
1961
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001962void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001963 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001964 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001965 DCHECK(info != nullptr);
1966 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001967}
1968
Vladimir Marko2196c652017-11-30 16:16:07 +00001969void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1970 DCHECK_EQ(Thread::Current(), self);
1971 MutexLock mu(self, lock_);
1972 if (UNLIKELY(method->IsNative())) {
1973 auto it = jni_stubs_map_.find(JniStubKey(method));
1974 DCHECK(it != jni_stubs_map_.end());
1975 JniStubData* data = &it->second;
1976 DCHECK(ContainsElement(data->GetMethods(), method));
1977 if (UNLIKELY(!data->IsCompiled())) {
1978 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1979 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1980 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1981 } else {
1982 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1983 DCHECK(info->IsMethodBeingCompiled(osr));
1984 info->SetIsMethodBeingCompiled(false, osr);
1985 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001986}
1987
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001988size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1989 MutexLock mu(Thread::Current(), lock_);
1990 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1991}
1992
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001993void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1994 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001995 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001996 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Alex Light2d441b12018-06-08 15:33:21 -07001997 const void* method_entrypoint = method->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001998 if ((profiling_info != nullptr) &&
1999 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
Alex Light2d441b12018-06-08 15:33:21 -07002000 // When instrumentation is set, the actual entrypoint is the one in the profiling info.
2001 method_entrypoint = profiling_info->GetSavedEntryPoint();
Nicolas Geoffray35122442016-03-02 12:05:30 +00002002 // Prevent future uses of the compiled code.
2003 profiling_info->SetSavedEntryPoint(nullptr);
2004 }
2005
Alex Light2d441b12018-06-08 15:33:21 -07002006 // Clear the method counter if we are running jitted code since we might want to jit this again in
2007 // the future.
2008 if (method_entrypoint == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07002009 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07002010 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002011 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
2012 method, GetQuickToInterpreterBridge());
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002013 ClearMethodCounter(method, /*was_warm=*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00002014 } else {
2015 MutexLock mu(Thread::Current(), lock_);
2016 auto it = osr_code_map_.find(method);
2017 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
2018 // Remove the OSR method, to avoid using it again.
2019 osr_code_map_.erase(it);
2020 }
2021 }
2022}
2023
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002024uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
2025 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
2026 uint8_t* result = reinterpret_cast<uint8_t*>(
Orion Hodson1d3fd082018-09-28 09:38:35 +01002027 mspace_memalign(exec_mspace_, alignment, code_size));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002028 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
2029 // Ensure the header ends up at expected instruction alignment.
2030 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
2031 used_memory_for_code_ += mspace_usable_size(result);
2032 return result;
2033}
2034
Orion Hodsondbd05fe2017-08-10 11:41:35 +01002035void JitCodeCache::FreeCode(uint8_t* code) {
2036 used_memory_for_code_ -= mspace_usable_size(code);
Orion Hodson1d3fd082018-09-28 09:38:35 +01002037 mspace_free(exec_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00002038}
2039
2040uint8_t* JitCodeCache::AllocateData(size_t data_size) {
2041 void* result = mspace_malloc(data_mspace_, data_size);
2042 used_memory_for_data_ += mspace_usable_size(result);
2043 return reinterpret_cast<uint8_t*>(result);
2044}
2045
2046void JitCodeCache::FreeData(uint8_t* data) {
2047 used_memory_for_data_ -= mspace_usable_size(data);
2048 mspace_free(data_mspace_, data);
2049}
2050
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002051void JitCodeCache::Dump(std::ostream& os) {
2052 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00002053 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002054 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
2055 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00002056 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002057 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00002058 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002059 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
2060 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
2061 << "Total number of JIT compilations for on stack replacement: "
2062 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002063 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00002064 histogram_stack_map_memory_use_.PrintMemoryUse(os);
2065 histogram_code_memory_use_.PrintMemoryUse(os);
2066 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00002067}
2068
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002069} // namespace jit
2070} // namespace art