blob: 3bee560cc25b613e7ee509e694dbf76a49cdc1b2 [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
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800124 std::string error_str;
125 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000126 // Map in low 4gb to simplify accessing root tables for x86_64.
127 // We could do PC-relative addressing to avoid this problem, but that
128 // would require reserving code and data area before submitting, which
129 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700130 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000131 "data-code-cache", nullptr,
132 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700133 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000134 /* low_4gb */ true,
135 /* reuse */ false,
136 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700137 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800139 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700140 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800141 *error_msg = oss.str();
142 return nullptr;
143 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100144
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000145 // Align both capacities to page size, as that's the unit mspaces use.
146 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
147 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
148
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 // +----------------+ --------------------
153 // : : ^ ^
154 // : post_code_map : | post_code_size |
155 // : [padding] : v |
156 // +----------------+ - |
157 // | | ^ |
158 // | code_map | | code_size |
159 // | [JIT Code] | v |
160 // +----------------+ - | total_mapping_size
161 // : : ^ |
162 // : pre_code_map : | pre_code_size |
163 // : [padding] : v |
164 // +----------------+ - |
165 // | | ^ |
166 // | data_map | | data_size |
167 // | [Jit Data] | v v
168 // +----------------+ --------------------
169 //
170 // The padding regions - pre_code_map and post_code_map - exist to
171 // put some random distance between the writable JIT code mapping
172 // and the executable mapping. The padding is discarded at the end
173 // of this function.
174 size_t total_mapping_size = kMaxMapSpacingPages * kPageSize;
175 size_t data_size = RoundUp((max_capacity - total_mapping_size) / 2, kPageSize);
176 size_t pre_code_size =
177 GetRandomNumber(kMinMapSpacingPages, kMaxMapSpacingPages) * kPageSize;
178 size_t code_size = max_capacity - total_mapping_size - data_size;
179 size_t post_code_size = total_mapping_size - pre_code_size;
180 DCHECK_EQ(code_size + data_size + total_mapping_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100181
David Sehrd1dbb742017-07-17 11:20:38 -0700182 // Create pre-code padding region after data region, discarded after
183 // code and data regions are set-up.
184 std::unique_ptr<MemMap> pre_code_map(SplitMemMap(data_map.get(),
185 "jit-code-cache-padding",
186 data_size,
187 kProtNone,
188 error_msg,
189 use_ashmem));
190 if (pre_code_map == nullptr) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100191 return nullptr;
192 }
David Sehrd1dbb742017-07-17 11:20:38 -0700193 DCHECK_EQ(data_map->Size(), data_size);
194 DCHECK_EQ(pre_code_map->Size(), pre_code_size + code_size + post_code_size);
195
196 // Create code region.
197 unique_fd writable_code_fd;
198 std::unique_ptr<MemMap> code_map(SplitMemMap(pre_code_map.get(),
199 "jit-code-cache",
200 pre_code_size,
201 use_two_mappings ? kProtCode : kProtAll,
202 error_msg,
203 use_ashmem,
204 &writable_code_fd));
205 if (code_map == nullptr) {
206 return nullptr;
207 }
208 DCHECK_EQ(pre_code_map->Size(), pre_code_size);
209 DCHECK_EQ(code_map->Size(), code_size + post_code_size);
210
211 // Padding after code region, discarded after code and data regions
212 // are set-up.
213 std::unique_ptr<MemMap> post_code_map(SplitMemMap(code_map.get(),
214 "jit-code-cache-padding",
215 code_size,
216 kProtNone,
217 error_msg,
218 use_ashmem));
219 if (post_code_map == nullptr) {
220 return nullptr;
221 }
222 DCHECK_EQ(code_map->Size(), code_size);
223 DCHECK_EQ(post_code_map->Size(), post_code_size);
224
225 std::unique_ptr<MemMap> writable_code_map;
226 if (use_two_mappings) {
227 // Allocate the R/W view.
228 writable_code_map.reset(MemMap::MapFile(code_size,
229 kProtData,
230 MAP_SHARED,
231 writable_code_fd.get(),
232 /* start */ 0,
233 /* low_4gb */ true,
234 "jit-writable-code",
235 &error_str));
236 if (writable_code_map == nullptr) {
237 std::ostringstream oss;
238 oss << "Failed to create writable code cache: " << error_str << " size=" << code_size;
239 *error_msg = oss.str();
240 return nullptr;
241 }
242 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000243 data_size = initial_capacity / 2;
244 code_size = initial_capacity - data_size;
245 DCHECK_EQ(code_size + data_size, initial_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700246 return new JitCodeCache(writable_code_map.release(),
247 code_map.release(),
248 data_map.release(),
249 code_size,
250 data_size,
251 max_capacity,
252 garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800253}
254
David Sehrd1dbb742017-07-17 11:20:38 -0700255JitCodeCache::JitCodeCache(MemMap* writable_code_map,
256 MemMap* executable_code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000257 MemMap* data_map,
258 size_t initial_code_capacity,
259 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000260 size_t max_capacity,
261 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100262 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000263 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100264 collection_in_progress_(false),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000265 data_map_(data_map),
David Sehrd1dbb742017-07-17 11:20:38 -0700266 executable_code_map_(executable_code_map),
267 writable_code_map_(writable_code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000268 max_capacity_(max_capacity),
269 current_capacity_(initial_code_capacity + initial_data_capacity),
270 code_end_(initial_code_capacity),
271 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000272 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000273 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000274 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000275 used_memory_for_data_(0),
276 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000277 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000278 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000279 number_of_collections_(0),
280 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
281 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000282 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
283 is_weak_access_enabled_(true),
284 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100285
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000286 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
David Sehrd1dbb742017-07-17 11:20:38 -0700287 MemMap* writable_map = GetWritableMemMap();
288 code_mspace_ = create_mspace_with_base(writable_map->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000289 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100290
291 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
292 PLOG(FATAL) << "create_mspace_with_base failed";
293 }
294
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000295 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100296
David Sehrd1dbb742017-07-17 11:20:38 -0700297 if (writable_code_map_ != nullptr) {
298 CHECKED_MPROTECT(writable_code_map_->Begin(), writable_code_map_->Size(), kProtReadOnly);
299 }
300 CHECKED_MPROTECT(executable_code_map_->Begin(), executable_code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100301 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100302
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000303 VLOG(jit) << "Created jit code cache: initial data size="
304 << PrettySize(initial_data_capacity)
305 << ", initial code size="
306 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800307}
308
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100309bool JitCodeCache::ContainsPc(const void* ptr) const {
David Sehrd1dbb742017-07-17 11:20:38 -0700310 return executable_code_map_->Begin() <= ptr && ptr < executable_code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800311}
312
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000313bool JitCodeCache::ContainsMethod(ArtMethod* method) {
314 MutexLock mu(Thread::Current(), lock_);
315 for (auto& it : method_code_map_) {
316 if (it.second == method) {
317 return true;
318 }
319 }
320 return false;
321}
322
David Sehrd1dbb742017-07-17 11:20:38 -0700323/* This method is only for CHECK/DCHECK that pointers are within to a region. */
324static bool IsAddressInMap(const void* addr,
325 const MemMap* mem_map,
326 const char* check_name) {
327 if (addr == nullptr || mem_map->HasAddress(addr)) {
328 return true;
329 }
330 LOG(ERROR) << "Is" << check_name << "Address " << addr
331 << " not in [" << reinterpret_cast<void*>(mem_map->Begin())
332 << ", " << reinterpret_cast<void*>(mem_map->Begin() + mem_map->Size()) << ")";
333 return false;
334}
335
336bool JitCodeCache::IsDataAddress(const void* raw_addr) const {
337 return IsAddressInMap(raw_addr, data_map_.get(), "Data");
338}
339
340bool JitCodeCache::IsExecutableAddress(const void* raw_addr) const {
341 return IsAddressInMap(raw_addr, executable_code_map_.get(), "Executable");
342}
343
344bool JitCodeCache::IsWritableAddress(const void* raw_addr) const {
345 return IsAddressInMap(raw_addr, GetWritableMemMap(), "Writable");
346}
347
348// Convert one address within the source map to the same offset within the destination map.
349static void* ConvertAddress(const void* source_address,
350 const MemMap* source_map,
351 const MemMap* destination_map) {
352 DCHECK(source_map->HasAddress(source_address)) << source_address;
353 ptrdiff_t offset = reinterpret_cast<const uint8_t*>(source_address) - source_map->Begin();
354 uintptr_t address = reinterpret_cast<uintptr_t>(destination_map->Begin()) + offset;
355 return reinterpret_cast<void*>(address);
356}
357
358template <typename T>
359T* JitCodeCache::ToExecutableAddress(T* writable_address) const {
360 CHECK(IsWritableAddress(writable_address));
361 if (writable_address == nullptr) {
362 return nullptr;
363 }
364 void* executable_address = ConvertAddress(writable_address,
365 GetWritableMemMap(),
366 executable_code_map_.get());
367 CHECK(IsExecutableAddress(executable_address));
368 return reinterpret_cast<T*>(executable_address);
369}
370
371void* JitCodeCache::ToWritableAddress(const void* executable_address) const {
372 CHECK(IsExecutableAddress(executable_address));
373 if (executable_address == nullptr) {
374 return nullptr;
375 }
376 void* writable_address = ConvertAddress(executable_address,
377 executable_code_map_.get(),
378 GetWritableMemMap());
379 CHECK(IsWritableAddress(writable_address));
380 return writable_address;
381}
382
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800383class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100384 public:
David Sehrd1dbb742017-07-17 11:20:38 -0700385 explicit ScopedCodeCacheWrite(JitCodeCache* code_cache, bool only_for_tlb_shootdown = false)
386 : ScopedTrace("ScopedCodeCacheWrite") {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800387 ScopedTrace trace("mprotect all");
David Sehrd1dbb742017-07-17 11:20:38 -0700388 int prot_to_start_writing = kProtAll;
389 if (code_cache->writable_code_map_ == nullptr) {
390 // If there is only one mapping, use the executable mapping and toggle between rwx and rx.
391 prot_to_start_writing = kProtAll;
392 prot_to_stop_writing_ = kProtCode;
393 } else {
394 // If there are two mappings, use the writable mapping and toggle between rw and r.
395 prot_to_start_writing = kProtData;
396 prot_to_stop_writing_ = kProtReadOnly;
397 }
398 writable_map_ = code_cache->GetWritableMemMap();
399 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
400 // one page.
401 size_ = only_for_tlb_shootdown ? kPageSize : writable_map_->Size();
402 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_start_writing);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800403 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100404 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800405 ScopedTrace trace("mprotect code");
David Sehrd1dbb742017-07-17 11:20:38 -0700406 CHECKED_MPROTECT(writable_map_->Begin(), size_, prot_to_stop_writing_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100407 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100408
David Sehrd1dbb742017-07-17 11:20:38 -0700409 private:
410 int prot_to_stop_writing_;
411 MemMap* writable_map_;
412 size_t size_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100413
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100414 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
415};
416
417uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100418 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000419 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700420 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000421 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100422 size_t frame_size_in_bytes,
423 size_t core_spill_mask,
424 size_t fp_spill_mask,
425 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000426 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000427 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000428 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700429 Handle<mirror::ObjectArray<mirror::Object>> roots,
430 bool has_should_deoptimize_flag,
431 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100432 uint8_t* result = CommitCodeInternal(self,
433 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000434 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700435 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000436 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100437 frame_size_in_bytes,
438 core_spill_mask,
439 fp_spill_mask,
440 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000441 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000442 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000443 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700444 roots,
445 has_should_deoptimize_flag,
446 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100447 if (result == nullptr) {
448 // Retry.
449 GarbageCollectCache(self);
450 result = CommitCodeInternal(self,
451 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000452 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700453 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000454 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100455 frame_size_in_bytes,
456 core_spill_mask,
457 fp_spill_mask,
458 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000459 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000460 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000461 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700462 roots,
463 has_should_deoptimize_flag,
464 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100465 }
466 return result;
467}
468
469bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
470 bool in_collection = false;
471 while (collection_in_progress_) {
472 in_collection = true;
473 lock_cond_.Wait(self);
474 }
475 return in_collection;
476}
477
478static uintptr_t FromCodeToAllocation(const void* code) {
479 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
480 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
481}
482
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000483static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
484 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
485}
486
487static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
488 // The length of the table is stored just before the stack map (and therefore at the end of
489 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
490 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
491}
492
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800493static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
494 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
495 // pointer.
496 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
497}
498
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000499static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
500 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
501}
502
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000503static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
504 REQUIRES_SHARED(Locks::mutator_lock_) {
505 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800506 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000507 // Put all roots in `roots_data`.
508 for (uint32_t i = 0; i < length; ++i) {
509 ObjPtr<mirror::Object> object = roots->Get(i);
510 if (kIsDebugBuild) {
511 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000512 if (object->IsString()) {
513 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
514 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
515 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
516 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000517 }
518 gc_roots[i] = GcRoot<mirror::Object>(object);
519 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000520}
521
David Sehrd1dbb742017-07-17 11:20:38 -0700522uint8_t* JitCodeCache::GetRootTable(const void* code_ptr, uint32_t* number_of_roots) {
523 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000524 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Sehrd1dbb742017-07-17 11:20:38 -0700525 // GetOptimizedCodeInfoPtr uses offsets relative to the EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000526 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
527 uint32_t roots = GetNumberOfRoots(data);
528 if (number_of_roots != nullptr) {
529 *number_of_roots = roots;
530 }
531 return data - ComputeRootTableSize(roots);
532}
533
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100534// Use a sentinel for marking entries in the JIT table that have been cleared.
535// This helps diagnosing in case the compiled code tries to wrongly access such
536// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700537static mirror::Class* const weak_sentinel =
538 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100539
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000540// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100541static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
542 IsMarkedVisitor* visitor,
543 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000544 REQUIRES_SHARED(Locks::mutator_lock_) {
545 // This does not need a read barrier because this is called by GC.
546 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100547 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000548 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
549 // Look at the classloader of the class to know if it has been unloaded.
550 // This does not need a read barrier because this is called by GC.
551 mirror::Object* class_loader =
552 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
553 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
554 // The class loader is live, update the entry if the class has moved.
555 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
556 // Note that new_object can be null for CMS and newly allocated objects.
557 if (new_cls != nullptr && new_cls != cls) {
558 *root_ptr = GcRoot<mirror::Class>(new_cls);
559 }
560 } else {
561 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100562 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000563 }
564 }
565}
566
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000567void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
568 MutexLock mu(Thread::Current(), lock_);
569 for (const auto& entry : method_code_map_) {
David Sehrd1dbb742017-07-17 11:20:38 -0700570 // GetRootTable takes an EXECUTABLE address.
571 CHECK(IsExecutableAddress(entry.first));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000572 uint32_t number_of_roots = 0;
573 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
574 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
575 for (uint32_t i = 0; i < number_of_roots; ++i) {
576 // This does not need a read barrier because this is called by GC.
577 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100578 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000579 // entry got deleted in a previous sweep.
580 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
581 mirror::Object* new_object = visitor->IsMarked(object);
582 // We know the string is marked because it's a strongly-interned string that
583 // is always alive. The IsMarked implementation of the CMS collector returns
584 // null for newly allocated objects, but we know those haven't moved. Therefore,
585 // only update the entry if we get a different non-null string.
586 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
587 // out of the weak access/creation pause. b/32167580
588 if (new_object != nullptr && new_object != object) {
589 DCHECK(new_object->IsString());
590 roots[i] = GcRoot<mirror::Object>(new_object);
591 }
592 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100593 ProcessWeakClass(
594 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000595 }
596 }
597 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000598 // Walk over inline caches to clear entries containing unloaded classes.
599 for (ProfilingInfo* info : profiling_infos_) {
600 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
601 InlineCache* cache = &info->cache_[i];
602 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100603 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000604 }
605 }
606 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000607}
608
David Sehrd1dbb742017-07-17 11:20:38 -0700609void JitCodeCache::FreeCodeAndData(const void* code_ptr) {
610 CHECK(IsExecutableAddress(code_ptr));
David Srbecky5cc349f2015-12-18 15:04:48 +0000611 // Notify native debugger that we are about to remove the code.
612 // It does nothing if we are not using native debugger.
613 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700614 // GetRootTable takes an EXECUTABLE address.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000615 FreeData(GetRootTable(code_ptr));
David Sehrd1dbb742017-07-17 11:20:38 -0700616 FreeRawCode(reinterpret_cast<uint8_t*>(FromCodeToAllocation(code_ptr)));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100617}
618
Mingyao Yang063fc772016-08-02 11:02:54 -0700619void JitCodeCache::FreeAllMethodHeaders(
620 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700621 // method_headers are expected to be in the executable region.
Mingyao Yang063fc772016-08-02 11:02:54 -0700622 {
623 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
624 Runtime::Current()->GetClassHierarchyAnalysis()
625 ->RemoveDependentsWithMethodHeaders(method_headers);
626 }
627
628 // We need to remove entries in method_headers from CHA dependencies
629 // first since once we do FreeCode() below, the memory can be reused
630 // so it's possible for the same method_header to start representing
631 // different compile code.
632 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -0700633 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700634 for (const OatQuickMethodHeader* method_header : method_headers) {
David Sehrd1dbb742017-07-17 11:20:38 -0700635 FreeCodeAndData(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700636 }
637}
638
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100639void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800640 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700641 // We use a set to first collect all method_headers whose code need to be
642 // removed. We need to free the underlying code after we remove CHA dependencies
643 // for entries in this set. And it's more efficient to iterate through
644 // the CHA dependency map just once with an unordered_set.
645 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000646 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700647 MutexLock mu(self, lock_);
648 // We do not check if a code cache GC is in progress, as this method comes
649 // with the classlinker_classes_lock_ held, and suspending ourselves could
650 // lead to a deadlock.
651 {
David Sehrd1dbb742017-07-17 11:20:38 -0700652 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -0700653 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
654 if (alloc.ContainsUnsafe(it->second)) {
David Sehrd1dbb742017-07-17 11:20:38 -0700655 CHECK(IsExecutableAddress(OatQuickMethodHeader::FromCodePointer(it->first)));
Mingyao Yang063fc772016-08-02 11:02:54 -0700656 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
657 it = method_code_map_.erase(it);
658 } else {
659 ++it;
660 }
661 }
662 }
663 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
664 if (alloc.ContainsUnsafe(it->first)) {
665 // Note that the code has already been pushed to method_headers in the loop
666 // above and is going to be removed in FreeCode() below.
667 it = osr_code_map_.erase(it);
668 } else {
669 ++it;
670 }
671 }
672 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
673 ProfilingInfo* info = *it;
674 if (alloc.ContainsUnsafe(info->GetMethod())) {
675 info->GetMethod()->SetProfilingInfo(nullptr);
676 FreeData(reinterpret_cast<uint8_t*>(info));
677 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000678 } else {
679 ++it;
680 }
681 }
682 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700683 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100684}
685
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000686bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
687 return kUseReadBarrier
688 ? self->GetWeakRefAccessEnabled()
689 : is_weak_access_enabled_.LoadSequentiallyConsistent();
690}
691
692void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
693 if (IsWeakAccessEnabled(self)) {
694 return;
695 }
696 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000697 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000698 while (!IsWeakAccessEnabled(self)) {
699 inline_cache_cond_.Wait(self);
700 }
701}
702
703void JitCodeCache::BroadcastForInlineCacheAccess() {
704 Thread* self = Thread::Current();
705 MutexLock mu(self, lock_);
706 inline_cache_cond_.Broadcast(self);
707}
708
709void JitCodeCache::AllowInlineCacheAccess() {
710 DCHECK(!kUseReadBarrier);
711 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
712 BroadcastForInlineCacheAccess();
713}
714
715void JitCodeCache::DisallowInlineCacheAccess() {
716 DCHECK(!kUseReadBarrier);
717 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
718}
719
720void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
721 Handle<mirror::ObjectArray<mirror::Class>> array) {
722 WaitUntilInlineCacheAccessible(Thread::Current());
723 // Note that we don't need to lock `lock_` here, the compiler calling
724 // this method has already ensured the inline cache will not be deleted.
725 for (size_t in_cache = 0, in_array = 0;
726 in_cache < InlineCache::kIndividualCacheSize;
727 ++in_cache) {
728 mirror::Class* object = ic.classes_[in_cache].Read();
729 if (object != nullptr) {
730 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000731 }
732 }
733}
734
Mathieu Chartierf044c222017-05-31 15:27:54 -0700735static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
736 if (was_warm) {
737 method->AddAccessFlags(kAccPreviouslyWarm);
738 }
739 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
740 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100741 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
742 // the warmup threshold is 1.
743 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
744 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700745}
746
Orion Hodson3ecac072017-07-20 15:28:44 +0100747#ifdef __aarch64__
748
749static void FlushJitCodeCacheRange(uint8_t* code_ptr,
Orion Hodson17272ab2017-07-21 14:32:52 +0100750 uint8_t* writable_ptr,
Orion Hodson3ecac072017-07-20 15:28:44 +0100751 size_t code_size) {
752 // Cache maintenance instructions can cause permission faults when a
753 // page is not present (e.g. swapped out or not backed). These
754 // faults should be handled by the kernel, but a bug in some Linux
755 // kernels may surface these permission faults to user-land which
756 // does not currently deal with them (b/63885946). To work around
757 // this, we read a value from each page to fault it in before
758 // attempting to perform cache maintenance operations.
759 //
760 // For reference, this behavior is caused by this commit:
761 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
762
763 // The cache-line size could be probed for from the CPU, but
764 // assuming a safe lower bound is safe for CPUs that have different
765 // cache-line sizes for big and little cores.
766 static const uintptr_t kSafeCacheLineSize = 32;
767
Orion Hodson17272ab2017-07-21 14:32:52 +0100768 // Ensure stores are present in L1 data cache.
769 __asm __volatile("dsb ish" ::: "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100770
Orion Hodson3ecac072017-07-20 15:28:44 +0100771 volatile uint8_t mutant;
Orion Hodson17272ab2017-07-21 14:32:52 +0100772
773 // Push dirty cache-lines out to the point of unification (PoU). The
774 // point of unification is the first point in the cache/memory
775 // hierarchy where the instruction cache and data cache have the
776 // same view of memory. The PoU is where an instruction fetch will
777 // fetch the new code generated by the JIT.
778 //
779 // See: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0024a/ch11s04.html
780 uintptr_t writable_addr = RoundDown(reinterpret_cast<uintptr_t>(writable_ptr),
781 kSafeCacheLineSize);
782 uintptr_t writable_end = RoundUp(reinterpret_cast<uintptr_t>(writable_ptr) + code_size,
783 kSafeCacheLineSize);
784 while (writable_addr < writable_end) {
Orion Hodson3ecac072017-07-20 15:28:44 +0100785 // Read from the cache-line to minimize the chance that a cache
786 // maintenance instruction causes a fault (see kernel bug comment
787 // above).
Orion Hodson17272ab2017-07-21 14:32:52 +0100788 mutant = *reinterpret_cast<const uint8_t*>(writable_addr);
789
790 // Flush cache-line
791 __asm volatile("dc cvau, %0" :: "r"(writable_addr) : "memory");
792 writable_addr += kSafeCacheLineSize;
793 }
794
795 __asm __volatile("dsb ish" ::: "memory");
796
797 uintptr_t code_addr = RoundDown(reinterpret_cast<uintptr_t>(code_ptr), kSafeCacheLineSize);
798 const uintptr_t code_end = RoundUp(reinterpret_cast<uintptr_t>(code_ptr) + code_size,
799 kSafeCacheLineSize);
800 while (code_addr < code_end) {
801 // Read from the cache-line to minimize the chance that a cache
802 // maintenance instruction causes a fault (see kernel bug comment
803 // above).
804 mutant = *reinterpret_cast<const uint8_t*>(code_addr);
Orion Hodson3ecac072017-07-20 15:28:44 +0100805
806 // Invalidating the data cache line is only strictly necessary
807 // when the JIT code cache has two mappings (the default). We know
808 // this cache line is clean so this is just invalidating it (using
Orion Hodson17272ab2017-07-21 14:32:52 +0100809 // "dc ivac" would be preferable, but counts as a write and this
810 // memory may not be mapped write permission).
811 __asm volatile("dc cvau, %0" :: "r"(code_addr) : "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100812
813 // Invalidate the instruction cache line to force instructions in
814 // range to be re-fetched following update.
Orion Hodson17272ab2017-07-21 14:32:52 +0100815 __asm volatile("ic ivau, %0" :: "r"(code_addr) : "memory");
Orion Hodson3ecac072017-07-20 15:28:44 +0100816
Orion Hodson17272ab2017-07-21 14:32:52 +0100817 code_addr += kSafeCacheLineSize;
Orion Hodson3ecac072017-07-20 15:28:44 +0100818 }
819
Orion Hodson17272ab2017-07-21 14:32:52 +0100820 // Wait for code cache invalidations to complete.
821 __asm __volatile("dsb ish" ::: "memory");
822
823 // Reset fetched instruction stream.
824 __asm __volatile("isb");
Orion Hodson3ecac072017-07-20 15:28:44 +0100825}
826
827#else // __aarch64
828
829static void FlushJitCodeCacheRange(uint8_t* code_ptr,
830 uint8_t* writable_ptr,
831 size_t code_size) {
832 if (writable_ptr != code_ptr) {
833 // When there are two mappings of the JIT code cache, RX and
834 // RW, flush the RW version first as we've just dirtied the
835 // cache lines with new code. Flushing the RX version first
836 // can cause a permission fault as the those addresses are not
837 // writable, but can appear dirty in the cache. There is a lot
838 // of potential subtlety here depending on how the cache is
839 // indexed and tagged.
840 //
841 // Flushing the RX version after the RW version is just
842 // invalidating cachelines in the instruction cache. This is
843 // necessary as the instruction cache will often have a
844 // different set of cache lines present and because the JIT
845 // code cache can start a new function at any boundary within
846 // a cache-line.
847 FlushDataCache(reinterpret_cast<char*>(writable_ptr),
848 reinterpret_cast<char*>(writable_ptr + code_size));
849 }
850 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
851 reinterpret_cast<char*>(code_ptr + code_size));
852}
853
854#endif // __aarch64
855
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100856uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
857 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000858 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700859 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000860 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100861 size_t frame_size_in_bytes,
862 size_t core_spill_mask,
863 size_t fp_spill_mask,
864 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000865 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000866 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000867 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700868 Handle<mirror::ObjectArray<mirror::Object>> roots,
869 bool has_should_deoptimize_flag,
870 const ArenaSet<ArtMethod*>&
871 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000872 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100873 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
874 // Ensure the header ends up at expected instruction alignment.
875 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
876 size_t total_size = header_size + code_size;
877
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100878 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100879 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000880 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100881 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000882 ScopedThreadSuspension sts(self, kSuspended);
883 MutexLock mu(self, lock_);
884 WaitForPotentialCollectionToComplete(self);
885 {
David Sehrd1dbb742017-07-17 11:20:38 -0700886 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000887 memory = AllocateCode(total_size);
888 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000889 return nullptr;
890 }
David Sehrd1dbb742017-07-17 11:20:38 -0700891 uint8_t* writable_ptr = memory + header_size;
892 code_ptr = ToExecutableAddress(writable_ptr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000893
David Sehrd1dbb742017-07-17 11:20:38 -0700894 std::copy(code, code + code_size, writable_ptr);
895 OatQuickMethodHeader* writable_method_header =
896 OatQuickMethodHeader::FromCodePointer(writable_ptr);
897 // We need to be able to write the OatQuickMethodHeader, so we use writable_method_header.
898 // Otherwise, the offsets encoded in OatQuickMethodHeader are used relative to an executable
899 // address, so we use code_ptr.
900 new (writable_method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000901 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700902 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000903 frame_size_in_bytes,
904 core_spill_mask,
905 fp_spill_mask,
906 code_size);
Orion Hodson3ecac072017-07-20 15:28:44 +0100907
908 FlushJitCodeCacheRange(code_ptr, writable_ptr, code_size);
Orion Hodson43ce5f82017-07-19 10:34:27 +0100909
Mingyao Yang063fc772016-08-02 11:02:54 -0700910 DCHECK(!Runtime::Current()->IsAotCompiler());
911 if (has_should_deoptimize_flag) {
David Sehrd1dbb742017-07-17 11:20:38 -0700912 writable_method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700913 }
David Sehrd1dbb742017-07-17 11:20:38 -0700914 // All the pointers exported from the cache are executable addresses.
915 method_header = ToExecutableAddress(writable_method_header);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100916 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100917
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000918 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100919 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000920 // We need to update the entry point in the runnable state for the instrumentation.
921 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700922 // Need cha_lock_ for checking all single-implementation flags and register
923 // dependencies.
924 MutexLock cha_mu(self, *Locks::cha_lock_);
925 bool single_impl_still_valid = true;
926 for (ArtMethod* single_impl : cha_single_implementation_list) {
927 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700928 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
929 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700930 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700931 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700932 break;
933 }
934 }
935
936 // Discard the code if any single-implementation assumptions are now invalid.
937 if (!single_impl_still_valid) {
938 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
939 return nullptr;
940 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000941 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800942 << "Should not be using cha on debuggable apps/runs!";
943
Mingyao Yang063fc772016-08-02 11:02:54 -0700944 for (ArtMethod* single_impl : cha_single_implementation_list) {
945 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
946 single_impl, method, method_header);
947 }
948
949 // The following needs to be guarded by cha_lock_ also. Otherwise it's
950 // possible that the compiled code is considered invalidated by some class linking,
951 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000952 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000953 // Fill the root table before updating the entry point.
David Sehrd1dbb742017-07-17 11:20:38 -0700954 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000955 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100956 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000957 FillRootTable(roots_data, roots);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100958 {
959 // Flush data cache, as compiled code references literals in it.
960 // We also need a TLB shootdown to act as memory barrier across cores.
David Sehrd1dbb742017-07-17 11:20:38 -0700961 ScopedCodeCacheWrite ccw(this, /* only_for_tlb_shootdown */ true);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100962 FlushDataCache(reinterpret_cast<char*>(roots_data),
963 reinterpret_cast<char*>(roots_data + data_size));
964 }
965 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000966 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000967 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000968 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100969 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000970 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
971 method, method_header->GetEntryPoint());
972 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000973 if (collection_in_progress_) {
974 // We need to update the live bitmap if there is a GC to ensure it sees this new
975 // code.
976 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
977 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000978 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000979 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100980 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700981 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000982 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
983 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
984 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700985 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
986 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000987 histogram_code_memory_use_.AddValue(code_size);
988 if (code_size > kCodeSizeLogThreshold) {
989 LOG(INFO) << "JIT allocated "
990 << PrettySize(code_size)
991 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700992 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000993 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000994 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100995
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100996 return reinterpret_cast<uint8_t*>(method_header);
997}
998
999size_t JitCodeCache::CodeCacheSize() {
1000 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001001 return CodeCacheSizeLocked();
1002}
1003
Orion Hodsoneced6922017-06-01 10:54:28 +01001004bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
1005 MutexLock mu(Thread::Current(), lock_);
1006 if (method->IsNative()) {
1007 return false;
1008 }
1009
1010 bool in_cache = false;
1011 {
David Sehrd1dbb742017-07-17 11:20:38 -07001012 ScopedCodeCacheWrite ccw(this);
Orion Hodsoneced6922017-06-01 10:54:28 +01001013 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
1014 if (code_iter->second == method) {
1015 if (release_memory) {
David Sehrd1dbb742017-07-17 11:20:38 -07001016 FreeCodeAndData(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +01001017 }
1018 code_iter = method_code_map_.erase(code_iter);
1019 in_cache = true;
1020 continue;
1021 }
1022 ++code_iter;
1023 }
1024 }
1025
1026 bool osr = false;
1027 auto code_map = osr_code_map_.find(method);
1028 if (code_map != osr_code_map_.end()) {
1029 osr_code_map_.erase(code_map);
1030 osr = true;
1031 }
1032
1033 if (!in_cache) {
1034 return false;
1035 }
1036
1037 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1038 if (info != nullptr) {
1039 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1040 DCHECK(profile != profiling_infos_.end());
1041 profiling_infos_.erase(profile);
1042 }
1043 method->SetProfilingInfo(nullptr);
1044 method->ClearCounter();
1045 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1046 method, GetQuickToInterpreterBridge());
1047 VLOG(jit)
1048 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
1049 << ArtMethod::PrettyMethod(method) << "@" << method
1050 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
1051 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
1052 return true;
1053}
1054
Alex Lightdba61482016-12-21 08:20:29 -08001055// This notifies the code cache that the given method has been redefined and that it should remove
1056// any cached information it has on the method. All threads must be suspended before calling this
1057// method. The compiled code for the method (if there is any) must not be in any threads call stack.
1058void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
1059 MutexLock mu(Thread::Current(), lock_);
1060 if (method->IsNative()) {
1061 return;
1062 }
1063 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1064 if (info != nullptr) {
1065 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
1066 DCHECK(profile != profiling_infos_.end());
1067 profiling_infos_.erase(profile);
1068 }
1069 method->SetProfilingInfo(nullptr);
David Sehrd1dbb742017-07-17 11:20:38 -07001070 ScopedCodeCacheWrite ccw(this);
Andreas Gampe39e67382017-05-15 19:26:38 -07001071 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -08001072 if (code_iter->second == method) {
David Sehrd1dbb742017-07-17 11:20:38 -07001073 FreeCodeAndData(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -07001074 code_iter = method_code_map_.erase(code_iter);
1075 continue;
Alex Lightdba61482016-12-21 08:20:29 -08001076 }
Andreas Gampe39e67382017-05-15 19:26:38 -07001077 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -08001078 }
1079 auto code_map = osr_code_map_.find(method);
1080 if (code_map != osr_code_map_.end()) {
1081 osr_code_map_.erase(code_map);
1082 }
1083}
1084
1085// This invalidates old_method. Once this function returns one can no longer use old_method to
1086// execute code unless it is fixed up. This fixup will happen later in the process of installing a
1087// class redefinition.
1088// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
1089// shouldn't be used since it is no longer logically in the jit code cache.
1090// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
1091void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +00001092 // Native methods have no profiling info and need no special handling from the JIT code cache.
1093 if (old_method->IsNative()) {
1094 return;
1095 }
Alex Lightdba61482016-12-21 08:20:29 -08001096 MutexLock mu(Thread::Current(), lock_);
1097 // Update ProfilingInfo to the new one and remove it from the old_method.
1098 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
1099 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
1100 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
1101 old_method->SetProfilingInfo(nullptr);
1102 // Since the JIT should be paused and all threads suspended by the time this is called these
1103 // checks should always pass.
1104 DCHECK(!info->IsInUseByCompiler());
1105 new_method->SetProfilingInfo(info);
1106 info->method_ = new_method;
1107 }
1108 // Update method_code_map_ to point to the new method.
1109 for (auto& it : method_code_map_) {
1110 if (it.second == old_method) {
1111 it.second = new_method;
1112 }
1113 }
1114 // Update osr_code_map_ to point to the new method.
1115 auto code_map = osr_code_map_.find(old_method);
1116 if (code_map != osr_code_map_.end()) {
1117 osr_code_map_.Put(new_method, code_map->second);
1118 osr_code_map_.erase(old_method);
1119 }
1120}
1121
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001122size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001123 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001124}
1125
1126size_t JitCodeCache::DataCacheSize() {
1127 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001128 return DataCacheSizeLocked();
1129}
1130
1131size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001132 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001133}
1134
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001135void JitCodeCache::ClearData(Thread* self,
1136 uint8_t* stack_map_data,
1137 uint8_t* roots_data) {
1138 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
David Sehrd1dbb742017-07-17 11:20:38 -07001139 CHECK(IsDataAddress(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001140 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +00001141 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001142}
1143
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001144size_t JitCodeCache::ReserveData(Thread* self,
1145 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001146 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001147 size_t number_of_roots,
1148 ArtMethod* method,
1149 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001150 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001151 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001152 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001153 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001154 uint8_t* result = nullptr;
1155
1156 {
1157 ScopedThreadSuspension sts(self, kSuspended);
1158 MutexLock mu(self, lock_);
1159 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001160 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001161 }
1162
1163 if (result == nullptr) {
1164 // Retry.
1165 GarbageCollectCache(self);
1166 ScopedThreadSuspension sts(self, kSuspended);
1167 MutexLock mu(self, lock_);
1168 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001169 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001170 }
1171
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001172 MutexLock mu(self, lock_);
1173 histogram_stack_map_memory_use_.AddValue(size);
1174 if (size > kStackMapSizeLogThreshold) {
1175 LOG(INFO) << "JIT allocated "
1176 << PrettySize(size)
1177 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001178 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001179 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001180 if (result != nullptr) {
1181 *roots_data = result;
1182 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001183 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001184 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001185 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001186 } else {
1187 *roots_data = nullptr;
1188 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001189 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001190 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001191 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001192}
1193
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001194class MarkCodeVisitor FINAL : public StackVisitor {
1195 public:
1196 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1197 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1198 code_cache_(code_cache_in),
1199 bitmap_(code_cache_->GetLiveBitmap()) {}
1200
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001201 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001202 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1203 if (method_header == nullptr) {
1204 return true;
1205 }
1206 const void* code = method_header->GetCode();
1207 if (code_cache_->ContainsPc(code)) {
1208 // Use the atomic set version, as multiple threads are executing this code.
1209 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1210 }
1211 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001212 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001213
1214 private:
1215 JitCodeCache* const code_cache_;
1216 CodeCacheBitmap* const bitmap_;
1217};
1218
1219class MarkCodeClosure FINAL : public Closure {
1220 public:
1221 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1222 : code_cache_(code_cache), barrier_(barrier) {}
1223
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001224 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001225 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001226 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1227 MarkCodeVisitor visitor(thread, code_cache_);
1228 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001229 if (kIsDebugBuild) {
1230 // The stack walking code queries the side instrumentation stack if it
1231 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1232 // must have been seen. We sanity check this below.
1233 for (const instrumentation::InstrumentationStackFrame& frame
1234 : *thread->GetInstrumentationStack()) {
1235 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1236 // its stack frame, it is not the method owning return_pc_. We just pass null to
1237 // LookupMethodHeader: the method is only checked against in debug builds.
1238 OatQuickMethodHeader* method_header =
1239 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
1240 if (method_header != nullptr) {
1241 const void* code = method_header->GetCode();
1242 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1243 }
1244 }
1245 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001246 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001247 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001248
1249 private:
1250 JitCodeCache* const code_cache_;
1251 Barrier* const barrier_;
1252};
1253
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001254void JitCodeCache::NotifyCollectionDone(Thread* self) {
1255 collection_in_progress_ = false;
1256 lock_cond_.Broadcast(self);
1257}
1258
1259void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1260 size_t per_space_footprint = new_footprint / 2;
David Sehrd1dbb742017-07-17 11:20:38 -07001261 CHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001262 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1263 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1264 {
David Sehrd1dbb742017-07-17 11:20:38 -07001265 ScopedCodeCacheWrite scc(this);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001266 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1267 }
1268}
1269
1270bool JitCodeCache::IncreaseCodeCacheCapacity() {
1271 if (current_capacity_ == max_capacity_) {
1272 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001273 }
1274
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001275 // Double the capacity if we're below 1MB, or increase it by 1MB if
1276 // we're above.
1277 if (current_capacity_ < 1 * MB) {
1278 current_capacity_ *= 2;
1279 } else {
1280 current_capacity_ += 1 * MB;
1281 }
1282 if (current_capacity_ > max_capacity_) {
1283 current_capacity_ = max_capacity_;
1284 }
1285
1286 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1287 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
1288 }
1289
1290 SetFootprintLimit(current_capacity_);
1291
1292 return true;
1293}
1294
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001295void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1296 Barrier barrier(0);
1297 size_t threads_running_checkpoint = 0;
1298 MarkCodeClosure closure(this, &barrier);
1299 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1300 // Now that we have run our checkpoint, move to a suspended state and wait
1301 // for other threads to run the checkpoint.
1302 ScopedThreadSuspension sts(self, kSuspended);
1303 if (threads_running_checkpoint != 0) {
1304 barrier.Increment(self, threads_running_checkpoint);
1305 }
1306}
1307
Nicolas Geoffray35122442016-03-02 12:05:30 +00001308bool JitCodeCache::ShouldDoFullCollection() {
1309 if (current_capacity_ == max_capacity_) {
1310 // Always do a full collection when the code cache is full.
1311 return true;
1312 } else if (current_capacity_ < kReservedCapacity) {
1313 // Always do partial collection when the code cache size is below the reserved
1314 // capacity.
1315 return false;
1316 } else if (last_collection_increased_code_cache_) {
1317 // This time do a full collection.
1318 return true;
1319 } else {
1320 // This time do a partial collection.
1321 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001322 }
1323}
1324
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001325void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001326 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001327 if (!garbage_collect_code_) {
1328 MutexLock mu(self, lock_);
1329 IncreaseCodeCacheCapacity();
1330 return;
1331 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001332
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001333 // Wait for an existing collection, or let everyone know we are starting one.
1334 {
1335 ScopedThreadSuspension sts(self, kSuspended);
1336 MutexLock mu(self, lock_);
1337 if (WaitForPotentialCollectionToComplete(self)) {
1338 return;
1339 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001340 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001341 live_bitmap_.reset(CodeCacheBitmap::Create(
1342 "code-cache-bitmap",
David Sehrd1dbb742017-07-17 11:20:38 -07001343 reinterpret_cast<uintptr_t>(executable_code_map_->Begin()),
1344 reinterpret_cast<uintptr_t>(executable_code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001345 collection_in_progress_ = true;
1346 }
1347 }
1348
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001349 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001350 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001351 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001352
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001353 bool do_full_collection = false;
1354 {
1355 MutexLock mu(self, lock_);
1356 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001357 }
1358
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001359 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1360 LOG(INFO) << "Do "
1361 << (do_full_collection ? "full" : "partial")
1362 << " code cache collection, code="
1363 << PrettySize(CodeCacheSize())
1364 << ", data=" << PrettySize(DataCacheSize());
1365 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001366
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001367 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1368
1369 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
1370 LOG(INFO) << "After code cache collection, code="
1371 << PrettySize(CodeCacheSize())
1372 << ", data=" << PrettySize(DataCacheSize());
1373 }
1374
1375 {
1376 MutexLock mu(self, lock_);
1377
1378 // Increase the code cache only when we do partial collections.
1379 // TODO: base this strategy on how full the code cache is?
1380 if (do_full_collection) {
1381 last_collection_increased_code_cache_ = false;
1382 } else {
1383 last_collection_increased_code_cache_ = true;
1384 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001385 }
1386
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001387 bool next_collection_will_be_full = ShouldDoFullCollection();
1388
1389 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001390 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001391 // Save the entry point of methods we have compiled, and update the entry
1392 // point of those methods to the interpreter. If the method is invoked, the
1393 // interpreter will update its entry point to the compiled code and call it.
1394 for (ProfilingInfo* info : profiling_infos_) {
1395 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1396 if (ContainsPc(entry_point)) {
1397 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001398 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1399 // class of the method. We may be concurrently running a GC which makes accessing
1400 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1401 // checked that the current entry point is JIT compiled code.
1402 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001403 }
1404 }
1405
1406 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1407 }
1408 live_bitmap_.reset(nullptr);
1409 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001410 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001411 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001412 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001413}
1414
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001415void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001416 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001417 std::unordered_set<OatQuickMethodHeader*> method_headers;
1418 {
1419 MutexLock mu(self, lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001420 ScopedCodeCacheWrite scc(this);
Mingyao Yang063fc772016-08-02 11:02:54 -07001421 // Iterate over all compiled code and remove entries that are not marked.
1422 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1423 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001424 CHECK(IsExecutableAddress(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001425 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1426 if (GetLiveBitmap()->Test(allocation)) {
1427 ++it;
1428 } else {
David Sehrd1dbb742017-07-17 11:20:38 -07001429 CHECK(IsExecutableAddress(it->first));
Mingyao Yang063fc772016-08-02 11:02:54 -07001430 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1431 it = method_code_map_.erase(it);
1432 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001433 }
1434 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001435 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001436}
1437
1438void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001439 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001440 {
1441 MutexLock mu(self, lock_);
1442 if (collect_profiling_info) {
1443 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1444 // Also remove the saved entry point from the ProfilingInfo objects.
1445 for (ProfilingInfo* info : profiling_infos_) {
1446 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001447 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001448 info->GetMethod()->SetProfilingInfo(nullptr);
1449 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001450
1451 if (info->GetSavedEntryPoint() != nullptr) {
1452 info->SetSavedEntryPoint(nullptr);
1453 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001454 // give it a chance to be hot again.
1455 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001456 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001457 }
1458 } else if (kIsDebugBuild) {
1459 // Sanity check that the profiling infos do not have a dangling entry point.
1460 for (ProfilingInfo* info : profiling_infos_) {
1461 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001462 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001463 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001464
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001465 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1466 // an entry point is either:
1467 // - an osr compiled code, that will be removed if not in a thread call stack.
1468 // - discarded compiled code, that will be removed if not in a thread call stack.
1469 for (const auto& it : method_code_map_) {
1470 ArtMethod* method = it.second;
1471 const void* code_ptr = it.first;
David Sehrd1dbb742017-07-17 11:20:38 -07001472 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001473 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1474 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1475 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1476 }
1477 }
1478
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001479 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001480 // on thread stacks).
1481 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001482 }
1483
1484 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001485 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001486
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001487 // At this point, mutator threads are still running, and entrypoints of methods can
1488 // change. We do know they cannot change to a code cache entry that is not marked,
1489 // therefore we can safely remove those entries.
1490 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001491
Nicolas Geoffray35122442016-03-02 12:05:30 +00001492 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001493 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001494 MutexLock mu(self, lock_);
1495 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001496 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001497 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
David Sehrd1dbb742017-07-17 11:20:38 -07001498 CHECK(IsDataAddress(info));
Nicolas Geoffray35122442016-03-02 12:05:30 +00001499 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001500 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1501 // that the compiled code would not get revived. As mutator threads run concurrently,
1502 // they may have revived the compiled code, and now we are in the situation where
1503 // a method has compiled code but no ProfilingInfo.
1504 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1505 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001506 if (ContainsPc(ptr) &&
1507 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001508 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001509 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001510 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001511 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001512 return true;
1513 }
1514 return false;
1515 });
1516 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001517 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001518 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001519}
1520
Nicolas Geoffray35122442016-03-02 12:05:30 +00001521bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001522 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001523 // Check that methods we have compiled do have a ProfilingInfo object. We would
1524 // have memory leaks of compiled code otherwise.
1525 for (const auto& it : method_code_map_) {
1526 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001527 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001528 const void* code_ptr = it.first;
1529 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1530 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1531 // If the code is not dead, then we have a problem. Note that this can even
1532 // happen just after a collection, as mutator threads are running in parallel
1533 // and could deoptimize an existing compiled code.
1534 return false;
1535 }
1536 }
1537 }
1538 return true;
1539}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001540
1541OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1542 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1543 if (kRuntimeISA == kArm) {
1544 // On Thumb-2, the pc is offset by one.
1545 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001546 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001547 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1548 return nullptr;
1549 }
1550
1551 MutexLock mu(Thread::Current(), lock_);
1552 if (method_code_map_.empty()) {
1553 return nullptr;
1554 }
1555 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1556 --it;
1557
1558 const void* code_ptr = it->first;
David Sehrd1dbb742017-07-17 11:20:38 -07001559 CHECK(IsExecutableAddress(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001560 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1561 if (!method_header->Contains(pc)) {
1562 return nullptr;
1563 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001564 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001565 // When we are walking the stack to redefine classes and creating obsolete methods it is
1566 // possible that we might have updated the method_code_map by making this method obsolete in a
1567 // previous frame. Therefore we should just check that the non-obsolete version of this method
1568 // is the one we expect. We change to the non-obsolete versions in the error message since the
1569 // obsolete version of the method might not be fully initialized yet. This situation can only
1570 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1571 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1572 // information.)
1573 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1574 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1575 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001576 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001577 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001578 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001579}
1580
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001581OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1582 MutexLock mu(Thread::Current(), lock_);
1583 auto it = osr_code_map_.find(method);
1584 if (it == osr_code_map_.end()) {
1585 return nullptr;
1586 }
1587 return OatQuickMethodHeader::FromCodePointer(it->second);
1588}
1589
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001590ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1591 ArtMethod* method,
1592 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001593 bool retry_allocation)
1594 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1595 NO_THREAD_SAFETY_ANALYSIS {
1596 ProfilingInfo* info = nullptr;
1597 if (!retry_allocation) {
1598 // If we are allocating for the interpreter, just try to lock, to avoid
1599 // lock contention with the JIT.
1600 if (lock_.ExclusiveTryLock(self)) {
1601 info = AddProfilingInfoInternal(self, method, entries);
1602 lock_.ExclusiveUnlock(self);
1603 }
1604 } else {
1605 {
1606 MutexLock mu(self, lock_);
1607 info = AddProfilingInfoInternal(self, method, entries);
1608 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001609
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001610 if (info == nullptr) {
1611 GarbageCollectCache(self);
1612 MutexLock mu(self, lock_);
1613 info = AddProfilingInfoInternal(self, method, entries);
1614 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001615 }
1616 return info;
1617}
1618
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001619ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001620 ArtMethod* method,
1621 const std::vector<uint32_t>& entries) {
1622 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001623 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001624 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001625
1626 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001627 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001628 if (info != nullptr) {
1629 return info;
1630 }
1631
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001632 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001633 if (data == nullptr) {
1634 return nullptr;
1635 }
1636 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001637
1638 // Make sure other threads see the data in the profiling info object before the
1639 // store in the ArtMethod's ProfilingInfo pointer.
1640 QuasiAtomic::ThreadFenceRelease();
1641
David Sehrd1dbb742017-07-17 11:20:38 -07001642 CHECK(IsDataAddress(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001643 method->SetProfilingInfo(info);
1644 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001645 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001646 return info;
1647}
1648
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001649// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1650// is already held.
1651void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1652 if (code_mspace_ == mspace) {
1653 size_t result = code_end_;
1654 code_end_ += increment;
David Sehrd1dbb742017-07-17 11:20:38 -07001655 MemMap* writable_map = GetWritableMemMap();
1656 return reinterpret_cast<void*>(result + writable_map->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001657 } else {
1658 DCHECK_EQ(data_mspace_, mspace);
1659 size_t result = data_end_;
1660 data_end_ += increment;
1661 return reinterpret_cast<void*>(result + data_map_->Begin());
1662 }
1663}
1664
Calin Juravle99629622016-04-19 16:33:46 +01001665void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001666 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001667 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001668 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001669 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001670 for (const ProfilingInfo* info : profiling_infos_) {
1671 ArtMethod* method = info->GetMethod();
1672 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001673 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1674 // Skip dex files which are not profiled.
1675 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001676 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001677 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001678
1679 // If the method didn't reach the compilation threshold don't save the inline caches.
1680 // They might be incomplete and cause unnecessary deoptimizations.
1681 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1682 if (method->GetCounter() < jit_compile_threshold) {
1683 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001684 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001685 continue;
1686 }
1687
Calin Juravle940eb0c2017-01-30 19:30:44 -08001688 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001689 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001690 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001691 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001692 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001693 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1694 mirror::Class* cls = cache.classes_[k].Read();
1695 if (cls == nullptr) {
1696 break;
1697 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001698
Calin Juravle13439f02017-02-21 01:17:21 -08001699 // Check if the receiver is in the boot class path or if it's in the
1700 // same class loader as the caller. If not, skip it, as there is not
1701 // much we can do during AOT.
1702 if (!cls->IsBootStrapClassLoaded() &&
1703 caller->GetClassLoader() != cls->GetClassLoader()) {
1704 is_missing_types = true;
1705 continue;
1706 }
1707
Calin Juravle4ca70a32017-02-21 16:22:24 -08001708 const DexFile* class_dex_file = nullptr;
1709 dex::TypeIndex type_index;
1710
1711 if (cls->GetDexCache() == nullptr) {
1712 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001713 // Make a best effort to find the type index in the method's dex file.
1714 // We could search all open dex files but that might turn expensive
1715 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001716 class_dex_file = dex_file;
1717 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1718 } else {
1719 class_dex_file = &(cls->GetDexFile());
1720 type_index = cls->GetDexTypeIndex();
1721 }
1722 if (!type_index.IsValid()) {
1723 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001724 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001725 continue;
1726 }
1727 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001728 // Only consider classes from the same apk (including multidex).
1729 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001730 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001731 } else {
1732 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001733 }
1734 }
1735 if (!profile_classes.empty()) {
1736 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001737 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001738 }
1739 }
1740 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001741 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001742 }
1743}
1744
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001745uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1746 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001747}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001748
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001749bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1750 MutexLock mu(Thread::Current(), lock_);
1751 return osr_code_map_.find(method) != osr_code_map_.end();
1752}
1753
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001754bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1755 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001756 return false;
1757 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001758
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001759 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001760 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1761 return false;
1762 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001763
Andreas Gampe542451c2016-07-26 09:02:02 -07001764 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001765 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001766 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001767 // Because the counter is not atomic, there are some rare cases where we may not hit the
1768 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001769 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001770 return false;
1771 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001772
buzbee454b3b62016-04-07 14:42:47 -07001773 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001774 return false;
1775 }
1776
buzbee454b3b62016-04-07 14:42:47 -07001777 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001778 return true;
1779}
1780
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001781ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001782 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001783 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001784 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001785 if (!info->IncrementInlineUse()) {
1786 // Overflow of inlining uses, just bail.
1787 return nullptr;
1788 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001789 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001790 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001791}
1792
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001793void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001794 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001795 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001796 DCHECK(info != nullptr);
1797 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001798}
1799
buzbee454b3b62016-04-07 14:42:47 -07001800void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001801 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001802 DCHECK(info->IsMethodBeingCompiled(osr));
1803 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001804}
1805
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001806size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1807 MutexLock mu(Thread::Current(), lock_);
David Sehrd1dbb742017-07-17 11:20:38 -07001808 CHECK(IsExecutableAddress(ptr));
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001809 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1810}
1811
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001812void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1813 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001814 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001815 if ((profiling_info != nullptr) &&
1816 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1817 // Prevent future uses of the compiled code.
1818 profiling_info->SetSavedEntryPoint(nullptr);
1819 }
1820
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001821 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001822 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001823 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001824 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1825 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001826 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001827 } else {
1828 MutexLock mu(Thread::Current(), lock_);
1829 auto it = osr_code_map_.find(method);
1830 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1831 // Remove the OSR method, to avoid using it again.
1832 osr_code_map_.erase(it);
1833 }
1834 }
1835}
1836
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001837uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1838 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1839 uint8_t* result = reinterpret_cast<uint8_t*>(
1840 mspace_memalign(code_mspace_, alignment, code_size));
1841 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1842 // Ensure the header ends up at expected instruction alignment.
1843 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
David Sehrd1dbb742017-07-17 11:20:38 -07001844 CHECK(IsWritableAddress(result));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001845 used_memory_for_code_ += mspace_usable_size(result);
1846 return result;
1847}
1848
David Sehrd1dbb742017-07-17 11:20:38 -07001849void JitCodeCache::FreeRawCode(void* code) {
1850 CHECK(IsExecutableAddress(code));
1851 void* writable_code = ToWritableAddress(code);
1852 used_memory_for_code_ -= mspace_usable_size(writable_code);
1853 mspace_free(code_mspace_, writable_code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001854}
1855
1856uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1857 void* result = mspace_malloc(data_mspace_, data_size);
David Sehrd1dbb742017-07-17 11:20:38 -07001858 CHECK(IsDataAddress(reinterpret_cast<uint8_t*>(result)));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001859 used_memory_for_data_ += mspace_usable_size(result);
1860 return reinterpret_cast<uint8_t*>(result);
1861}
1862
1863void JitCodeCache::FreeData(uint8_t* data) {
David Sehrd1dbb742017-07-17 11:20:38 -07001864 CHECK(IsDataAddress(data));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001865 used_memory_for_data_ -= mspace_usable_size(data);
1866 mspace_free(data_mspace_, data);
1867}
1868
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001869void JitCodeCache::Dump(std::ostream& os) {
1870 MutexLock mu(Thread::Current(), lock_);
1871 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1872 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1873 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1874 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1875 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1876 << "Total number of JIT compilations for on stack replacement: "
1877 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001878 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001879 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1880 histogram_code_memory_use_.PrintMemoryUse(os);
1881 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001882}
1883
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001884} // namespace jit
1885} // namespace art