blob: a5c167eee85c4b2f352371a5fa17c4f64423b24b [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"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070029#include "dex_file_loader.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010030#include "entrypoints/runtime_asm_entrypoints.h"
31#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010032#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000033#include "handle.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070034#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000035#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000036#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010037#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080038#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070040#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070041#include "object_callbacks.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000042#include "profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070044#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000045#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010046#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080047
48namespace art {
49namespace jit {
50
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010051static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
52static constexpr int kProtData = PROT_READ | PROT_WRITE;
53static constexpr int kProtCode = PROT_READ | PROT_EXEC;
54
Nicolas Geoffray933330a2016-03-16 14:20:06 +000055static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
56static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
57
Vladimir Markoe7441632017-11-29 13:00:56 +000058class JitCodeCache::JniStubKey {
59 public:
60 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
61 : shorty_(method->GetShorty()),
62 is_static_(method->IsStatic()),
63 is_fast_native_(method->IsFastNative()),
64 is_critical_native_(method->IsCriticalNative()),
65 is_synchronized_(method->IsSynchronized()) {
66 DCHECK(!(is_fast_native_ && is_critical_native_));
67 }
68
69 bool operator<(const JniStubKey& rhs) const {
70 if (is_static_ != rhs.is_static_) {
71 return rhs.is_static_;
72 }
73 if (is_synchronized_ != rhs.is_synchronized_) {
74 return rhs.is_synchronized_;
75 }
76 if (is_fast_native_ != rhs.is_fast_native_) {
77 return rhs.is_fast_native_;
78 }
79 if (is_critical_native_ != rhs.is_critical_native_) {
80 return rhs.is_critical_native_;
81 }
82 return strcmp(shorty_, rhs.shorty_) < 0;
83 }
84
85 // Update the shorty to point to another method's shorty. Call this function when removing
86 // the method that references the old shorty from JniCodeData and not removing the entire
87 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
88 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
89 const char* shorty = method->GetShorty();
90 DCHECK_STREQ(shorty_, shorty);
91 shorty_ = shorty;
92 }
93
94 private:
95 // The shorty points to a DexFile data and may need to change
96 // to point to the same shorty in a different DexFile.
97 mutable const char* shorty_;
98
99 const bool is_static_;
100 const bool is_fast_native_;
101 const bool is_critical_native_;
102 const bool is_synchronized_;
103};
104
105class JitCodeCache::JniStubData {
106 public:
107 JniStubData() : code_(nullptr), methods_() {}
108
109 void SetCode(const void* code) {
110 DCHECK(code != nullptr);
111 code_ = code;
112 }
113
114 const void* GetCode() const {
115 return code_;
116 }
117
118 bool IsCompiled() const {
119 return GetCode() != nullptr;
120 }
121
122 void AddMethod(ArtMethod* method) {
123 if (!ContainsElement(methods_, method)) {
124 methods_.push_back(method);
125 }
126 }
127
128 const std::vector<ArtMethod*>& GetMethods() const {
129 return methods_;
130 }
131
132 void RemoveMethodsIn(const LinearAlloc& alloc) {
133 auto kept_end = std::remove_if(
134 methods_.begin(),
135 methods_.end(),
136 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
137 methods_.erase(kept_end, methods_.end());
138 }
139
140 bool RemoveMethod(ArtMethod* method) {
141 auto it = std::find(methods_.begin(), methods_.end(), method);
142 if (it != methods_.end()) {
143 methods_.erase(it);
144 return true;
145 } else {
146 return false;
147 }
148 }
149
150 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
151 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
152 }
153
154 private:
155 const void* code_;
156 std::vector<ArtMethod*> methods_;
157};
158
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000159JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
160 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000161 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000162 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800163 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100164 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000165
David Sehrd1dbb742017-07-17 11:20:38 -0700166 // Generating debug information is for using the Linux perf tool on
167 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100168 // Also, target linux does not support ashmem.
169 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700170
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000171 // With 'perf', we want a 1-1 mapping between an address and a method.
172 bool garbage_collect_code = !generate_debug_info;
173
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000174 // We need to have 32 bit offsets from method headers in code cache which point to things
175 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
176 // Ensure we're below 1 GB to be safe.
177 if (max_capacity > 1 * GB) {
178 std::ostringstream oss;
179 oss << "Maxium code cache capacity is limited to 1 GB, "
180 << PrettySize(max_capacity) << " is too big";
181 *error_msg = oss.str();
182 return nullptr;
183 }
184
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800185 std::string error_str;
186 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000187 // Map in low 4gb to simplify accessing root tables for x86_64.
188 // We could do PC-relative addressing to avoid this problem, but that
189 // would require reserving code and data area before submitting, which
190 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700191 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000192 "data-code-cache", nullptr,
193 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700194 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000195 /* low_4gb */ true,
196 /* reuse */ false,
197 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700198 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100199 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800200 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700201 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800202 *error_msg = oss.str();
203 return nullptr;
204 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100205
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100206 // Align both capacities to page size, as that's the unit mspaces use.
207 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
208 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100209
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100210 // Data cache is 1 / 2 of the map.
211 // TODO: Make this variable?
212 size_t data_size = max_capacity / 2;
213 size_t code_size = max_capacity - data_size;
214 DCHECK_EQ(code_size + data_size, max_capacity);
215 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700216
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100217 MemMap* code_map =
218 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700219 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100220 std::ostringstream oss;
221 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
222 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700223 return nullptr;
224 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100225 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000226 data_size = initial_capacity / 2;
227 code_size = initial_capacity - data_size;
228 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100229 return new JitCodeCache(
230 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800231}
232
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100233JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000234 MemMap* data_map,
235 size_t initial_code_capacity,
236 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000237 size_t max_capacity,
238 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100239 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000240 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100241 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100242 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000243 data_map_(data_map),
244 max_capacity_(max_capacity),
245 current_capacity_(initial_code_capacity + initial_data_capacity),
246 code_end_(initial_code_capacity),
247 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000248 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000249 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000250 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000251 used_memory_for_data_(0),
252 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000253 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000254 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000255 number_of_collections_(0),
256 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
257 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000258 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
259 is_weak_access_enabled_(true),
260 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100261
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000262 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100263 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000264 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100265
266 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
267 PLOG(FATAL) << "create_mspace_with_base failed";
268 }
269
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000270 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100271
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700272 CheckedCall(mprotect,
273 "mprotect jit code cache",
274 code_map_->Begin(),
275 code_map_->Size(),
276 kProtCode);
277 CheckedCall(mprotect,
278 "mprotect jit data cache",
279 data_map_->Begin(),
280 data_map_->Size(),
281 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100282
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000283 VLOG(jit) << "Created jit code cache: initial data size="
284 << PrettySize(initial_data_capacity)
285 << ", initial code size="
286 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800287}
288
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000289JitCodeCache::~JitCodeCache() {}
290
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100291bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100292 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800293}
294
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000295bool JitCodeCache::ContainsMethod(ArtMethod* method) {
296 MutexLock mu(Thread::Current(), lock_);
Vladimir Markoe7441632017-11-29 13:00:56 +0000297 if (UNLIKELY(method->IsNative())) {
298 auto it = jni_stubs_map_.find(JniStubKey(method));
299 if (it != jni_stubs_map_.end() &&
300 it->second.IsCompiled() &&
301 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000302 return true;
303 }
Vladimir Markoe7441632017-11-29 13:00:56 +0000304 } else {
305 for (const auto& it : method_code_map_) {
306 if (it.second == method) {
307 return true;
308 }
309 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000310 }
311 return false;
312}
313
Vladimir Markoe7441632017-11-29 13:00:56 +0000314const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
315 DCHECK(method->IsNative());
316 MutexLock mu(Thread::Current(), lock_);
317 auto it = jni_stubs_map_.find(JniStubKey(method));
318 if (it != jni_stubs_map_.end()) {
319 JniStubData& data = it->second;
320 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
321 return data.GetCode();
322 }
323 }
324 return nullptr;
325}
326
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800327class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100328 public:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100329 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
330 : ScopedTrace("ScopedCodeCacheWrite"),
331 code_map_(code_map),
332 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800333 ScopedTrace trace("mprotect all");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700334 CheckedCall(mprotect,
335 "make code writable",
336 code_map_->Begin(),
337 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
338 kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800339 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100340 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800341 ScopedTrace trace("mprotect code");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700342 CheckedCall(mprotect,
343 "make code protected",
344 code_map_->Begin(),
345 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
346 kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100347 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700348
David Sehrd1dbb742017-07-17 11:20:38 -0700349 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100350 MemMap* const code_map_;
351
352 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
353 // one page.
354 const bool only_for_tlb_shootdown_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100355
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100356 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
357};
358
359uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100360 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000361 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700362 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000363 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100364 size_t frame_size_in_bytes,
365 size_t core_spill_mask,
366 size_t fp_spill_mask,
367 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000368 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100369 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000370 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700371 Handle<mirror::ObjectArray<mirror::Object>> roots,
372 bool has_should_deoptimize_flag,
373 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100374 uint8_t* result = CommitCodeInternal(self,
375 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000376 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700377 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000378 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100379 frame_size_in_bytes,
380 core_spill_mask,
381 fp_spill_mask,
382 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000383 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100384 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000385 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700386 roots,
387 has_should_deoptimize_flag,
388 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100389 if (result == nullptr) {
390 // Retry.
391 GarbageCollectCache(self);
392 result = CommitCodeInternal(self,
393 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000394 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700395 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000396 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100397 frame_size_in_bytes,
398 core_spill_mask,
399 fp_spill_mask,
400 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000401 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100402 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000403 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700404 roots,
405 has_should_deoptimize_flag,
406 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100407 }
408 return result;
409}
410
411bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
412 bool in_collection = false;
413 while (collection_in_progress_) {
414 in_collection = true;
415 lock_cond_.Wait(self);
416 }
417 return in_collection;
418}
419
420static uintptr_t FromCodeToAllocation(const void* code) {
421 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
422 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
423}
424
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000425static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
426 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
427}
428
429static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
430 // The length of the table is stored just before the stack map (and therefore at the end of
431 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
432 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
433}
434
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800435static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
436 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
437 // pointer.
438 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
439}
440
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000441static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
442 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
443}
444
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000445static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
446 REQUIRES_SHARED(Locks::mutator_lock_) {
447 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800448 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000449 // Put all roots in `roots_data`.
450 for (uint32_t i = 0; i < length; ++i) {
451 ObjPtr<mirror::Object> object = roots->Get(i);
452 if (kIsDebugBuild) {
453 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000454 if (object->IsString()) {
455 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
456 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
457 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
458 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000459 }
460 gc_roots[i] = GcRoot<mirror::Object>(object);
461 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000462}
463
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100464static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000465 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
466 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
467 uint32_t roots = GetNumberOfRoots(data);
468 if (number_of_roots != nullptr) {
469 *number_of_roots = roots;
470 }
471 return data - ComputeRootTableSize(roots);
472}
473
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100474// Use a sentinel for marking entries in the JIT table that have been cleared.
475// This helps diagnosing in case the compiled code tries to wrongly access such
476// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700477static mirror::Class* const weak_sentinel =
478 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100479
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000480// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100481static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
482 IsMarkedVisitor* visitor,
483 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000484 REQUIRES_SHARED(Locks::mutator_lock_) {
485 // This does not need a read barrier because this is called by GC.
486 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100487 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000488 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
489 // Look at the classloader of the class to know if it has been unloaded.
490 // This does not need a read barrier because this is called by GC.
491 mirror::Object* class_loader =
492 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
493 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
494 // The class loader is live, update the entry if the class has moved.
495 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
496 // Note that new_object can be null for CMS and newly allocated objects.
497 if (new_cls != nullptr && new_cls != cls) {
498 *root_ptr = GcRoot<mirror::Class>(new_cls);
499 }
500 } else {
501 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100502 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000503 }
504 }
505}
506
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000507void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
508 MutexLock mu(Thread::Current(), lock_);
509 for (const auto& entry : method_code_map_) {
510 uint32_t number_of_roots = 0;
511 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
512 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
513 for (uint32_t i = 0; i < number_of_roots; ++i) {
514 // This does not need a read barrier because this is called by GC.
515 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100516 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000517 // entry got deleted in a previous sweep.
518 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
519 mirror::Object* new_object = visitor->IsMarked(object);
520 // We know the string is marked because it's a strongly-interned string that
521 // is always alive. The IsMarked implementation of the CMS collector returns
522 // null for newly allocated objects, but we know those haven't moved. Therefore,
523 // only update the entry if we get a different non-null string.
524 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
525 // out of the weak access/creation pause. b/32167580
526 if (new_object != nullptr && new_object != object) {
527 DCHECK(new_object->IsString());
528 roots[i] = GcRoot<mirror::Object>(new_object);
529 }
530 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100531 ProcessWeakClass(
532 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000533 }
534 }
535 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000536 // Walk over inline caches to clear entries containing unloaded classes.
537 for (ProfilingInfo* info : profiling_infos_) {
538 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
539 InlineCache* cache = &info->cache_[i];
540 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100541 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000542 }
543 }
544 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000545}
546
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100547void JitCodeCache::FreeCode(const void* code_ptr) {
548 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000549 // Notify native debugger that we are about to remove the code.
550 // It does nothing if we are not using native debugger.
551 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Vladimir Markoe7441632017-11-29 13:00:56 +0000552 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
553 FreeData(GetRootTable(code_ptr));
554 } // else this is a JNI stub without any data.
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100555 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100556}
557
Mingyao Yang063fc772016-08-02 11:02:54 -0700558void JitCodeCache::FreeAllMethodHeaders(
559 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
560 {
561 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700562 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700563 ->RemoveDependentsWithMethodHeaders(method_headers);
564 }
565
566 // We need to remove entries in method_headers from CHA dependencies
567 // first since once we do FreeCode() below, the memory can be reused
568 // so it's possible for the same method_header to start representing
569 // different compile code.
570 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100571 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700572 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100573 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700574 }
575}
576
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100577void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800578 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700579 // We use a set to first collect all method_headers whose code need to be
580 // removed. We need to free the underlying code after we remove CHA dependencies
581 // for entries in this set. And it's more efficient to iterate through
582 // the CHA dependency map just once with an unordered_set.
583 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000584 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700585 MutexLock mu(self, lock_);
586 // We do not check if a code cache GC is in progress, as this method comes
587 // with the classlinker_classes_lock_ held, and suspending ourselves could
588 // lead to a deadlock.
589 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100590 ScopedCodeCacheWrite scc(code_map_.get());
Vladimir Markoe7441632017-11-29 13:00:56 +0000591 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
592 it->second.RemoveMethodsIn(alloc);
593 if (it->second.GetMethods().empty()) {
594 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
595 it = jni_stubs_map_.erase(it);
596 } else {
597 it->first.UpdateShorty(it->second.GetMethods().front());
598 ++it;
599 }
600 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700601 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
602 if (alloc.ContainsUnsafe(it->second)) {
603 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
604 it = method_code_map_.erase(it);
605 } else {
606 ++it;
607 }
608 }
609 }
610 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
611 if (alloc.ContainsUnsafe(it->first)) {
612 // Note that the code has already been pushed to method_headers in the loop
613 // above and is going to be removed in FreeCode() below.
614 it = osr_code_map_.erase(it);
615 } else {
616 ++it;
617 }
618 }
619 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
620 ProfilingInfo* info = *it;
621 if (alloc.ContainsUnsafe(info->GetMethod())) {
622 info->GetMethod()->SetProfilingInfo(nullptr);
623 FreeData(reinterpret_cast<uint8_t*>(info));
624 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000625 } else {
626 ++it;
627 }
628 }
629 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700630 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100631}
632
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000633bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
634 return kUseReadBarrier
635 ? self->GetWeakRefAccessEnabled()
636 : is_weak_access_enabled_.LoadSequentiallyConsistent();
637}
638
639void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
640 if (IsWeakAccessEnabled(self)) {
641 return;
642 }
643 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000644 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000645 while (!IsWeakAccessEnabled(self)) {
646 inline_cache_cond_.Wait(self);
647 }
648}
649
650void JitCodeCache::BroadcastForInlineCacheAccess() {
651 Thread* self = Thread::Current();
652 MutexLock mu(self, lock_);
653 inline_cache_cond_.Broadcast(self);
654}
655
656void JitCodeCache::AllowInlineCacheAccess() {
657 DCHECK(!kUseReadBarrier);
658 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
659 BroadcastForInlineCacheAccess();
660}
661
662void JitCodeCache::DisallowInlineCacheAccess() {
663 DCHECK(!kUseReadBarrier);
664 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
665}
666
667void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
668 Handle<mirror::ObjectArray<mirror::Class>> array) {
669 WaitUntilInlineCacheAccessible(Thread::Current());
670 // Note that we don't need to lock `lock_` here, the compiler calling
671 // this method has already ensured the inline cache will not be deleted.
672 for (size_t in_cache = 0, in_array = 0;
673 in_cache < InlineCache::kIndividualCacheSize;
674 ++in_cache) {
675 mirror::Class* object = ic.classes_[in_cache].Read();
676 if (object != nullptr) {
677 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000678 }
679 }
680}
681
Mathieu Chartierf044c222017-05-31 15:27:54 -0700682static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
683 if (was_warm) {
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100684 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700685 }
686 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
687 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100688 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
689 // the warmup threshold is 1.
690 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
691 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700692}
693
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100694uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
695 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000696 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700697 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000698 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100699 size_t frame_size_in_bytes,
700 size_t core_spill_mask,
701 size_t fp_spill_mask,
702 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000703 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100704 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000705 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700706 Handle<mirror::ObjectArray<mirror::Object>> roots,
707 bool has_should_deoptimize_flag,
708 const ArenaSet<ArtMethod*>&
709 cha_single_implementation_list) {
Vladimir Markoe7441632017-11-29 13:00:56 +0000710 DCHECK_NE(stack_map != nullptr, method->IsNative());
711 DCHECK(!method->IsNative() || !osr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100712 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
713 // Ensure the header ends up at expected instruction alignment.
714 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
715 size_t total_size = header_size + code_size;
716
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100717 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100718 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000719 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100720 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000721 ScopedThreadSuspension sts(self, kSuspended);
722 MutexLock mu(self, lock_);
723 WaitForPotentialCollectionToComplete(self);
724 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100725 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000726 memory = AllocateCode(total_size);
727 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000728 return nullptr;
729 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100730 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000731
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100732 std::copy(code, code + code_size, code_ptr);
733 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
734 new (method_header) OatQuickMethodHeader(
Vladimir Markoe7441632017-11-29 13:00:56 +0000735 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
736 (method_info != nullptr) ? code_ptr - method_info : 0u,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000737 frame_size_in_bytes,
738 core_spill_mask,
739 fp_spill_mask,
740 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100741 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
742 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
743 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
744 // 6P) stop being supported or their kernels are fixed.
745 //
746 // For reference, this behavior is caused by this commit:
747 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
748 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
749 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700750 DCHECK(!Runtime::Current()->IsAotCompiler());
751 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100752 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700753 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100754 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100755
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000756 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100757 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000758 // We need to update the entry point in the runnable state for the instrumentation.
759 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700760 // Need cha_lock_ for checking all single-implementation flags and register
761 // dependencies.
762 MutexLock cha_mu(self, *Locks::cha_lock_);
763 bool single_impl_still_valid = true;
764 for (ArtMethod* single_impl : cha_single_implementation_list) {
765 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700766 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
767 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700768 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700769 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700770 break;
771 }
772 }
773
774 // Discard the code if any single-implementation assumptions are now invalid.
775 if (!single_impl_still_valid) {
776 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
777 return nullptr;
778 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000779 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800780 << "Should not be using cha on debuggable apps/runs!";
781
Mingyao Yang063fc772016-08-02 11:02:54 -0700782 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700783 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700784 single_impl, method, method_header);
785 }
786
787 // The following needs to be guarded by cha_lock_ also. Otherwise it's
788 // possible that the compiled code is considered invalidated by some class linking,
789 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000790 MutexLock mu(self, lock_);
Vladimir Markoe7441632017-11-29 13:00:56 +0000791 if (UNLIKELY(method->IsNative())) {
792 DCHECK(stack_map == nullptr);
793 DCHECK(roots_data == nullptr);
794 auto it = jni_stubs_map_.find(JniStubKey(method));
795 DCHECK(it != jni_stubs_map_.end())
796 << "Entry inserted in NotifyCompilationOf() should be alive.";
797 JniStubData* data = &it->second;
798 DCHECK(ContainsElement(data->GetMethods(), method))
799 << "Entry inserted in NotifyCompilationOf() should contain this method.";
800 data->SetCode(code_ptr);
801 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
802 for (ArtMethod* m : data->GetMethods()) {
803 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
804 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100805 } else {
Vladimir Markoe7441632017-11-29 13:00:56 +0000806 // Fill the root table before updating the entry point.
807 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
808 DCHECK_LE(roots_data, stack_map);
809 FillRootTable(roots_data, roots);
810 {
811 // Flush data cache, as compiled code references literals in it.
812 // We also need a TLB shootdown to act as memory barrier across cores.
813 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
814 FlushDataCache(reinterpret_cast<char*>(roots_data),
815 reinterpret_cast<char*>(roots_data + data_size));
816 }
817 method_code_map_.Put(code_ptr, method);
818 if (osr) {
819 number_of_osr_compilations_++;
820 osr_code_map_.Put(method, code_ptr);
821 } else {
822 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
823 method, method_header->GetEntryPoint());
824 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000825 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000826 if (collection_in_progress_) {
827 // We need to update the live bitmap if there is a GC to ensure it sees this new
828 // code.
829 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
830 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000831 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000832 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100833 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700834 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000835 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
836 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
837 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700838 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
839 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000840 histogram_code_memory_use_.AddValue(code_size);
841 if (code_size > kCodeSizeLogThreshold) {
842 LOG(INFO) << "JIT allocated "
843 << PrettySize(code_size)
844 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700845 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000846 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000847 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100848
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100849 return reinterpret_cast<uint8_t*>(method_header);
850}
851
852size_t JitCodeCache::CodeCacheSize() {
853 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000854 return CodeCacheSizeLocked();
855}
856
Orion Hodsoneced6922017-06-01 10:54:28 +0100857bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Markoe7441632017-11-29 13:00:56 +0000858 // This function is used only for testing and only with non-native methods.
859 CHECK(!method->IsNative());
860
Orion Hodsoneced6922017-06-01 10:54:28 +0100861 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100862
Vladimir Markoe7441632017-11-29 13:00:56 +0000863 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
864 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100865
866 if (!in_cache) {
867 return false;
868 }
869
Orion Hodsoneced6922017-06-01 10:54:28 +0100870 method->ClearCounter();
871 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
872 method, GetQuickToInterpreterBridge());
873 VLOG(jit)
874 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
875 << ArtMethod::PrettyMethod(method) << "@" << method
876 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
877 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
878 return true;
879}
880
Vladimir Markoe7441632017-11-29 13:00:56 +0000881bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
882 if (LIKELY(!method->IsNative())) {
883 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
884 if (info != nullptr) {
885 RemoveElement(profiling_infos_, info);
886 }
887 method->SetProfilingInfo(nullptr);
888 }
889
890 bool in_cache = false;
891 ScopedCodeCacheWrite ccw(code_map_.get());
892 if (UNLIKELY(method->IsNative())) {
893 auto it = jni_stubs_map_.find(JniStubKey(method));
894 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
895 in_cache = true;
896 if (it->second.GetMethods().empty()) {
897 if (release_memory) {
898 FreeCode(it->second.GetCode());
899 }
900 jni_stubs_map_.erase(it);
901 } else {
902 it->first.UpdateShorty(it->second.GetMethods().front());
903 }
904 }
905 } else {
906 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
907 if (it->second == method) {
908 in_cache = true;
909 if (release_memory) {
910 FreeCode(it->first);
911 }
912 it = method_code_map_.erase(it);
913 } else {
914 ++it;
915 }
916 }
917
918 auto osr_it = osr_code_map_.find(method);
919 if (osr_it != osr_code_map_.end()) {
920 osr_code_map_.erase(osr_it);
921 }
922 }
923
924 return in_cache;
925}
926
Alex Lightdba61482016-12-21 08:20:29 -0800927// This notifies the code cache that the given method has been redefined and that it should remove
928// any cached information it has on the method. All threads must be suspended before calling this
929// method. The compiled code for the method (if there is any) must not be in any threads call stack.
930void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
931 MutexLock mu(Thread::Current(), lock_);
Vladimir Markoe7441632017-11-29 13:00:56 +0000932 RemoveMethodLocked(method, /* release_memory */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800933}
934
935// This invalidates old_method. Once this function returns one can no longer use old_method to
936// execute code unless it is fixed up. This fixup will happen later in the process of installing a
937// class redefinition.
938// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
939// shouldn't be used since it is no longer logically in the jit code cache.
940// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
941void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Markoe7441632017-11-29 13:00:56 +0000942 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000943 if (old_method->IsNative()) {
Vladimir Markoe7441632017-11-29 13:00:56 +0000944 // Update methods in jni_stubs_map_.
945 for (auto& entry : jni_stubs_map_) {
946 JniStubData& data = entry.second;
947 data.MoveObsoleteMethod(old_method, new_method);
948 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000949 return;
950 }
Alex Lightdba61482016-12-21 08:20:29 -0800951 // Update ProfilingInfo to the new one and remove it from the old_method.
952 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
953 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
954 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
955 old_method->SetProfilingInfo(nullptr);
956 // Since the JIT should be paused and all threads suspended by the time this is called these
957 // checks should always pass.
958 DCHECK(!info->IsInUseByCompiler());
959 new_method->SetProfilingInfo(info);
960 info->method_ = new_method;
961 }
962 // Update method_code_map_ to point to the new method.
963 for (auto& it : method_code_map_) {
964 if (it.second == old_method) {
965 it.second = new_method;
966 }
967 }
968 // Update osr_code_map_ to point to the new method.
969 auto code_map = osr_code_map_.find(old_method);
970 if (code_map != osr_code_map_.end()) {
971 osr_code_map_.Put(new_method, code_map->second);
972 osr_code_map_.erase(old_method);
973 }
974}
975
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000976size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000977 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100978}
979
980size_t JitCodeCache::DataCacheSize() {
981 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000982 return DataCacheSizeLocked();
983}
984
985size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000986 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800987}
988
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000989void JitCodeCache::ClearData(Thread* self,
990 uint8_t* stack_map_data,
991 uint8_t* roots_data) {
992 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000993 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000994 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000995}
996
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000997size_t JitCodeCache::ReserveData(Thread* self,
998 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700999 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001000 size_t number_of_roots,
1001 ArtMethod* method,
1002 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001003 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001004 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001005 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001006 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001007 uint8_t* result = nullptr;
1008
1009 {
1010 ScopedThreadSuspension sts(self, kSuspended);
1011 MutexLock mu(self, lock_);
1012 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001013 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001014 }
1015
1016 if (result == nullptr) {
1017 // Retry.
1018 GarbageCollectCache(self);
1019 ScopedThreadSuspension sts(self, kSuspended);
1020 MutexLock mu(self, lock_);
1021 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001022 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001023 }
1024
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001025 MutexLock mu(self, lock_);
1026 histogram_stack_map_memory_use_.AddValue(size);
1027 if (size > kStackMapSizeLogThreshold) {
1028 LOG(INFO) << "JIT allocated "
1029 << PrettySize(size)
1030 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001031 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001032 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001033 if (result != nullptr) {
1034 *roots_data = result;
1035 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001036 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001037 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001038 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001039 } else {
1040 *roots_data = nullptr;
1041 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001042 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001043 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001044 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001045}
1046
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001047class MarkCodeVisitor FINAL : public StackVisitor {
1048 public:
1049 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1050 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1051 code_cache_(code_cache_in),
1052 bitmap_(code_cache_->GetLiveBitmap()) {}
1053
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001054 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001055 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1056 if (method_header == nullptr) {
1057 return true;
1058 }
1059 const void* code = method_header->GetCode();
1060 if (code_cache_->ContainsPc(code)) {
1061 // Use the atomic set version, as multiple threads are executing this code.
1062 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1063 }
1064 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001065 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001066
1067 private:
1068 JitCodeCache* const code_cache_;
1069 CodeCacheBitmap* const bitmap_;
1070};
1071
1072class MarkCodeClosure FINAL : public Closure {
1073 public:
1074 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1075 : code_cache_(code_cache), barrier_(barrier) {}
1076
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001077 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001078 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001079 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1080 MarkCodeVisitor visitor(thread, code_cache_);
1081 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001082 if (kIsDebugBuild) {
1083 // The stack walking code queries the side instrumentation stack if it
1084 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1085 // must have been seen. We sanity check this below.
1086 for (const instrumentation::InstrumentationStackFrame& frame
1087 : *thread->GetInstrumentationStack()) {
1088 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1089 // its stack frame, it is not the method owning return_pc_. We just pass null to
1090 // LookupMethodHeader: the method is only checked against in debug builds.
1091 OatQuickMethodHeader* method_header =
Vladimir Markoe7441632017-11-29 13:00:56 +00001092 code_cache_->LookupMethodHeader(frame.return_pc_, /* method */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001093 if (method_header != nullptr) {
1094 const void* code = method_header->GetCode();
1095 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1096 }
1097 }
1098 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001099 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001100 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001101
1102 private:
1103 JitCodeCache* const code_cache_;
1104 Barrier* const barrier_;
1105};
1106
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001107void JitCodeCache::NotifyCollectionDone(Thread* self) {
1108 collection_in_progress_ = false;
1109 lock_cond_.Broadcast(self);
1110}
1111
1112void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1113 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001114 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001115 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1116 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1117 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001118 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001119 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1120 }
1121}
1122
1123bool JitCodeCache::IncreaseCodeCacheCapacity() {
1124 if (current_capacity_ == max_capacity_) {
1125 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001126 }
1127
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001128 // Double the capacity if we're below 1MB, or increase it by 1MB if
1129 // we're above.
1130 if (current_capacity_ < 1 * MB) {
1131 current_capacity_ *= 2;
1132 } else {
1133 current_capacity_ += 1 * MB;
1134 }
1135 if (current_capacity_ > max_capacity_) {
1136 current_capacity_ = max_capacity_;
1137 }
1138
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001139 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001140
1141 SetFootprintLimit(current_capacity_);
1142
1143 return true;
1144}
1145
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001146void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1147 Barrier barrier(0);
1148 size_t threads_running_checkpoint = 0;
1149 MarkCodeClosure closure(this, &barrier);
1150 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1151 // Now that we have run our checkpoint, move to a suspended state and wait
1152 // for other threads to run the checkpoint.
1153 ScopedThreadSuspension sts(self, kSuspended);
1154 if (threads_running_checkpoint != 0) {
1155 barrier.Increment(self, threads_running_checkpoint);
1156 }
1157}
1158
Nicolas Geoffray35122442016-03-02 12:05:30 +00001159bool JitCodeCache::ShouldDoFullCollection() {
1160 if (current_capacity_ == max_capacity_) {
1161 // Always do a full collection when the code cache is full.
1162 return true;
1163 } else if (current_capacity_ < kReservedCapacity) {
1164 // Always do partial collection when the code cache size is below the reserved
1165 // capacity.
1166 return false;
1167 } else if (last_collection_increased_code_cache_) {
1168 // This time do a full collection.
1169 return true;
1170 } else {
1171 // This time do a partial collection.
1172 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001173 }
1174}
1175
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001176void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001177 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001178 if (!garbage_collect_code_) {
1179 MutexLock mu(self, lock_);
1180 IncreaseCodeCacheCapacity();
1181 return;
1182 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001183
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001184 // Wait for an existing collection, or let everyone know we are starting one.
1185 {
1186 ScopedThreadSuspension sts(self, kSuspended);
1187 MutexLock mu(self, lock_);
1188 if (WaitForPotentialCollectionToComplete(self)) {
1189 return;
1190 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001191 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001192 live_bitmap_.reset(CodeCacheBitmap::Create(
1193 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001194 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1195 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001196 collection_in_progress_ = true;
1197 }
1198 }
1199
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001200 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001201 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001202 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001203
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001204 bool do_full_collection = false;
1205 {
1206 MutexLock mu(self, lock_);
1207 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001208 }
1209
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001210 VLOG(jit) << "Do "
1211 << (do_full_collection ? "full" : "partial")
1212 << " code cache collection, code="
1213 << PrettySize(CodeCacheSize())
1214 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001215
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001216 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1217
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001218 VLOG(jit) << "After code cache collection, code="
1219 << PrettySize(CodeCacheSize())
1220 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001221
1222 {
1223 MutexLock mu(self, lock_);
1224
1225 // Increase the code cache only when we do partial collections.
1226 // TODO: base this strategy on how full the code cache is?
1227 if (do_full_collection) {
1228 last_collection_increased_code_cache_ = false;
1229 } else {
1230 last_collection_increased_code_cache_ = true;
1231 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001232 }
1233
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001234 bool next_collection_will_be_full = ShouldDoFullCollection();
1235
1236 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001237 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001238 // Save the entry point of methods we have compiled, and update the entry
1239 // point of those methods to the interpreter. If the method is invoked, the
1240 // interpreter will update its entry point to the compiled code and call it.
1241 for (ProfilingInfo* info : profiling_infos_) {
1242 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1243 if (ContainsPc(entry_point)) {
1244 info->SetSavedEntryPoint(entry_point);
Vladimir Markoe7441632017-11-29 13:00:56 +00001245 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001246 // class of the method. We may be concurrently running a GC which makes accessing
1247 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1248 // checked that the current entry point is JIT compiled code.
1249 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001250 }
1251 }
1252
1253 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Markoe7441632017-11-29 13:00:56 +00001254
1255 // Change entry points of native methods back to the GenericJNI entrypoint.
1256 for (const auto& entry : jni_stubs_map_) {
1257 const JniStubData& data = entry.second;
1258 if (!data.IsCompiled()) {
1259 continue;
1260 }
1261 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1262 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1263 const OatQuickMethodHeader* method_header =
1264 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1265 for (ArtMethod* method : data.GetMethods()) {
1266 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1267 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1268 method->SetCounter(new_counter);
1269 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1270 }
1271 }
1272 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001273 }
1274 live_bitmap_.reset(nullptr);
1275 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001276 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001277 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001278 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001279}
1280
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001281void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001282 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001283 std::unordered_set<OatQuickMethodHeader*> method_headers;
1284 {
1285 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001286 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001287 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Markoe7441632017-11-29 13:00:56 +00001288 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1289 JniStubData* data = &it->second;
1290 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1291 ++it;
1292 } else {
1293 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1294 it = jni_stubs_map_.erase(it);
1295 }
1296 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001297 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1298 const void* code_ptr = it->first;
1299 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1300 if (GetLiveBitmap()->Test(allocation)) {
1301 ++it;
1302 } else {
Vladimir Markoe7441632017-11-29 13:00:56 +00001303 method_headers.insert(OatQuickMethodHeader::FromCodePointer(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001304 it = method_code_map_.erase(it);
1305 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001306 }
1307 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001308 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001309}
1310
1311void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001312 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001313 {
1314 MutexLock mu(self, lock_);
1315 if (collect_profiling_info) {
1316 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1317 // Also remove the saved entry point from the ProfilingInfo objects.
1318 for (ProfilingInfo* info : profiling_infos_) {
1319 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001320 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001321 info->GetMethod()->SetProfilingInfo(nullptr);
1322 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001323
1324 if (info->GetSavedEntryPoint() != nullptr) {
1325 info->SetSavedEntryPoint(nullptr);
1326 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001327 // give it a chance to be hot again.
1328 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001329 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001330 }
1331 } else if (kIsDebugBuild) {
1332 // Sanity check that the profiling infos do not have a dangling entry point.
1333 for (ProfilingInfo* info : profiling_infos_) {
1334 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001335 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001336 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001337
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001338 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1339 // an entry point is either:
1340 // - an osr compiled code, that will be removed if not in a thread call stack.
1341 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Markoe7441632017-11-29 13:00:56 +00001342 for (const auto& entry : jni_stubs_map_) {
1343 const JniStubData& data = entry.second;
1344 const void* code_ptr = data.GetCode();
1345 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1346 for (ArtMethod* method : data.GetMethods()) {
1347 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1348 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1349 break;
1350 }
1351 }
1352 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001353 for (const auto& it : method_code_map_) {
1354 ArtMethod* method = it.second;
1355 const void* code_ptr = it.first;
1356 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1357 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1358 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1359 }
1360 }
1361
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001362 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001363 // on thread stacks).
1364 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001365 }
1366
1367 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001368 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001369
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001370 // At this point, mutator threads are still running, and entrypoints of methods can
1371 // change. We do know they cannot change to a code cache entry that is not marked,
1372 // therefore we can safely remove those entries.
1373 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001374
Nicolas Geoffray35122442016-03-02 12:05:30 +00001375 if (collect_profiling_info) {
1376 MutexLock mu(self, lock_);
1377 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001378 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001379 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001380 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001381 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1382 // that the compiled code would not get revived. As mutator threads run concurrently,
1383 // they may have revived the compiled code, and now we are in the situation where
1384 // a method has compiled code but no ProfilingInfo.
1385 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1386 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001387 if (ContainsPc(ptr) &&
1388 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001389 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001390 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001391 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001392 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001393 return true;
1394 }
1395 return false;
1396 });
1397 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001398 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001399 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001400}
1401
Nicolas Geoffray35122442016-03-02 12:05:30 +00001402bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001403 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001404 // Check that methods we have compiled do have a ProfilingInfo object. We would
1405 // have memory leaks of compiled code otherwise.
1406 for (const auto& it : method_code_map_) {
1407 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001408 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001409 const void* code_ptr = it.first;
1410 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1411 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1412 // If the code is not dead, then we have a problem. Note that this can even
1413 // happen just after a collection, as mutator threads are running in parallel
1414 // and could deoptimize an existing compiled code.
1415 return false;
1416 }
1417 }
1418 }
1419 return true;
1420}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001421
1422OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001423 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1424 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001425 // On Thumb-2, the pc is offset by one.
1426 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001427 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001428 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1429 return nullptr;
1430 }
1431
Vladimir Markoe7441632017-11-29 13:00:56 +00001432 if (!kIsDebugBuild) {
1433 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1434 CHECK(method != nullptr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001435 }
Vladimir Marko3417eae2017-09-21 18:14:28 +01001436
Vladimir Markoe7441632017-11-29 13:00:56 +00001437 MutexLock mu(Thread::Current(), lock_);
1438 OatQuickMethodHeader* method_header = nullptr;
1439 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1440 if (method != nullptr && UNLIKELY(method->IsNative())) {
1441 auto it = jni_stubs_map_.find(JniStubKey(method));
1442 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1443 return nullptr;
1444 }
1445 const void* code_ptr = it->second.GetCode();
1446 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1447 if (!method_header->Contains(pc)) {
1448 return nullptr;
1449 }
1450 } else {
1451 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1452 if (it != method_code_map_.begin()) {
1453 --it;
1454 const void* code_ptr = it->first;
1455 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1456 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1457 found_method = it->second;
1458 }
1459 }
1460 if (method_header == nullptr && method == nullptr) {
1461 // Scan all compiled JNI stubs as well. This slow search is used only
1462 // for checks in debug build, for release builds the `method` is not null.
1463 for (auto&& entry : jni_stubs_map_) {
1464 const JniStubData& data = entry.second;
1465 if (data.IsCompiled() &&
1466 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1467 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1468 }
1469 }
1470 }
1471 if (method_header == nullptr) {
1472 return nullptr;
1473 }
Vladimir Marko47d31852017-11-28 18:36:12 +00001474 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001475
1476 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001477 // When we are walking the stack to redefine classes and creating obsolete methods it is
1478 // possible that we might have updated the method_code_map by making this method obsolete in a
1479 // previous frame. Therefore we should just check that the non-obsolete version of this method
1480 // is the one we expect. We change to the non-obsolete versions in the error message since the
1481 // obsolete version of the method might not be fully initialized yet. This situation can only
1482 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001483 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001484 // information.)
Vladimir Markoe7441632017-11-29 13:00:56 +00001485 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001486 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Markoe7441632017-11-29 13:00:56 +00001487 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001488 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001489 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001490 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001491}
1492
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001493OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1494 MutexLock mu(Thread::Current(), lock_);
1495 auto it = osr_code_map_.find(method);
1496 if (it == osr_code_map_.end()) {
1497 return nullptr;
1498 }
1499 return OatQuickMethodHeader::FromCodePointer(it->second);
1500}
1501
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001502ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1503 ArtMethod* method,
1504 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001505 bool retry_allocation)
1506 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1507 NO_THREAD_SAFETY_ANALYSIS {
1508 ProfilingInfo* info = nullptr;
1509 if (!retry_allocation) {
1510 // If we are allocating for the interpreter, just try to lock, to avoid
1511 // lock contention with the JIT.
1512 if (lock_.ExclusiveTryLock(self)) {
1513 info = AddProfilingInfoInternal(self, method, entries);
1514 lock_.ExclusiveUnlock(self);
1515 }
1516 } else {
1517 {
1518 MutexLock mu(self, lock_);
1519 info = AddProfilingInfoInternal(self, method, entries);
1520 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001521
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001522 if (info == nullptr) {
1523 GarbageCollectCache(self);
1524 MutexLock mu(self, lock_);
1525 info = AddProfilingInfoInternal(self, method, entries);
1526 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001527 }
1528 return info;
1529}
1530
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001531ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001532 ArtMethod* method,
1533 const std::vector<uint32_t>& entries) {
1534 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001535 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001536 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001537
1538 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001539 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001540 if (info != nullptr) {
1541 return info;
1542 }
1543
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001544 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001545 if (data == nullptr) {
1546 return nullptr;
1547 }
1548 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001549
1550 // Make sure other threads see the data in the profiling info object before the
1551 // store in the ArtMethod's ProfilingInfo pointer.
1552 QuasiAtomic::ThreadFenceRelease();
1553
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001554 method->SetProfilingInfo(info);
1555 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001556 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001557 return info;
1558}
1559
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001560// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1561// is already held.
1562void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1563 if (code_mspace_ == mspace) {
1564 size_t result = code_end_;
1565 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001566 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001567 } else {
1568 DCHECK_EQ(data_mspace_, mspace);
1569 size_t result = data_end_;
1570 data_end_ += increment;
1571 return reinterpret_cast<void*>(result + data_map_->Begin());
1572 }
1573}
1574
Calin Juravle99629622016-04-19 16:33:46 +01001575void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001576 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001577 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001578 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001579 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001580 for (const ProfilingInfo* info : profiling_infos_) {
1581 ArtMethod* method = info->GetMethod();
1582 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001583 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1584 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001585 // Skip dex files which are not profiled.
1586 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001587 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001588 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001589
1590 // If the method didn't reach the compilation threshold don't save the inline caches.
1591 // They might be incomplete and cause unnecessary deoptimizations.
1592 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1593 if (method->GetCounter() < jit_compile_threshold) {
1594 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001595 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001596 continue;
1597 }
1598
Calin Juravle940eb0c2017-01-30 19:30:44 -08001599 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001600 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001601 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001602 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001603 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001604 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1605 mirror::Class* cls = cache.classes_[k].Read();
1606 if (cls == nullptr) {
1607 break;
1608 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001609
Calin Juravle13439f02017-02-21 01:17:21 -08001610 // Check if the receiver is in the boot class path or if it's in the
1611 // same class loader as the caller. If not, skip it, as there is not
1612 // much we can do during AOT.
1613 if (!cls->IsBootStrapClassLoaded() &&
1614 caller->GetClassLoader() != cls->GetClassLoader()) {
1615 is_missing_types = true;
1616 continue;
1617 }
1618
Calin Juravle4ca70a32017-02-21 16:22:24 -08001619 const DexFile* class_dex_file = nullptr;
1620 dex::TypeIndex type_index;
1621
1622 if (cls->GetDexCache() == nullptr) {
1623 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001624 // Make a best effort to find the type index in the method's dex file.
1625 // We could search all open dex files but that might turn expensive
1626 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001627 class_dex_file = dex_file;
1628 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1629 } else {
1630 class_dex_file = &(cls->GetDexFile());
1631 type_index = cls->GetDexTypeIndex();
1632 }
1633 if (!type_index.IsValid()) {
1634 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001635 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001636 continue;
1637 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001638 if (ContainsElement(dex_base_locations,
1639 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001640 // Only consider classes from the same apk (including multidex).
1641 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001642 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001643 } else {
1644 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001645 }
1646 }
1647 if (!profile_classes.empty()) {
1648 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001649 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001650 }
1651 }
1652 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001653 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001654 }
1655}
1656
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001657uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1658 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001659}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001660
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001661bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1662 MutexLock mu(Thread::Current(), lock_);
1663 return osr_code_map_.find(method) != osr_code_map_.end();
1664}
1665
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001666bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1667 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001668 return false;
1669 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001670
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001671 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001672 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1673 return false;
1674 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001675
Vladimir Markoe7441632017-11-29 13:00:56 +00001676 if (UNLIKELY(method->IsNative())) {
1677 JniStubKey key(method);
1678 auto it = jni_stubs_map_.find(key);
1679 bool new_compilation = false;
1680 if (it == jni_stubs_map_.end()) {
1681 // Create a new entry to mark the stub as being compiled.
1682 it = jni_stubs_map_.Put(key, JniStubData{});
1683 new_compilation = true;
1684 }
1685 JniStubData* data = &it->second;
1686 data->AddMethod(method);
1687 if (data->IsCompiled()) {
1688 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1689 const void* entrypoint = method_header->GetEntryPoint();
1690 // Update also entrypoints of other methods held by the JniStubData.
1691 // We could simply update the entrypoint of `method` but if the last JIT GC has
1692 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1693 // as well change them back as this stub shall not be collected anyway and this
1694 // can avoid a few expensive GenericJNI calls.
1695 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1696 for (ArtMethod* m : data->GetMethods()) {
1697 instrumentation->UpdateMethodsCode(m, entrypoint);
1698 }
1699 if (collection_in_progress_) {
1700 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1701 }
1702 }
1703 return new_compilation;
1704 } else {
1705 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1706 if (info == nullptr) {
1707 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1708 // Because the counter is not atomic, there are some rare cases where we may not hit the
1709 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1710 ClearMethodCounter(method, /*was_warm*/ false);
1711 return false;
1712 }
Vladimir Marko47d31852017-11-28 18:36:12 +00001713
Vladimir Markoe7441632017-11-29 13:00:56 +00001714 if (info->IsMethodBeingCompiled(osr)) {
1715 return false;
1716 }
Vladimir Marko47d31852017-11-28 18:36:12 +00001717
Vladimir Markoe7441632017-11-29 13:00:56 +00001718 info->SetIsMethodBeingCompiled(true, osr);
1719 return true;
1720 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001721}
1722
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001723ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001724 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001725 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001726 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001727 if (!info->IncrementInlineUse()) {
1728 // Overflow of inlining uses, just bail.
1729 return nullptr;
1730 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001731 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001732 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001733}
1734
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001735void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001736 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001737 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001738 DCHECK(info != nullptr);
1739 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001740}
1741
Vladimir Markoe7441632017-11-29 13:00:56 +00001742void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1743 DCHECK_EQ(Thread::Current(), self);
1744 MutexLock mu(self, lock_);
1745 if (UNLIKELY(method->IsNative())) {
1746 auto it = jni_stubs_map_.find(JniStubKey(method));
1747 DCHECK(it != jni_stubs_map_.end());
1748 JniStubData* data = &it->second;
1749 DCHECK(ContainsElement(data->GetMethods(), method));
1750 if (UNLIKELY(!data->IsCompiled())) {
1751 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1752 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1753 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1754 } else {
1755 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1756 DCHECK(info->IsMethodBeingCompiled(osr));
1757 info->SetIsMethodBeingCompiled(false, osr);
1758 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001759}
1760
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001761size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1762 MutexLock mu(Thread::Current(), lock_);
1763 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1764}
1765
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001766void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1767 const OatQuickMethodHeader* header) {
Vladimir Markoe7441632017-11-29 13:00:56 +00001768 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001769 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001770 if ((profiling_info != nullptr) &&
1771 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1772 // Prevent future uses of the compiled code.
1773 profiling_info->SetSavedEntryPoint(nullptr);
1774 }
1775
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001776 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001777 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001778 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001779 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1780 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001781 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001782 } else {
1783 MutexLock mu(Thread::Current(), lock_);
1784 auto it = osr_code_map_.find(method);
1785 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1786 // Remove the OSR method, to avoid using it again.
1787 osr_code_map_.erase(it);
1788 }
1789 }
1790}
1791
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001792uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1793 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1794 uint8_t* result = reinterpret_cast<uint8_t*>(
1795 mspace_memalign(code_mspace_, alignment, code_size));
1796 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1797 // Ensure the header ends up at expected instruction alignment.
1798 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1799 used_memory_for_code_ += mspace_usable_size(result);
1800 return result;
1801}
1802
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001803void JitCodeCache::FreeCode(uint8_t* code) {
1804 used_memory_for_code_ -= mspace_usable_size(code);
1805 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001806}
1807
1808uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1809 void* result = mspace_malloc(data_mspace_, data_size);
1810 used_memory_for_data_ += mspace_usable_size(result);
1811 return reinterpret_cast<uint8_t*>(result);
1812}
1813
1814void JitCodeCache::FreeData(uint8_t* data) {
1815 used_memory_for_data_ -= mspace_usable_size(data);
1816 mspace_free(data_mspace_, data);
1817}
1818
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001819void JitCodeCache::Dump(std::ostream& os) {
1820 MutexLock mu(Thread::Current(), lock_);
1821 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1822 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1823 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Markoe7441632017-11-29 13:00:56 +00001824 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001825 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1826 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1827 << "Total number of JIT compilations for on stack replacement: "
1828 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001829 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001830 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1831 histogram_code_memory_use_.PrintMemoryUse(os);
1832 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001833}
1834
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001835} // namespace jit
1836} // namespace art