blob: 653fb87ca99540d8ef0eedbc3b69206a7c8acf62 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Andreas Gampe5629d2d2017-05-15 16:28:13 -070021#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070027#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "entrypoints/runtime_asm_entrypoints.h"
30#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010031#include "gc/scoped_gc_critical_section.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070032#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000033#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000034#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010035#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070038#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070039#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070041#include "stack.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010042#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080043
44namespace art {
45namespace jit {
46
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010047static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
48static constexpr int kProtData = PROT_READ | PROT_WRITE;
49static constexpr int kProtCode = PROT_READ | PROT_EXEC;
David Sehrd1dbb742017-07-17 11:20:38 -070050static constexpr int kProtReadOnly = PROT_READ;
51static constexpr int kProtNone = PROT_NONE;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010052
Nicolas Geoffray933330a2016-03-16 14:20:06 +000053static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
54static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
David Sehrd1dbb742017-07-17 11:20:38 -070055static constexpr size_t kMinMapSpacingPages = 1;
56static constexpr size_t kMaxMapSpacingPages = 128;
Nicolas Geoffray933330a2016-03-16 14:20:06 +000057
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010058#define CHECKED_MPROTECT(memory, size, prot) \
59 do { \
60 int rc = mprotect(memory, size, prot); \
61 if (UNLIKELY(rc != 0)) { \
62 errno = rc; \
63 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
64 } \
65 } while (false) \
66
David Sehrd1dbb742017-07-17 11:20:38 -070067static MemMap* SplitMemMap(MemMap* existing_map,
68 const char* name,
69 size_t split_offset,
70 int split_prot,
71 std::string* error_msg,
72 bool use_ashmem,
73 unique_fd* shmem_fd = nullptr) {
74 std::string error_str;
75 uint8_t* divider = existing_map->Begin() + split_offset;
76 MemMap* new_map = existing_map->RemapAtEnd(divider,
77 name,
78 split_prot,
79 MAP_SHARED,
80 &error_str,
81 use_ashmem,
82 shmem_fd);
83 if (new_map == nullptr) {
84 std::ostringstream oss;
85 oss << "Failed to create spacing for " << name << ": "
86 << error_str << " offset=" << split_offset;
87 *error_msg = oss.str();
88 return nullptr;
89 }
90 return new_map;
91}
92
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000093JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
94 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000095 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000096 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080097 ScopedTrace trace(__PRETTY_FUNCTION__);
David Sehrd1dbb742017-07-17 11:20:38 -070098 CHECK_GT(max_capacity, initial_capacity);
99 CHECK_GE(max_capacity - kMaxMapSpacingPages * kPageSize, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000100
David Sehrd1dbb742017-07-17 11:20:38 -0700101 // Generating debug information is for using the Linux perf tool on
102 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100103 // Also, target linux does not support ashmem.
104 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700105
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000106 // With 'perf', we want a 1-1 mapping between an address and a method.
107 bool garbage_collect_code = !generate_debug_info;
108
David Sehrd1dbb742017-07-17 11:20:38 -0700109 // We only use two mappings (separating rw from rx) if we are able to use ashmem.
110 // See the above comment for debug information and not using ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100111 bool use_two_mappings = use_ashmem;
David Sehrd1dbb742017-07-17 11:20:38 -0700112
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000113 // We need to have 32 bit offsets from method headers in code cache which point to things
114 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
115 // Ensure we're below 1 GB to be safe.
116 if (max_capacity > 1 * GB) {
117 std::ostringstream oss;
118 oss << "Maxium code cache capacity is limited to 1 GB, "
119 << PrettySize(max_capacity) << " is too big";
120 *error_msg = oss.str();
121 return nullptr;
122 }
123
Orion Hodson56fe32e2017-07-21 11:42:10 +0100124 // Align both capacities to page size, as that's the unit mspaces use.
125 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
126 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
127
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800128 std::string error_str;
129 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000130 // Map in low 4gb to simplify accessing root tables for x86_64.
131 // We could do PC-relative addressing to avoid this problem, but that
132 // would require reserving code and data area before submitting, which
133 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700134 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000135 "data-code-cache", nullptr,
136 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700137 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000138 /* low_4gb */ true,
139 /* reuse */ false,
140 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700141 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100142 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800143 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700144 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800145 *error_msg = oss.str();
146 return nullptr;
147 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148
David Sehrd1dbb742017-07-17 11:20:38 -0700149 // Create a region for JIT data and executable code. This will be
150 // laid out as:
151 //
152 // +----------------+ --------------------
Orion Hodson56fe32e2017-07-21 11:42:10 +0100153 // | code_sync_map_ | ^ code_sync_size ^
154 // | | v |
155 // +----------------+ -- |
156 // : : ^ |
David Sehrd1dbb742017-07-17 11:20:38 -0700157 // : post_code_map : | post_code_size |
158 // : [padding] : v |
159 // +----------------+ - |
160 // | | ^ |
Orion Hodson56fe32e2017-07-21 11:42:10 +0100161 // | code_map | | code_size | total_mapping_size
David Sehrd1dbb742017-07-17 11:20:38 -0700162 // | [JIT Code] | v |
Orion Hodson56fe32e2017-07-21 11:42:10 +0100163 // +----------------+ - |
David Sehrd1dbb742017-07-17 11:20:38 -0700164 // : : ^ |
165 // : pre_code_map : | pre_code_size |
166 // : [padding] : v |
167 // +----------------+ - |
168 // | | ^ |
169 // | data_map | | data_size |
170 // | [Jit Data] | v v
171 // +----------------+ --------------------
172 //
Orion Hodson56fe32e2017-07-21 11:42:10 +0100173 // The code_sync_map_ contains a page that we use flush CPU instruction
174 // pipelines (see FlushInstructionPipelines()).
175 //
David Sehrd1dbb742017-07-17 11:20:38 -0700176 // The padding regions - pre_code_map and post_code_map - exist to
177 // put some random distance between the writable JIT code mapping
178 // and the executable mapping. The padding is discarded at the end
179 // of this function.
Orion Hodson56fe32e2017-07-21 11:42:10 +0100180 //
181 size_t data_size = (max_capacity - kMaxMapSpacingPages * kPageSize) / 2;
David Sehrd1dbb742017-07-17 11:20:38 -0700182 size_t pre_code_size =
Orion Hodson56fe32e2017-07-21 11:42:10 +0100183 GetRandomNumber(kMinMapSpacingPages, kMaxMapSpacingPages - 1) * kPageSize;
184 size_t code_size = max_capacity - data_size - kMaxMapSpacingPages * kPageSize;
185 size_t code_sync_size = kPageSize;
186 size_t post_code_size = kMaxMapSpacingPages * kPageSize - pre_code_size - code_sync_size;
187 DCHECK_EQ(data_size, code_size);
188 DCHECK_EQ(pre_code_size + post_code_size + code_sync_size, kMaxMapSpacingPages * kPageSize);
189 DCHECK_EQ(data_size + pre_code_size + code_size + post_code_size + code_sync_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100190
David Sehrd1dbb742017-07-17 11:20:38 -0700191 // Create pre-code padding region after data region, discarded after
192 // code and data regions are set-up.
193 std::unique_ptr<MemMap> pre_code_map(SplitMemMap(data_map.get(),
194 "jit-code-cache-padding",
195 data_size,
196 kProtNone,
197 error_msg,
198 use_ashmem));
199 if (pre_code_map == nullptr) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 return nullptr;
201 }
David Sehrd1dbb742017-07-17 11:20:38 -0700202 DCHECK_EQ(data_map->Size(), data_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100203 DCHECK_EQ(pre_code_map->Size(), pre_code_size + code_size + post_code_size + code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700204
205 // Create code region.
206 unique_fd writable_code_fd;
207 std::unique_ptr<MemMap> code_map(SplitMemMap(pre_code_map.get(),
208 "jit-code-cache",
209 pre_code_size,
210 use_two_mappings ? kProtCode : kProtAll,
211 error_msg,
212 use_ashmem,
213 &writable_code_fd));
214 if (code_map == nullptr) {
215 return nullptr;
216 }
217 DCHECK_EQ(pre_code_map->Size(), pre_code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100218 DCHECK_EQ(code_map->Size(), code_size + post_code_size + code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700219
220 // Padding after code region, discarded after code and data regions
221 // are set-up.
222 std::unique_ptr<MemMap> post_code_map(SplitMemMap(code_map.get(),
223 "jit-code-cache-padding",
224 code_size,
225 kProtNone,
226 error_msg,
227 use_ashmem));
228 if (post_code_map == nullptr) {
229 return nullptr;
230 }
231 DCHECK_EQ(code_map->Size(), code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100232 DCHECK_EQ(post_code_map->Size(), post_code_size + code_sync_size);
233
234 std::unique_ptr<MemMap> code_sync_map(SplitMemMap(post_code_map.get(),
235 "jit-code-sync",
236 post_code_size,
237 kProtCode,
238 error_msg,
239 use_ashmem));
240 if (code_sync_map == nullptr) {
241 return nullptr;
242 }
David Sehrd1dbb742017-07-17 11:20:38 -0700243 DCHECK_EQ(post_code_map->Size(), post_code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100244 DCHECK_EQ(code_sync_map->Size(), code_sync_size);
David Sehrd1dbb742017-07-17 11:20:38 -0700245
246 std::unique_ptr<MemMap> writable_code_map;
247 if (use_two_mappings) {
248 // Allocate the R/W view.
249 writable_code_map.reset(MemMap::MapFile(code_size,
250 kProtData,
251 MAP_SHARED,
252 writable_code_fd.get(),
253 /* start */ 0,
254 /* low_4gb */ true,
255 "jit-writable-code",
256 &error_str));
257 if (writable_code_map == nullptr) {
258 std::ostringstream oss;
259 oss << "Failed to create writable code cache: " << error_str << " size=" << code_size;
260 *error_msg = oss.str();
261 return nullptr;
262 }
263 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000264 data_size = initial_capacity / 2;
265 code_size = initial_capacity - data_size;
266 DCHECK_EQ(code_size + data_size, initial_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700267 return new JitCodeCache(writable_code_map.release(),
268 code_map.release(),
269 data_map.release(),
Orion Hodson56fe32e2017-07-21 11:42:10 +0100270 code_sync_map.release(),
David Sehrd1dbb742017-07-17 11:20:38 -0700271 code_size,
272 data_size,
273 max_capacity,
274 garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800275}
276
David Sehrd1dbb742017-07-17 11:20:38 -0700277JitCodeCache::JitCodeCache(MemMap* writable_code_map,
278 MemMap* executable_code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000279 MemMap* data_map,
Orion Hodson56fe32e2017-07-21 11:42:10 +0100280 MemMap* code_sync_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000281 size_t initial_code_capacity,
282 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000283 size_t max_capacity,
284 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100285 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000286 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100287 collection_in_progress_(false),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000288 data_map_(data_map),
David Sehrd1dbb742017-07-17 11:20:38 -0700289 executable_code_map_(executable_code_map),
290 writable_code_map_(writable_code_map),
Orion Hodson56fe32e2017-07-21 11:42:10 +0100291 code_sync_map_(code_sync_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000292 max_capacity_(max_capacity),
293 current_capacity_(initial_code_capacity + initial_data_capacity),
294 code_end_(initial_code_capacity),
295 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000296 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000297 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000298 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000299 used_memory_for_data_(0),
300 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000301 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000302 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000303 number_of_collections_(0),
304 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
305 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000306 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
307 is_weak_access_enabled_(true),
308 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100309
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000310 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700311 MemMap* writable_map = GetWritableMemMap();
312 code_mspace_ = create_mspace_with_base(writable_map->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000313 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100314
315 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
316 PLOG(FATAL) << "create_mspace_with_base failed";
317 }
318
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000319 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100320
David Sehrd1dbb742017-07-17 11:20:38 -0700321 if (writable_code_map_ != nullptr) {
322 CHECKED_MPROTECT(writable_code_map_->Begin(), writable_code_map_->Size(), kProtReadOnly);
323 }
324 CHECKED_MPROTECT(executable_code_map_->Begin(), executable_code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100326
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000327 VLOG(jit) << "Created jit code cache: initial data size="
328 << PrettySize(initial_data_capacity)
329 << ", initial code size="
330 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800331}
332
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100333bool JitCodeCache::ContainsPc(const void* ptr) const {
David Sehrd1dbb742017-07-17 11:20:38 -0700334 return executable_code_map_->Begin() <= ptr && ptr < executable_code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800335}
336
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000337bool JitCodeCache::ContainsMethod(ArtMethod* method) {
338 MutexLock mu(Thread::Current(), lock_);
339 for (auto& it : method_code_map_) {
340 if (it.second == method) {
341 return true;
342 }
343 }
344 return false;
345}
346
David Sehrd1dbb742017-07-17 11:20:38 -0700347/* This method is only for CHECK/DCHECK that pointers are within to a region. */
348static bool IsAddressInMap(const void* addr,
349 const MemMap* mem_map,
350 const char* check_name) {
351 if (addr == nullptr || mem_map->HasAddress(addr)) {
352 return true;
353 }
354 LOG(ERROR) << "Is" << check_name << "Address " << addr
355 << " not in [" << reinterpret_cast<void*>(mem_map->Begin())
356 << ", " << reinterpret_cast<void*>(mem_map->Begin() + mem_map->Size()) << ")";
357 return false;
358}
359
360bool JitCodeCache::IsDataAddress(const void* raw_addr) const {
361 return IsAddressInMap(raw_addr, data_map_.get(), "Data");
362}
363
364bool JitCodeCache::IsExecutableAddress(const void* raw_addr) const {
365 return IsAddressInMap(raw_addr, executable_code_map_.get(), "Executable");
366}
367
368bool JitCodeCache::IsWritableAddress(const void* raw_addr) const {
369 return IsAddressInMap(raw_addr, GetWritableMemMap(), "Writable");
370}
371
372// Convert one address within the source map to the same offset within the destination map.
373static void* ConvertAddress(const void* source_address,
374 const MemMap* source_map,
375 const MemMap* destination_map) {
376 DCHECK(source_map->HasAddress(source_address)) << source_address;
377 ptrdiff_t offset = reinterpret_cast<const uint8_t*>(source_address) - source_map->Begin();
378 uintptr_t address = reinterpret_cast<uintptr_t>(destination_map->Begin()) + offset;
379 return reinterpret_cast<void*>(address);
380}
381
382template <typename T>
383T* JitCodeCache::ToExecutableAddress(T* writable_address) const {
384 CHECK(IsWritableAddress(writable_address));
385 if (writable_address == nullptr) {
386 return nullptr;
387 }
388 void* executable_address = ConvertAddress(writable_address,
389 GetWritableMemMap(),
390 executable_code_map_.get());
391 CHECK(IsExecutableAddress(executable_address));
392 return reinterpret_cast<T*>(executable_address);
393}
394
395void* JitCodeCache::ToWritableAddress(const void* executable_address) const {
396 CHECK(IsExecutableAddress(executable_address));
397 if (executable_address == nullptr) {
398 return nullptr;
399 }
400 void* writable_address = ConvertAddress(executable_address,
401 executable_code_map_.get(),
402 GetWritableMemMap());
403 CHECK(IsWritableAddress(writable_address));
404 return writable_address;
405}
406
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800407class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408 public:
Orion Hodson56fe32e2017-07-21 11:42:10 +0100409 explicit ScopedCodeCacheWrite(JitCodeCache* code_cache)
David Sehrd1dbb742017-07-17 11:20:38 -0700410 : ScopedTrace("ScopedCodeCacheWrite") {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800411 ScopedTrace trace("mprotect all");
David Sehrd1dbb742017-07-17 11:20:38 -0700412 int prot_to_start_writing = kProtAll;
413 if (code_cache->writable_code_map_ == nullptr) {
414 // If there is only one mapping, use the executable mapping and toggle between rwx and rx.
415 prot_to_start_writing = kProtAll;
416 prot_to_stop_writing_ = kProtCode;
417 } else {
418 // If there are two mappings, use the writable mapping and toggle between rw and r.
419 prot_to_start_writing = kProtData;
420 prot_to_stop_writing_ = kProtReadOnly;
421 }
422 writable_map_ = code_cache->GetWritableMemMap();
423 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
424 // one page.
Orion Hodson56fe32e2017-07-21 11:42:10 +0100425 size_ = writable_map_->Size();
David Sehrd1dbb742017-07-17 11:20:38 -0700426 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_start_writing);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800427 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100428 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800429 ScopedTrace trace("mprotect code");
David Sehrd1dbb742017-07-17 11:20:38 -0700430 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_stop_writing_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100431 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100432
David Sehrd1dbb742017-07-17 11:20:38 -0700433 private:
434 int prot_to_stop_writing_;
435 MemMap* writable_map_;
436 size_t size_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100437
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100438 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
439};
440
441uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100442 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000443 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700444 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000445 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100446 size_t frame_size_in_bytes,
447 size_t core_spill_mask,
448 size_t fp_spill_mask,
449 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000450 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000451 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700452 Handle<mirror::ObjectArray<mirror::Object>> roots,
453 bool has_should_deoptimize_flag,
454 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100455 uint8_t* result = CommitCodeInternal(self,
456 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000457 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700458 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000459 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100460 frame_size_in_bytes,
461 core_spill_mask,
462 fp_spill_mask,
463 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000464 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000465 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700466 roots,
467 has_should_deoptimize_flag,
468 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100469 if (result == nullptr) {
470 // Retry.
471 GarbageCollectCache(self);
472 result = CommitCodeInternal(self,
473 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000474 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700475 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000476 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100477 frame_size_in_bytes,
478 core_spill_mask,
479 fp_spill_mask,
480 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000481 code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000482 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700483 roots,
484 has_should_deoptimize_flag,
485 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100486 }
487 return result;
488}
489
490bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
491 bool in_collection = false;
492 while (collection_in_progress_) {
493 in_collection = true;
494 lock_cond_.Wait(self);
495 }
496 return in_collection;
497}
498
499static uintptr_t FromCodeToAllocation(const void* code) {
500 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
501 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
502}
503
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000504static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
505 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
506}
507
508static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
509 // The length of the table is stored just before the stack map (and therefore at the end of
510 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
511 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
512}
513
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800514static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
515 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
516 // pointer.
517 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
518}
519
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000520static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
521 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
522}
523
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000524static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
525 REQUIRES_SHARED(Locks::mutator_lock_) {
526 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800527 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000528 // Put all roots in `roots_data`.
529 for (uint32_t i = 0; i < length; ++i) {
530 ObjPtr<mirror::Object> object = roots->Get(i);
531 if (kIsDebugBuild) {
532 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000533 if (object->IsString()) {
534 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
535 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
536 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
537 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000538 }
539 gc_roots[i] = GcRoot<mirror::Object>(object);
540 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000541}
542
David Sehrd1dbb742017-07-17 11:20:38 -0700543uint8_t* JitCodeCache::GetRootTable(const void* code_ptr, uint32_t* number_of_roots) {
544 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000545 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Sehrd1dbb742017-07-17 11:20:38 -0700546 // GetOptimizedCodeInfoPtr uses offsets relative to the EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000547 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
548 uint32_t roots = GetNumberOfRoots(data);
549 if (number_of_roots != nullptr) {
550 *number_of_roots = roots;
551 }
552 return data - ComputeRootTableSize(roots);
553}
554
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100555// Use a sentinel for marking entries in the JIT table that have been cleared.
556// This helps diagnosing in case the compiled code tries to wrongly access such
557// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700558static mirror::Class* const weak_sentinel =
559 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100560
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000561// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100562static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
563 IsMarkedVisitor* visitor,
564 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000565 REQUIRES_SHARED(Locks::mutator_lock_) {
566 // This does not need a read barrier because this is called by GC.
567 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100568 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000569 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
570 // Look at the classloader of the class to know if it has been unloaded.
571 // This does not need a read barrier because this is called by GC.
572 mirror::Object* class_loader =
573 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
574 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
575 // The class loader is live, update the entry if the class has moved.
576 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
577 // Note that new_object can be null for CMS and newly allocated objects.
578 if (new_cls != nullptr && new_cls != cls) {
579 *root_ptr = GcRoot<mirror::Class>(new_cls);
580 }
581 } else {
582 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100583 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000584 }
585 }
586}
587
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000588void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
589 MutexLock mu(Thread::Current(), lock_);
590 for (const auto& entry : method_code_map_) {
David Sehrd1dbb742017-07-17 11:20:38 -0700591 // GetRootTable takes an EXECUTABLE address.
592 CHECK(IsExecutableAddress(entry.first));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000593 uint32_t number_of_roots = 0;
594 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
595 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
596 for (uint32_t i = 0; i < number_of_roots; ++i) {
597 // This does not need a read barrier because this is called by GC.
598 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100599 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000600 // entry got deleted in a previous sweep.
601 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
602 mirror::Object* new_object = visitor->IsMarked(object);
603 // We know the string is marked because it's a strongly-interned string that
604 // is always alive. The IsMarked implementation of the CMS collector returns
605 // null for newly allocated objects, but we know those haven't moved. Therefore,
606 // only update the entry if we get a different non-null string.
607 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
608 // out of the weak access/creation pause. b/32167580
609 if (new_object != nullptr && new_object != object) {
610 DCHECK(new_object->IsString());
611 roots[i] = GcRoot<mirror::Object>(new_object);
612 }
613 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100614 ProcessWeakClass(
615 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000616 }
617 }
618 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000619 // Walk over inline caches to clear entries containing unloaded classes.
620 for (ProfilingInfo* info : profiling_infos_) {
621 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
622 InlineCache* cache = &info->cache_[i];
623 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100624 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000625 }
626 }
627 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000628}
629
David Sehrd1dbb742017-07-17 11:20:38 -0700630void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
631 CHECK(IsExecutableAddress(code_ptr));
David Srbecky5cc349f2015-12-18 15:04:48 +0000632 // Notify native debugger that we are about to remove the code.
633 // It does nothing if we are not using native debugger.
634 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700635 // GetRootTable takes an EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000636 FreeData(GetRootTable(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700637 FreeRawCode(reinterpret_cast<uint8_t*>(FromCodeToAllocation(code_ptr)));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100638}
639
Mingyao Yang063fc772016-08-02 11:02:54 -0700640void JitCodeCache::FreeAllMethodHeaders(
641 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700642 // method_headers are expected to be in the executable region.
Mingyao Yang063fc772016-08-02 11:02:54 -0700643 {
644 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
645 Runtime::Current()->GetClassHierarchyAnalysis()
646 ->RemoveDependentsWithMethodHeaders(method_headers);
647 }
648
649 // We need to remove entries in method_headers from CHA dependencies
650 // first since once we do FreeCode() below, the memory can be reused
651 // so it's possible for the same method_header to start representing
652 // different compile code.
653 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -0700654 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700655 for (const OatQuickMethodHeader* method_header : method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700656 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700657 }
658}
659
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100660void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800661 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700662 // We use a set to first collect all method_headers whose code need to be
663 // removed. We need to free the underlying code after we remove CHA dependencies
664 // for entries in this set. And it's more efficient to iterate through
665 // the CHA dependency map just once with an unordered_set.
666 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000667 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700668 MutexLock mu(self, lock_);
669 // We do not check if a code cache GC is in progress, as this method comes
670 // with the classlinker_classes_lock_ held, and suspending ourselves could
671 // lead to a deadlock.
672 {
David Sehrd1dbb742017-07-17 11:20:38 -0700673 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700674 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
675 if (alloc.ContainsUnsafe(it->second)) {
David Sehrd1dbb742017-07-17 11:20:38 -0700676 CHECK(IsExecutableAddress(OatQuickMethodHeader::FromCodePointer(it->first)));
Mingyao Yang063fc772016-08-02 11:02:54 -0700677 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
678 it = method_code_map_.erase(it);
679 } else {
680 ++it;
681 }
682 }
683 }
684 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
685 if (alloc.ContainsUnsafe(it->first)) {
686 // Note that the code has already been pushed to method_headers in the loop
687 // above and is going to be removed in FreeCode() below.
688 it = osr_code_map_.erase(it);
689 } else {
690 ++it;
691 }
692 }
693 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
694 ProfilingInfo* info = *it;
695 if (alloc.ContainsUnsafe(info->GetMethod())) {
696 info->GetMethod()->SetProfilingInfo(nullptr);
697 FreeData(reinterpret_cast<uint8_t*>(info));
698 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000699 } else {
700 ++it;
701 }
702 }
703 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700704 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100705}
706
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000707bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
708 return kUseReadBarrier
709 ? self->GetWeakRefAccessEnabled()
710 : is_weak_access_enabled_.LoadSequentiallyConsistent();
711}
712
713void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
714 if (IsWeakAccessEnabled(self)) {
715 return;
716 }
717 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000718 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000719 while (!IsWeakAccessEnabled(self)) {
720 inline_cache_cond_.Wait(self);
721 }
722}
723
724void JitCodeCache::BroadcastForInlineCacheAccess() {
725 Thread* self = Thread::Current();
726 MutexLock mu(self, lock_);
727 inline_cache_cond_.Broadcast(self);
728}
729
730void JitCodeCache::AllowInlineCacheAccess() {
731 DCHECK(!kUseReadBarrier);
732 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
733 BroadcastForInlineCacheAccess();
734}
735
736void JitCodeCache::DisallowInlineCacheAccess() {
737 DCHECK(!kUseReadBarrier);
738 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
739}
740
741void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
742 Handle<mirror::ObjectArray<mirror::Class>> array) {
743 WaitUntilInlineCacheAccessible(Thread::Current());
744 // Note that we don't need to lock `lock_` here, the compiler calling
745 // this method has already ensured the inline cache will not be deleted.
746 for (size_t in_cache = 0, in_array = 0;
747 in_cache < InlineCache::kIndividualCacheSize;
748 ++in_cache) {
749 mirror::Class* object = ic.classes_[in_cache].Read();
750 if (object != nullptr) {
751 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000752 }
753 }
754}
755
Mathieu Chartierf044c222017-05-31 15:27:54 -0700756static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
757 if (was_warm) {
758 method->AddAccessFlags(kAccPreviouslyWarm);
759 }
760 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
761 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100762 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
763 // the warmup threshold is 1.
764 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
765 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700766}
767
Orion Hodson56fe32e2017-07-21 11:42:10 +0100768static void FlushInstructionPiplines(uint8_t* sync_page) {
769 // After updating the JIT code cache we need to force all CPUs to
770 // flush their instruction pipelines. In the absence of system call
771 // to do this explicitly, we can achieve this indirectly by toggling
772 // permissions on an executable page. This should send an IPI to
773 // each core to update the TLB entry with the interrupt raised on
774 // each core causing the instruction pipeline to be flushed.
775 CHECKED_MPROTECT(sync_page, kPageSize, kProtAll);
776 // Ensure the sync_page is present otherwise a TLB update may not be
777 // necessary.
778 sync_page[0] = 0;
779 CHECKED_MPROTECT(sync_page, kPageSize, kProtCode);
780}
781
Orion Hodson3ecac072017-07-20 15:28:44 +0100782#ifdef __aarch64__
783
784static void FlushJitCodeCacheRange(uint8_t* code_ptr,
785 uint8_t* writable_ptr ATTRIBUTE_UNUSED,
786 size_t code_size) {
787 // Cache maintenance instructions can cause permission faults when a
788 // page is not present (e.g. swapped out or not backed). These
789 // faults should be handled by the kernel, but a bug in some Linux
790 // kernels may surface these permission faults to user-land which
791 // does not currently deal with them (b/63885946). To work around
792 // this, we read a value from each page to fault it in before
793 // attempting to perform cache maintenance operations.
794 //
795 // For reference, this behavior is caused by this commit:
796 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
797
798 // The cache-line size could be probed for from the CPU, but
799 // assuming a safe lower bound is safe for CPUs that have different
800 // cache-line sizes for big and little cores.
801 static const uintptr_t kSafeCacheLineSize = 32;
802
803 // Ensure stores are present in data cache.
804 __asm __volatile("dsb sy");
805
806 uintptr_t addr = RoundDown(reinterpret_cast<uintptr_t>(code_ptr), kSafeCacheLineSize);
807 const uintptr_t limit_addr = RoundUp(reinterpret_cast<uintptr_t>(code_ptr) + code_size,
808 kSafeCacheLineSize);
809 volatile uint8_t mutant;
810 while (addr < limit_addr) {
811 // Read from the cache-line to minimize the chance that a cache
812 // maintenance instruction causes a fault (see kernel bug comment
813 // above).
814 mutant = *reinterpret_cast<const uint8_t*>(addr);
815
816 // Invalidating the data cache line is only strictly necessary
817 // when the JIT code cache has two mappings (the default). We know
818 // this cache line is clean so this is just invalidating it (using
819 // "dc ivac" would be preferable, but is privileged).
820 __asm volatile("dc cvau, %0" :: "r"(addr));
821
822 // Invalidate the instruction cache line to force instructions in
823 // range to be re-fetched following update.
824 __asm volatile("ic ivau, %0" :: "r"(addr));
825
826 addr += kSafeCacheLineSize;
827 }
828
829 // Drain data and instruction buffers.
830 __asm __volatile("dsb sy");
831 __asm __volatile("isb sy");
832}
833
834#else // __aarch64
835
836static void FlushJitCodeCacheRange(uint8_t* code_ptr,
837 uint8_t* writable_ptr,
838 size_t code_size) {
839 if (writable_ptr != code_ptr) {
840 // When there are two mappings of the JIT code cache, RX and
841 // RW, flush the RW version first as we've just dirtied the
842 // cache lines with new code. Flushing the RX version first
843 // can cause a permission fault as the those addresses are not
844 // writable, but can appear dirty in the cache. There is a lot
845 // of potential subtlety here depending on how the cache is
846 // indexed and tagged.
847 //
848 // Flushing the RX version after the RW version is just
849 // invalidating cachelines in the instruction cache. This is
850 // necessary as the instruction cache will often have a
851 // different set of cache lines present and because the JIT
852 // code cache can start a new function at any boundary within
853 // a cache-line.
854 FlushDataCache(reinterpret_cast<char*>(writable_ptr),
855 reinterpret_cast<char*>(writable_ptr + code_size));
856 }
857 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
858 reinterpret_cast<char*>(code_ptr + code_size));
859}
860
861#endif // __aarch64
862
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100863uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
864 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000865 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700866 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000867 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100868 size_t frame_size_in_bytes,
869 size_t core_spill_mask,
870 size_t fp_spill_mask,
871 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000872 size_t code_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000873 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700874 Handle<mirror::ObjectArray<mirror::Object>> roots,
875 bool has_should_deoptimize_flag,
876 const ArenaSet<ArtMethod*>&
877 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000878 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100879 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
880 // Ensure the header ends up at expected instruction alignment.
881 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
882 size_t total_size = header_size + code_size;
883
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100884 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100885 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000886 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100887 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000888 ScopedThreadSuspension sts(self, kSuspended);
889 MutexLock mu(self, lock_);
890 WaitForPotentialCollectionToComplete(self);
891 {
David Sehrd1dbb742017-07-17 11:20:38 -0700892 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000893 memory = AllocateCode(total_size);
894 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000895 return nullptr;
896 }
David Sehrd1dbb742017-07-17 11:20:38 -0700897 uint8_t* writable_ptr = memory + header_size;
898 code_ptr = ToExecutableAddress(writable_ptr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000899
David Sehrd1dbb742017-07-17 11:20:38 -0700900 std::copy(code, code + code_size, writable_ptr);
901 OatQuickMethodHeader* writable_method_header =
902 OatQuickMethodHeader::FromCodePointer(writable_ptr);
903 // We need to be able to write the OatQuickMethodHeader, so we use writable_method_header.
904 // Otherwise, the offsets encoded in OatQuickMethodHeader are used relative to an executable
905 // address, so we use code_ptr.
906 new (writable_method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000907 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700908 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000909 frame_size_in_bytes,
910 core_spill_mask,
911 fp_spill_mask,
912 code_size);
Orion Hodson3ecac072017-07-20 15:28:44 +0100913
914 FlushJitCodeCacheRange(code_ptr, writable_ptr, code_size);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100915 FlushInstructionPiplines(code_sync_map_->Begin());
Orion Hodson43ce5f82017-07-19 10:34:27 +0100916
Mingyao Yang063fc772016-08-02 11:02:54 -0700917 DCHECK(!Runtime::Current()->IsAotCompiler());
918 if (has_should_deoptimize_flag) {
David Sehrd1dbb742017-07-17 11:20:38 -0700919 writable_method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700920 }
David Sehrd1dbb742017-07-17 11:20:38 -0700921 // All the pointers exported from the cache are executable addresses.
922 method_header = ToExecutableAddress(writable_method_header);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100923 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100924
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000925 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100926 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000927 // We need to update the entry point in the runnable state for the instrumentation.
928 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700929 // Need cha_lock_ for checking all single-implementation flags and register
930 // dependencies.
931 MutexLock cha_mu(self, *Locks::cha_lock_);
932 bool single_impl_still_valid = true;
933 for (ArtMethod* single_impl : cha_single_implementation_list) {
934 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700935 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
936 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700937 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700938 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700939 break;
940 }
941 }
942
943 // Discard the code if any single-implementation assumptions are now invalid.
944 if (!single_impl_still_valid) {
945 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
946 return nullptr;
947 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000948 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800949 << "Should not be using cha on debuggable apps/runs!";
950
Mingyao Yang063fc772016-08-02 11:02:54 -0700951 for (ArtMethod* single_impl : cha_single_implementation_list) {
952 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
953 single_impl, method, method_header);
954 }
955
956 // The following needs to be guarded by cha_lock_ also. Otherwise it's
957 // possible that the compiled code is considered invalidated by some class linking,
958 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000959 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000960 // Fill the root table before updating the entry point.
David Sehrd1dbb742017-07-17 11:20:38 -0700961 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000962 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100963 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000964 FillRootTable(roots_data, roots);
Orion Hodson56fe32e2017-07-21 11:42:10 +0100965
966 // Ensure the updates to the root table are visible with a store fence.
967 QuasiAtomic::ThreadFenceSequentiallyConsistent();
968
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100969 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000970 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000971 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000972 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100973 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000974 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
975 method, method_header->GetEntryPoint());
976 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000977 if (collection_in_progress_) {
978 // We need to update the live bitmap if there is a GC to ensure it sees this new
979 // code.
980 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
981 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000982 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000983 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100984 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700985 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000986 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
987 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
988 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700989 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
990 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000991 histogram_code_memory_use_.AddValue(code_size);
992 if (code_size > kCodeSizeLogThreshold) {
993 LOG(INFO) << "JIT allocated "
994 << PrettySize(code_size)
995 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700996 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000997 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000998 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100999
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001000 return reinterpret_cast<uint8_t*>(method_header);
1001}
1002
1003size_t JitCodeCache::CodeCacheSize() {
1004 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001005 return CodeCacheSizeLocked();
1006}
1007
Orion Hodsoneced6922017-06-01 10:54:28 +01001008bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
1009 MutexLock mu(Thread::Current(), lock_);
1010 if (method->IsNative()) {
1011 return false;
1012 }
1013
1014 bool in_cache = false;
1015 {
David Sehrd1dbb742017-07-17 11:20:38 -07001016 ScopedCodeCacheWrite ccw(this);
Orion Hodsoneced6922017-06-01 10:54:28 +01001017 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
1018 if (code_iter->second == method) {
1019 if (release_memory) {
David Sehrd1dbb742017-07-17 11:20:38 -07001020 FreeCodeAndData(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +01001021 }
1022 code_iter = method_code_map_.erase(code_iter);
1023 in_cache = true;
1024 continue;
1025 }
1026 ++code_iter;
1027 }
1028 }
1029
1030 bool osr = false;
1031 auto code_map = osr_code_map_.find(method);
1032 if (code_map != osr_code_map_.end()) {
1033 osr_code_map_.erase(code_map);
1034 osr = true;
1035 }
1036
1037 if (!in_cache) {
1038 return false;
1039 }
1040
1041 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1042 if (info != nullptr) {
1043 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1044 DCHECK(profile != profiling_infos_.end());
1045 profiling_infos_.erase(profile);
1046 }
1047 method->SetProfilingInfo(nullptr);
1048 method->ClearCounter();
1049 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1050 method, GetQuickToInterpreterBridge());
1051 VLOG(jit)
1052 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1053 << ArtMethod::PrettyMethod(method) << "@" << method
1054 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1055 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1056 return true;
1057}
1058
Alex Lightdba61482016-12-21 08:20:29 -08001059// This notifies the code cache that the given method has been redefined and that it should remove
1060// any cached information it has on the method. All threads must be suspended before calling this
1061// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1062void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1063 MutexLock mu(Thread::Current(), lock_);
1064 if (method->IsNative()) {
1065 return;
1066 }
1067 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1068 if (info != nullptr) {
1069 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1070 DCHECK(profile != profiling_infos_.end());
1071 profiling_infos_.erase(profile);
1072 }
1073 method->SetProfilingInfo(nullptr);
David Sehrd1dbb742017-07-17 11:20:38 -07001074 ScopedCodeCacheWrite ccw(this);
Andreas Gampe39e67382017-05-15 19:26:38 -07001075 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -08001076 if (code_iter->second == method) {
David Sehrd1dbb742017-07-17 11:20:38 -07001077 FreeCodeAndData(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -07001078 code_iter = method_code_map_.erase(code_iter);
1079 continue;
Alex Lightdba61482016-12-21 08:20:29 -08001080 }
Andreas Gampe39e67382017-05-15 19:26:38 -07001081 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -08001082 }
1083 auto code_map = osr_code_map_.find(method);
1084 if (code_map != osr_code_map_.end()) {
1085 osr_code_map_.erase(code_map);
1086 }
1087}
1088
1089// This invalidates old_method. Once this function returns one can no longer use old_method to
1090// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1091// class redefinition.
1092// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1093// shouldn't be used since it is no longer logically in the jit code cache.
1094// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1095void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +00001096 // Native methods have no profiling info and need no special handling from the JIT code cache.
1097 if (old_method->IsNative()) {
1098 return;
1099 }
Alex Lightdba61482016-12-21 08:20:29 -08001100 MutexLock mu(Thread::Current(), lock_);
1101 // Update ProfilingInfo to the new one and remove it from the old_method.
1102 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1103 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1104 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1105 old_method->SetProfilingInfo(nullptr);
1106 // Since the JIT should be paused and all threads suspended by the time this is called these
1107 // checks should always pass.
1108 DCHECK(!info->IsInUseByCompiler());
1109 new_method->SetProfilingInfo(info);
1110 info->method_ = new_method;
1111 }
1112 // Update method_code_map_ to point to the new method.
1113 for (auto& it : method_code_map_) {
1114 if (it.second == old_method) {
1115 it.second = new_method;
1116 }
1117 }
1118 // Update osr_code_map_ to point to the new method.
1119 auto code_map = osr_code_map_.find(old_method);
1120 if (code_map != osr_code_map_.end()) {
1121 osr_code_map_.Put(new_method, code_map->second);
1122 osr_code_map_.erase(old_method);
1123 }
1124}
1125
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001126size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001127 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001128}
1129
1130size_t JitCodeCache::DataCacheSize() {
1131 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001132 return DataCacheSizeLocked();
1133}
1134
1135size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001136 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001137}
1138
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001139void JitCodeCache::ClearData(Thread* self,
1140 uint8_t* stack_map_data,
1141 uint8_t* roots_data) {
1142 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
David Sehrd1dbb742017-07-17 11:20:38 -07001143 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001144 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001145 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001146}
1147
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001148size_t JitCodeCache::ReserveData(Thread* self,
1149 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001150 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001151 size_t number_of_roots,
1152 ArtMethod* method,
1153 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001154 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001155 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001156 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001157 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001158 uint8_t* result = nullptr;
1159
1160 {
1161 ScopedThreadSuspension sts(self, kSuspended);
1162 MutexLock mu(self, lock_);
1163 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001164 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001165 }
1166
1167 if (result == nullptr) {
1168 // Retry.
1169 GarbageCollectCache(self);
1170 ScopedThreadSuspension sts(self, kSuspended);
1171 MutexLock mu(self, lock_);
1172 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001173 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001174 }
1175
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001176 MutexLock mu(self, lock_);
1177 histogram_stack_map_memory_use_.AddValue(size);
1178 if (size > kStackMapSizeLogThreshold) {
1179 LOG(INFO) << "JIT allocated "
1180 << PrettySize(size)
1181 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001182 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001183 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001184 if (result != nullptr) {
1185 *roots_data = result;
1186 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001187 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001188 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001189 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001190 } else {
1191 *roots_data = nullptr;
1192 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001193 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001194 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001195 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001196}
1197
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001198class MarkCodeVisitor FINAL : public StackVisitor {
1199 public:
1200 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1201 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1202 code_cache_(code_cache_in),
1203 bitmap_(code_cache_->GetLiveBitmap()) {}
1204
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001205 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001206 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1207 if (method_header == nullptr) {
1208 return true;
1209 }
1210 const void* code = method_header->GetCode();
1211 if (code_cache_->ContainsPc(code)) {
1212 // Use the atomic set version, as multiple threads are executing this code.
1213 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1214 }
1215 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001216 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001217
1218 private:
1219 JitCodeCache* const code_cache_;
1220 CodeCacheBitmap* const bitmap_;
1221};
1222
1223class MarkCodeClosure FINAL : public Closure {
1224 public:
1225 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1226 : code_cache_(code_cache), barrier_(barrier) {}
1227
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001228 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001229 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001230 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1231 MarkCodeVisitor visitor(thread, code_cache_);
1232 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001233 if (kIsDebugBuild) {
1234 // The stack walking code queries the side instrumentation stack if it
1235 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1236 // must have been seen. We sanity check this below.
1237 for (const instrumentation::InstrumentationStackFrame& frame
1238 : *thread->GetInstrumentationStack()) {
1239 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1240 // its stack frame, it is not the method owning return_pc_. We just pass null to
1241 // LookupMethodHeader: the method is only checked against in debug builds.
1242 OatQuickMethodHeader* method_header =
1243 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
1244 if (method_header != nullptr) {
1245 const void* code = method_header->GetCode();
1246 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1247 }
1248 }
1249 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001250 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001251 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001252
1253 private:
1254 JitCodeCache* const code_cache_;
1255 Barrier* const barrier_;
1256};
1257
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001258void JitCodeCache::NotifyCollectionDone(Thread* self) {
1259 collection_in_progress_ = false;
1260 lock_cond_.Broadcast(self);
1261}
1262
1263void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1264 size_t per_space_footprint = new_footprint / 2;
David Sehrd1dbb742017-07-17 11:20:38 -07001265 CHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001266 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1267 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1268 {
David Sehrd1dbb742017-07-17 11:20:38 -07001269 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001270 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1271 }
1272}
1273
1274bool JitCodeCache::IncreaseCodeCacheCapacity() {
1275 if (current_capacity_ == max_capacity_) {
1276 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001277 }
1278
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001279 // Double the capacity if we're below 1MB, or increase it by 1MB if
1280 // we're above.
1281 if (current_capacity_ < 1 * MB) {
1282 current_capacity_ *= 2;
1283 } else {
1284 current_capacity_ += 1 * MB;
1285 }
1286 if (current_capacity_ > max_capacity_) {
1287 current_capacity_ = max_capacity_;
1288 }
1289
1290 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1291 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
1292 }
1293
1294 SetFootprintLimit(current_capacity_);
1295
1296 return true;
1297}
1298
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001299void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1300 Barrier barrier(0);
1301 size_t threads_running_checkpoint = 0;
1302 MarkCodeClosure closure(this, &barrier);
1303 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1304 // Now that we have run our checkpoint, move to a suspended state and wait
1305 // for other threads to run the checkpoint.
1306 ScopedThreadSuspension sts(self, kSuspended);
1307 if (threads_running_checkpoint != 0) {
1308 barrier.Increment(self, threads_running_checkpoint);
1309 }
1310}
1311
Nicolas Geoffray35122442016-03-02 12:05:30 +00001312bool JitCodeCache::ShouldDoFullCollection() {
1313 if (current_capacity_ == max_capacity_) {
1314 // Always do a full collection when the code cache is full.
1315 return true;
1316 } else if (current_capacity_ < kReservedCapacity) {
1317 // Always do partial collection when the code cache size is below the reserved
1318 // capacity.
1319 return false;
1320 } else if (last_collection_increased_code_cache_) {
1321 // This time do a full collection.
1322 return true;
1323 } else {
1324 // This time do a partial collection.
1325 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001326 }
1327}
1328
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001329void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001330 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001331 if (!garbage_collect_code_) {
1332 MutexLock mu(self, lock_);
1333 IncreaseCodeCacheCapacity();
1334 return;
1335 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001336
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001337 // Wait for an existing collection, or let everyone know we are starting one.
1338 {
1339 ScopedThreadSuspension sts(self, kSuspended);
1340 MutexLock mu(self, lock_);
1341 if (WaitForPotentialCollectionToComplete(self)) {
1342 return;
1343 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001344 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001345 live_bitmap_.reset(CodeCacheBitmap::Create(
1346 "code-cache-bitmap",
David Sehrd1dbb742017-07-17 11:20:38 -07001347 reinterpret_cast<uintptr_t>(executable_code_map_->Begin()),
1348 reinterpret_cast<uintptr_t>(executable_code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001349 collection_in_progress_ = true;
1350 }
1351 }
1352
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001353 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001354 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001355 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001356
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001357 bool do_full_collection = false;
1358 {
1359 MutexLock mu(self, lock_);
1360 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001361 }
1362
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001363 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1364 LOG(INFO) << "Do "
1365 << (do_full_collection ? "full" : "partial")
1366 << " code cache collection, code="
1367 << PrettySize(CodeCacheSize())
1368 << ", data=" << PrettySize(DataCacheSize());
1369 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001370
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001371 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1372
1373 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1374 LOG(INFO) << "After code cache collection, code="
1375 << PrettySize(CodeCacheSize())
1376 << ", data=" << PrettySize(DataCacheSize());
1377 }
1378
1379 {
1380 MutexLock mu(self, lock_);
1381
1382 // Increase the code cache only when we do partial collections.
1383 // TODO: base this strategy on how full the code cache is?
1384 if (do_full_collection) {
1385 last_collection_increased_code_cache_ = false;
1386 } else {
1387 last_collection_increased_code_cache_ = true;
1388 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001389 }
1390
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001391 bool next_collection_will_be_full = ShouldDoFullCollection();
1392
1393 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001394 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001395 // Save the entry point of methods we have compiled, and update the entry
1396 // point of those methods to the interpreter. If the method is invoked, the
1397 // interpreter will update its entry point to the compiled code and call it.
1398 for (ProfilingInfo* info : profiling_infos_) {
1399 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1400 if (ContainsPc(entry_point)) {
1401 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001402 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1403 // class of the method. We may be concurrently running a GC which makes accessing
1404 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1405 // checked that the current entry point is JIT compiled code.
1406 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001407 }
1408 }
1409
1410 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1411 }
1412 live_bitmap_.reset(nullptr);
1413 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001414 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001415 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001416 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001417}
1418
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001419void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001420 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001421 std::unordered_set<OatQuickMethodHeader*> method_headers;
1422 {
1423 MutexLock mu(self, lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001424 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001425 // Iterate over all compiled code and remove entries that are not marked.
1426 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1427 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001428 CHECK(IsExecutableAddress(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001429 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1430 if (GetLiveBitmap()->Test(allocation)) {
1431 ++it;
1432 } else {
David Sehrd1dbb742017-07-17 11:20:38 -07001433 CHECK(IsExecutableAddress(it->first));
Mingyao Yang063fc772016-08-02 11:02:54 -07001434 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1435 it = method_code_map_.erase(it);
1436 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001437 }
1438 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001439 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001440}
1441
1442void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001443 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001444 {
1445 MutexLock mu(self, lock_);
1446 if (collect_profiling_info) {
1447 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1448 // Also remove the saved entry point from the ProfilingInfo objects.
1449 for (ProfilingInfo* info : profiling_infos_) {
1450 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001451 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001452 info->GetMethod()->SetProfilingInfo(nullptr);
1453 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001454
1455 if (info->GetSavedEntryPoint() != nullptr) {
1456 info->SetSavedEntryPoint(nullptr);
1457 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001458 // give it a chance to be hot again.
1459 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001460 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001461 }
1462 } else if (kIsDebugBuild) {
1463 // Sanity check that the profiling infos do not have a dangling entry point.
1464 for (ProfilingInfo* info : profiling_infos_) {
1465 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001466 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001467 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001468
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001469 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1470 // an entry point is either:
1471 // - an osr compiled code, that will be removed if not in a thread call stack.
1472 // - discarded compiled code, that will be removed if not in a thread call stack.
1473 for (const auto& it : method_code_map_) {
1474 ArtMethod* method = it.second;
1475 const void* code_ptr = it.first;
David Sehrd1dbb742017-07-17 11:20:38 -07001476 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001477 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1478 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1479 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1480 }
1481 }
1482
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001483 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001484 // on thread stacks).
1485 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001486 }
1487
1488 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001489 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001490
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001491 // At this point, mutator threads are still running, and entrypoints of methods can
1492 // change. We do know they cannot change to a code cache entry that is not marked,
1493 // therefore we can safely remove those entries.
1494 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001495
Nicolas Geoffray35122442016-03-02 12:05:30 +00001496 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001497 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001498 MutexLock mu(self, lock_);
1499 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001500 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001501 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
David Sehrd1dbb742017-07-17 11:20:38 -07001502 CHECK(IsDataAddress(info));
Nicolas Geoffray35122442016-03-02 12:05:30 +00001503 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001504 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1505 // that the compiled code would not get revived. As mutator threads run concurrently,
1506 // they may have revived the compiled code, and now we are in the situation where
1507 // a method has compiled code but no ProfilingInfo.
1508 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1509 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001510 if (ContainsPc(ptr) &&
1511 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001512 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001513 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001514 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001515 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001516 return true;
1517 }
1518 return false;
1519 });
1520 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001521 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001522 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001523}
1524
Nicolas Geoffray35122442016-03-02 12:05:30 +00001525bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001526 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001527 // Check that methods we have compiled do have a ProfilingInfo object. We would
1528 // have memory leaks of compiled code otherwise.
1529 for (const auto& it : method_code_map_) {
1530 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001531 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001532 const void* code_ptr = it.first;
1533 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1534 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1535 // If the code is not dead, then we have a problem. Note that this can even
1536 // happen just after a collection, as mutator threads are running in parallel
1537 // and could deoptimize an existing compiled code.
1538 return false;
1539 }
1540 }
1541 }
1542 return true;
1543}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001544
1545OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1546 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1547 if (kRuntimeISA == kArm) {
1548 // On Thumb-2, the pc is offset by one.
1549 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001550 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001551 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1552 return nullptr;
1553 }
1554
1555 MutexLock mu(Thread::Current(), lock_);
1556 if (method_code_map_.empty()) {
1557 return nullptr;
1558 }
1559 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1560 --it;
1561
1562 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001563 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001564 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1565 if (!method_header->Contains(pc)) {
1566 return nullptr;
1567 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001568 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001569 // When we are walking the stack to redefine classes and creating obsolete methods it is
1570 // possible that we might have updated the method_code_map by making this method obsolete in a
1571 // previous frame. Therefore we should just check that the non-obsolete version of this method
1572 // is the one we expect. We change to the non-obsolete versions in the error message since the
1573 // obsolete version of the method might not be fully initialized yet. This situation can only
1574 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1575 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1576 // information.)
1577 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1578 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1579 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001580 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001581 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001582 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001583}
1584
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001585OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1586 MutexLock mu(Thread::Current(), lock_);
1587 auto it = osr_code_map_.find(method);
1588 if (it == osr_code_map_.end()) {
1589 return nullptr;
1590 }
1591 return OatQuickMethodHeader::FromCodePointer(it->second);
1592}
1593
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001594ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1595 ArtMethod* method,
1596 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001597 bool retry_allocation)
1598 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1599 NO_THREAD_SAFETY_ANALYSIS {
1600 ProfilingInfo* info = nullptr;
1601 if (!retry_allocation) {
1602 // If we are allocating for the interpreter, just try to lock, to avoid
1603 // lock contention with the JIT.
1604 if (lock_.ExclusiveTryLock(self)) {
1605 info = AddProfilingInfoInternal(self, method, entries);
1606 lock_.ExclusiveUnlock(self);
1607 }
1608 } else {
1609 {
1610 MutexLock mu(self, lock_);
1611 info = AddProfilingInfoInternal(self, method, entries);
1612 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001613
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001614 if (info == nullptr) {
1615 GarbageCollectCache(self);
1616 MutexLock mu(self, lock_);
1617 info = AddProfilingInfoInternal(self, method, entries);
1618 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001619 }
1620 return info;
1621}
1622
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001623ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001624 ArtMethod* method,
1625 const std::vector<uint32_t>& entries) {
1626 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001627 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001628 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001629
1630 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001631 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001632 if (info != nullptr) {
1633 return info;
1634 }
1635
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001636 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001637 if (data == nullptr) {
1638 return nullptr;
1639 }
1640 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001641
1642 // Make sure other threads see the data in the profiling info object before the
1643 // store in the ArtMethod's ProfilingInfo pointer.
1644 QuasiAtomic::ThreadFenceRelease();
1645
David Sehrd1dbb742017-07-17 11:20:38 -07001646 CHECK(IsDataAddress(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001647 method->SetProfilingInfo(info);
1648 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001649 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001650 return info;
1651}
1652
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001653// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1654// is already held.
1655void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1656 if (code_mspace_ == mspace) {
1657 size_t result = code_end_;
1658 code_end_ += increment;
David Sehrd1dbb742017-07-17 11:20:38 -07001659 MemMap* writable_map = GetWritableMemMap();
1660 return reinterpret_cast<void*>(result + writable_map->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001661 } else {
1662 DCHECK_EQ(data_mspace_, mspace);
1663 size_t result = data_end_;
1664 data_end_ += increment;
1665 return reinterpret_cast<void*>(result + data_map_->Begin());
1666 }
1667}
1668
Calin Juravle99629622016-04-19 16:33:46 +01001669void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001670 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001671 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001672 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001673 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001674 for (const ProfilingInfo* info : profiling_infos_) {
1675 ArtMethod* method = info->GetMethod();
1676 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001677 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1678 // Skip dex files which are not profiled.
1679 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001680 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001681 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001682
1683 // If the method didn't reach the compilation threshold don't save the inline caches.
1684 // They might be incomplete and cause unnecessary deoptimizations.
1685 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1686 if (method->GetCounter() < jit_compile_threshold) {
1687 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001688 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001689 continue;
1690 }
1691
Calin Juravle940eb0c2017-01-30 19:30:44 -08001692 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001693 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001694 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001695 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001696 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001697 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1698 mirror::Class* cls = cache.classes_[k].Read();
1699 if (cls == nullptr) {
1700 break;
1701 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001702
Calin Juravle13439f02017-02-21 01:17:21 -08001703 // Check if the receiver is in the boot class path or if it's in the
1704 // same class loader as the caller. If not, skip it, as there is not
1705 // much we can do during AOT.
1706 if (!cls->IsBootStrapClassLoaded() &&
1707 caller->GetClassLoader() != cls->GetClassLoader()) {
1708 is_missing_types = true;
1709 continue;
1710 }
1711
Calin Juravle4ca70a32017-02-21 16:22:24 -08001712 const DexFile* class_dex_file = nullptr;
1713 dex::TypeIndex type_index;
1714
1715 if (cls->GetDexCache() == nullptr) {
1716 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001717 // Make a best effort to find the type index in the method's dex file.
1718 // We could search all open dex files but that might turn expensive
1719 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001720 class_dex_file = dex_file;
1721 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1722 } else {
1723 class_dex_file = &(cls->GetDexFile());
1724 type_index = cls->GetDexTypeIndex();
1725 }
1726 if (!type_index.IsValid()) {
1727 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001728 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001729 continue;
1730 }
1731 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001732 // Only consider classes from the same apk (including multidex).
1733 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001734 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001735 } else {
1736 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001737 }
1738 }
1739 if (!profile_classes.empty()) {
1740 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001741 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001742 }
1743 }
1744 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001745 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001746 }
1747}
1748
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001749uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1750 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001751}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001752
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001753bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1754 MutexLock mu(Thread::Current(), lock_);
1755 return osr_code_map_.find(method) != osr_code_map_.end();
1756}
1757
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001758bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1759 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001760 return false;
1761 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001762
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001763 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001764 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1765 return false;
1766 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001767
Andreas Gampe542451c2016-07-26 09:02:02 -07001768 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001769 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001770 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001771 // Because the counter is not atomic, there are some rare cases where we may not hit the
1772 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001773 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001774 return false;
1775 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001776
buzbee454b3b62016-04-07 14:42:47 -07001777 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001778 return false;
1779 }
1780
buzbee454b3b62016-04-07 14:42:47 -07001781 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001782 return true;
1783}
1784
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001785ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001786 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001787 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001788 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001789 if (!info->IncrementInlineUse()) {
1790 // Overflow of inlining uses, just bail.
1791 return nullptr;
1792 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001793 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001794 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001795}
1796
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001797void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001798 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001799 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001800 DCHECK(info != nullptr);
1801 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001802}
1803
buzbee454b3b62016-04-07 14:42:47 -07001804void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001805 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001806 DCHECK(info->IsMethodBeingCompiled(osr));
1807 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001808}
1809
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001810size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1811 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001812 CHECK(IsExecutableAddress(ptr));
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001813 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1814}
1815
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001816void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1817 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001818 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001819 if ((profiling_info != nullptr) &&
1820 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1821 // Prevent future uses of the compiled code.
1822 profiling_info->SetSavedEntryPoint(nullptr);
1823 }
1824
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001825 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001826 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001827 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001828 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1829 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001830 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001831 } else {
1832 MutexLock mu(Thread::Current(), lock_);
1833 auto it = osr_code_map_.find(method);
1834 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1835 // Remove the OSR method, to avoid using it again.
1836 osr_code_map_.erase(it);
1837 }
1838 }
1839}
1840
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001841uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1842 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1843 uint8_t* result = reinterpret_cast<uint8_t*>(
1844 mspace_memalign(code_mspace_, alignment, code_size));
1845 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1846 // Ensure the header ends up at expected instruction alignment.
1847 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
David Sehrd1dbb742017-07-17 11:20:38 -07001848 CHECK(IsWritableAddress(result));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001849 used_memory_for_code_ += mspace_usable_size(result);
1850 return result;
1851}
1852
David Sehrd1dbb742017-07-17 11:20:38 -07001853void JitCodeCache::FreeRawCode(void* code) {
1854 CHECK(IsExecutableAddress(code));
1855 void* writable_code = ToWritableAddress(code);
1856 used_memory_for_code_ -= mspace_usable_size(writable_code);
1857 mspace_free(code_mspace_, writable_code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001858}
1859
1860uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1861 void* result = mspace_malloc(data_mspace_, data_size);
David Sehrd1dbb742017-07-17 11:20:38 -07001862 CHECK(IsDataAddress(reinterpret_cast<uint8_t*>(result)));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001863 used_memory_for_data_ += mspace_usable_size(result);
1864 return reinterpret_cast<uint8_t*>(result);
1865}
1866
1867void JitCodeCache::FreeData(uint8_t* data) {
David Sehrd1dbb742017-07-17 11:20:38 -07001868 CHECK(IsDataAddress(data));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001869 used_memory_for_data_ -= mspace_usable_size(data);
1870 mspace_free(data_mspace_, data);
1871}
1872
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001873void JitCodeCache::Dump(std::ostream& os) {
1874 MutexLock mu(Thread::Current(), lock_);
1875 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1876 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1877 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1878 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1879 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1880 << "Total number of JIT compilations for on stack replacement: "
1881 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001882 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001883 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1884 histogram_code_memory_use_.PrintMemoryUse(os);
1885 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001886}
1887
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001888} // namespace jit
1889} // namespace art