blob: 1c4b93eb4805bbf6b3fa35239e6665d93f0c8fbf [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"
Andreas Gampe170331f2017-12-07 18:41:03 -080024#include "base/logging.h" // For VLOG.
David Sehrc431b9d2018-03-02 12:01:51 -080025#include "base/quasi_atomic.h"
Calin Juravle66f55232015-12-08 15:09:10 +000026#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010028#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070029#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000030#include "debugger_interface.h"
David Sehr9e734c72018-01-04 17:56:19 -080031#include "dex/dex_file_loader.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "entrypoints/runtime_asm_entrypoints.h"
33#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010034#include "gc/scoped_gc_critical_section.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000035#include "handle.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070036#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000037#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000038#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010039#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080040#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080041#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070042#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070043#include "object_callbacks.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000044#include "profile_compilation_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070045#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070046#include "stack.h"
Vladimir Markob0b68cf2017-11-14 18:11:50 +000047#include "thread-current-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010048#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080049
50namespace art {
51namespace jit {
52
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010053static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
54static constexpr int kProtData = PROT_READ | PROT_WRITE;
55static constexpr int kProtCode = PROT_READ | PROT_EXEC;
56
Nicolas Geoffray933330a2016-03-16 14:20:06 +000057static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
58static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
59
Vladimir Marko2196c652017-11-30 16:16:07 +000060class JitCodeCache::JniStubKey {
61 public:
62 explicit JniStubKey(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_)
63 : shorty_(method->GetShorty()),
64 is_static_(method->IsStatic()),
65 is_fast_native_(method->IsFastNative()),
66 is_critical_native_(method->IsCriticalNative()),
67 is_synchronized_(method->IsSynchronized()) {
68 DCHECK(!(is_fast_native_ && is_critical_native_));
69 }
70
71 bool operator<(const JniStubKey& rhs) const {
72 if (is_static_ != rhs.is_static_) {
73 return rhs.is_static_;
74 }
75 if (is_synchronized_ != rhs.is_synchronized_) {
76 return rhs.is_synchronized_;
77 }
78 if (is_fast_native_ != rhs.is_fast_native_) {
79 return rhs.is_fast_native_;
80 }
81 if (is_critical_native_ != rhs.is_critical_native_) {
82 return rhs.is_critical_native_;
83 }
84 return strcmp(shorty_, rhs.shorty_) < 0;
85 }
86
87 // Update the shorty to point to another method's shorty. Call this function when removing
88 // the method that references the old shorty from JniCodeData and not removing the entire
89 // JniCodeData; the old shorty may become a dangling pointer when that method is unloaded.
90 void UpdateShorty(ArtMethod* method) const REQUIRES_SHARED(Locks::mutator_lock_) {
91 const char* shorty = method->GetShorty();
92 DCHECK_STREQ(shorty_, shorty);
93 shorty_ = shorty;
94 }
95
96 private:
97 // The shorty points to a DexFile data and may need to change
98 // to point to the same shorty in a different DexFile.
99 mutable const char* shorty_;
100
101 const bool is_static_;
102 const bool is_fast_native_;
103 const bool is_critical_native_;
104 const bool is_synchronized_;
105};
106
107class JitCodeCache::JniStubData {
108 public:
109 JniStubData() : code_(nullptr), methods_() {}
110
111 void SetCode(const void* code) {
112 DCHECK(code != nullptr);
113 code_ = code;
114 }
115
116 const void* GetCode() const {
117 return code_;
118 }
119
120 bool IsCompiled() const {
121 return GetCode() != nullptr;
122 }
123
124 void AddMethod(ArtMethod* method) {
125 if (!ContainsElement(methods_, method)) {
126 methods_.push_back(method);
127 }
128 }
129
130 const std::vector<ArtMethod*>& GetMethods() const {
131 return methods_;
132 }
133
134 void RemoveMethodsIn(const LinearAlloc& alloc) {
135 auto kept_end = std::remove_if(
136 methods_.begin(),
137 methods_.end(),
138 [&alloc](ArtMethod* method) { return alloc.ContainsUnsafe(method); });
139 methods_.erase(kept_end, methods_.end());
140 }
141
142 bool RemoveMethod(ArtMethod* method) {
143 auto it = std::find(methods_.begin(), methods_.end(), method);
144 if (it != methods_.end()) {
145 methods_.erase(it);
146 return true;
147 } else {
148 return false;
149 }
150 }
151
152 void MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
153 std::replace(methods_.begin(), methods_.end(), old_method, new_method);
154 }
155
156 private:
157 const void* code_;
158 std::vector<ArtMethod*> methods_;
159};
160
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000161JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
162 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000163 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000164 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800165 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100166 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000167
David Sehrd1dbb742017-07-17 11:20:38 -0700168 // Generating debug information is for using the Linux perf tool on
169 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +0100170 // Also, target linux does not support ashmem.
171 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -0700172
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000173 // With 'perf', we want a 1-1 mapping between an address and a method.
174 bool garbage_collect_code = !generate_debug_info;
175
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000176 // We need to have 32 bit offsets from method headers in code cache which point to things
177 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
178 // Ensure we're below 1 GB to be safe.
179 if (max_capacity > 1 * GB) {
180 std::ostringstream oss;
181 oss << "Maxium code cache capacity is limited to 1 GB, "
182 << PrettySize(max_capacity) << " is too big";
183 *error_msg = oss.str();
184 return nullptr;
185 }
186
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800187 std::string error_str;
188 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000189 // Map in low 4gb to simplify accessing root tables for x86_64.
190 // We could do PC-relative addressing to avoid this problem, but that
191 // would require reserving code and data area before submitting, which
192 // means more windows for the code memory to be RWX.
Andreas Gampee4deaf32017-06-09 15:27:15 -0700193 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000194 "data-code-cache", nullptr,
195 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700196 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000197 /* low_4gb */ true,
198 /* reuse */ false,
199 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -0700200 use_ashmem));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100201 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800202 std::ostringstream oss;
Andreas Gampee4deaf32017-06-09 15:27:15 -0700203 oss << "Failed to create read write cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800204 *error_msg = oss.str();
205 return nullptr;
206 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100207
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100208 // Align both capacities to page size, as that's the unit mspaces use.
209 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
210 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100211
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100212 // Data cache is 1 / 2 of the map.
213 // TODO: Make this variable?
214 size_t data_size = max_capacity / 2;
215 size_t code_size = max_capacity - data_size;
216 DCHECK_EQ(code_size + data_size, max_capacity);
217 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700218
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100219 MemMap* code_map =
220 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700221 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100222 std::ostringstream oss;
223 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
224 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700225 return nullptr;
226 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100227 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000228 data_size = initial_capacity / 2;
229 code_size = initial_capacity - data_size;
230 DCHECK_EQ(code_size + data_size, initial_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100231 return new JitCodeCache(
232 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800233}
234
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100235JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000236 MemMap* data_map,
237 size_t initial_code_capacity,
238 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000239 size_t max_capacity,
240 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100241 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000242 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100243 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100244 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000245 data_map_(data_map),
246 max_capacity_(max_capacity),
247 current_capacity_(initial_code_capacity + initial_data_capacity),
248 code_end_(initial_code_capacity),
249 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000250 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000251 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000252 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000253 used_memory_for_data_(0),
254 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000255 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000256 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000257 number_of_collections_(0),
258 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
259 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000260 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
261 is_weak_access_enabled_(true),
262 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100263
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000264 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100265 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000266 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100267
268 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
269 PLOG(FATAL) << "create_mspace_with_base failed";
270 }
271
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000272 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100273
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700274 CheckedCall(mprotect,
275 "mprotect jit code cache",
276 code_map_->Begin(),
277 code_map_->Size(),
278 kProtCode);
279 CheckedCall(mprotect,
280 "mprotect jit data cache",
281 data_map_->Begin(),
282 data_map_->Size(),
283 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100284
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000285 VLOG(jit) << "Created jit code cache: initial data size="
286 << PrettySize(initial_data_capacity)
287 << ", initial code size="
288 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800289}
290
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000291JitCodeCache::~JitCodeCache() {}
292
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100293bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100294 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800295}
296
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000297bool JitCodeCache::ContainsMethod(ArtMethod* method) {
298 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000299 if (UNLIKELY(method->IsNative())) {
300 auto it = jni_stubs_map_.find(JniStubKey(method));
301 if (it != jni_stubs_map_.end() &&
302 it->second.IsCompiled() &&
303 ContainsElement(it->second.GetMethods(), method)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000304 return true;
305 }
Vladimir Marko2196c652017-11-30 16:16:07 +0000306 } else {
307 for (const auto& it : method_code_map_) {
308 if (it.second == method) {
309 return true;
310 }
311 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000312 }
313 return false;
314}
315
Vladimir Marko2196c652017-11-30 16:16:07 +0000316const void* JitCodeCache::GetJniStubCode(ArtMethod* method) {
317 DCHECK(method->IsNative());
318 MutexLock mu(Thread::Current(), lock_);
319 auto it = jni_stubs_map_.find(JniStubKey(method));
320 if (it != jni_stubs_map_.end()) {
321 JniStubData& data = it->second;
322 if (data.IsCompiled() && ContainsElement(data.GetMethods(), method)) {
323 return data.GetCode();
324 }
325 }
326 return nullptr;
327}
328
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800329class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100330 public:
Orion Hodson74ed8d32018-03-07 11:19:54 +0000331 explicit ScopedCodeCacheWrite(MemMap* code_map)
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100332 : ScopedTrace("ScopedCodeCacheWrite"),
Orion Hodson74ed8d32018-03-07 11:19:54 +0000333 code_map_(code_map) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800334 ScopedTrace trace("mprotect all");
Orion Hodson74ed8d32018-03-07 11:19:54 +0000335 CheckedCall(mprotect, "make code writable", code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800336 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100337 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800338 ScopedTrace trace("mprotect code");
Orion Hodson74ed8d32018-03-07 11:19:54 +0000339 CheckedCall(mprotect, "make code protected", code_map_->Begin(), code_map_->Size(), kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100340 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700341
David Sehrd1dbb742017-07-17 11:20:38 -0700342 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100343 MemMap* const code_map_;
344
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100345 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
346};
347
348uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100349 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000350 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700351 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000352 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100353 size_t frame_size_in_bytes,
354 size_t core_spill_mask,
355 size_t fp_spill_mask,
356 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000357 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100358 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000359 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700360 Handle<mirror::ObjectArray<mirror::Object>> roots,
361 bool has_should_deoptimize_flag,
362 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100363 uint8_t* result = CommitCodeInternal(self,
364 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000365 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700366 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000367 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100368 frame_size_in_bytes,
369 core_spill_mask,
370 fp_spill_mask,
371 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000372 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100373 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000374 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700375 roots,
376 has_should_deoptimize_flag,
377 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100378 if (result == nullptr) {
379 // Retry.
380 GarbageCollectCache(self);
381 result = CommitCodeInternal(self,
382 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000383 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700384 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000385 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100386 frame_size_in_bytes,
387 core_spill_mask,
388 fp_spill_mask,
389 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000390 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100391 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000392 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700393 roots,
394 has_should_deoptimize_flag,
395 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100396 }
397 return result;
398}
399
400bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
401 bool in_collection = false;
402 while (collection_in_progress_) {
403 in_collection = true;
404 lock_cond_.Wait(self);
405 }
406 return in_collection;
407}
408
409static uintptr_t FromCodeToAllocation(const void* code) {
410 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
411 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
412}
413
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000414static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
415 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
416}
417
418static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
419 // The length of the table is stored just before the stack map (and therefore at the end of
420 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
421 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
422}
423
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800424static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
425 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
426 // pointer.
427 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
428}
429
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000430static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
431 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
432}
433
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000434static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
435 REQUIRES_SHARED(Locks::mutator_lock_) {
436 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800437 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000438 // Put all roots in `roots_data`.
439 for (uint32_t i = 0; i < length; ++i) {
440 ObjPtr<mirror::Object> object = roots->Get(i);
441 if (kIsDebugBuild) {
442 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000443 if (object->IsString()) {
444 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
445 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
446 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
447 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000448 }
449 gc_roots[i] = GcRoot<mirror::Object>(object);
450 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000451}
452
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100453static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000454 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
455 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
456 uint32_t roots = GetNumberOfRoots(data);
457 if (number_of_roots != nullptr) {
458 *number_of_roots = roots;
459 }
460 return data - ComputeRootTableSize(roots);
461}
462
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100463// Use a sentinel for marking entries in the JIT table that have been cleared.
464// This helps diagnosing in case the compiled code tries to wrongly access such
465// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700466static mirror::Class* const weak_sentinel =
467 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100468
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000469// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100470static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
471 IsMarkedVisitor* visitor,
472 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000473 REQUIRES_SHARED(Locks::mutator_lock_) {
474 // This does not need a read barrier because this is called by GC.
475 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100476 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000477 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
478 // Look at the classloader of the class to know if it has been unloaded.
479 // This does not need a read barrier because this is called by GC.
480 mirror::Object* class_loader =
481 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
482 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
483 // The class loader is live, update the entry if the class has moved.
484 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
485 // Note that new_object can be null for CMS and newly allocated objects.
486 if (new_cls != nullptr && new_cls != cls) {
487 *root_ptr = GcRoot<mirror::Class>(new_cls);
488 }
489 } else {
490 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100491 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000492 }
493 }
494}
495
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000496void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
497 MutexLock mu(Thread::Current(), lock_);
498 for (const auto& entry : method_code_map_) {
499 uint32_t number_of_roots = 0;
500 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
501 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
502 for (uint32_t i = 0; i < number_of_roots; ++i) {
503 // This does not need a read barrier because this is called by GC.
504 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100505 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000506 // entry got deleted in a previous sweep.
507 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
508 mirror::Object* new_object = visitor->IsMarked(object);
509 // We know the string is marked because it's a strongly-interned string that
510 // is always alive. The IsMarked implementation of the CMS collector returns
511 // null for newly allocated objects, but we know those haven't moved. Therefore,
512 // only update the entry if we get a different non-null string.
513 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
514 // out of the weak access/creation pause. b/32167580
515 if (new_object != nullptr && new_object != object) {
516 DCHECK(new_object->IsString());
517 roots[i] = GcRoot<mirror::Object>(new_object);
518 }
519 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100520 ProcessWeakClass(
521 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000522 }
523 }
524 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000525 // Walk over inline caches to clear entries containing unloaded classes.
526 for (ProfilingInfo* info : profiling_infos_) {
527 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
528 InlineCache* cache = &info->cache_[i];
529 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100530 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000531 }
532 }
533 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000534}
535
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100536void JitCodeCache::FreeCode(const void* code_ptr) {
537 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000538 // Notify native debugger that we are about to remove the code.
539 // It does nothing if we are not using native debugger.
David Srbeckyfb3de3d2018-01-29 16:11:49 +0000540 MutexLock mu(Thread::Current(), *Locks::native_debug_interface_lock_);
David Srbecky440a9b32018-02-15 17:47:29 +0000541 RemoveNativeDebugInfoForJit(code_ptr);
Vladimir Marko2196c652017-11-30 16:16:07 +0000542 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->IsOptimized()) {
543 FreeData(GetRootTable(code_ptr));
544 } // else this is a JNI stub without any data.
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100545 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100546}
547
Mingyao Yang063fc772016-08-02 11:02:54 -0700548void JitCodeCache::FreeAllMethodHeaders(
549 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
550 {
551 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700552 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700553 ->RemoveDependentsWithMethodHeaders(method_headers);
554 }
555
556 // We need to remove entries in method_headers from CHA dependencies
557 // first since once we do FreeCode() below, the memory can be reused
558 // so it's possible for the same method_header to start representing
559 // different compile code.
560 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100561 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700562 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100563 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700564 }
565}
566
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100567void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800568 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700569 // We use a set to first collect all method_headers whose code need to be
570 // removed. We need to free the underlying code after we remove CHA dependencies
571 // for entries in this set. And it's more efficient to iterate through
572 // the CHA dependency map just once with an unordered_set.
573 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000574 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700575 MutexLock mu(self, lock_);
576 // We do not check if a code cache GC is in progress, as this method comes
577 // with the classlinker_classes_lock_ held, and suspending ourselves could
578 // lead to a deadlock.
579 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100580 ScopedCodeCacheWrite scc(code_map_.get());
Vladimir Marko2196c652017-11-30 16:16:07 +0000581 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
582 it->second.RemoveMethodsIn(alloc);
583 if (it->second.GetMethods().empty()) {
584 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->second.GetCode()));
585 it = jni_stubs_map_.erase(it);
586 } else {
587 it->first.UpdateShorty(it->second.GetMethods().front());
588 ++it;
589 }
590 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700591 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
592 if (alloc.ContainsUnsafe(it->second)) {
593 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
594 it = method_code_map_.erase(it);
595 } else {
596 ++it;
597 }
598 }
599 }
600 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
601 if (alloc.ContainsUnsafe(it->first)) {
602 // Note that the code has already been pushed to method_headers in the loop
603 // above and is going to be removed in FreeCode() below.
604 it = osr_code_map_.erase(it);
605 } else {
606 ++it;
607 }
608 }
609 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
610 ProfilingInfo* info = *it;
611 if (alloc.ContainsUnsafe(info->GetMethod())) {
612 info->GetMethod()->SetProfilingInfo(nullptr);
613 FreeData(reinterpret_cast<uint8_t*>(info));
614 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000615 } else {
616 ++it;
617 }
618 }
619 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700620 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100621}
622
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000623bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
624 return kUseReadBarrier
625 ? self->GetWeakRefAccessEnabled()
Orion Hodson88591fe2018-03-06 13:35:43 +0000626 : is_weak_access_enabled_.load(std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000627}
628
629void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
630 if (IsWeakAccessEnabled(self)) {
631 return;
632 }
633 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000634 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000635 while (!IsWeakAccessEnabled(self)) {
636 inline_cache_cond_.Wait(self);
637 }
638}
639
640void JitCodeCache::BroadcastForInlineCacheAccess() {
641 Thread* self = Thread::Current();
642 MutexLock mu(self, lock_);
643 inline_cache_cond_.Broadcast(self);
644}
645
646void JitCodeCache::AllowInlineCacheAccess() {
647 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000648 is_weak_access_enabled_.store(true, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000649 BroadcastForInlineCacheAccess();
650}
651
652void JitCodeCache::DisallowInlineCacheAccess() {
653 DCHECK(!kUseReadBarrier);
Orion Hodson88591fe2018-03-06 13:35:43 +0000654 is_weak_access_enabled_.store(false, std::memory_order_seq_cst);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000655}
656
657void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
658 Handle<mirror::ObjectArray<mirror::Class>> array) {
659 WaitUntilInlineCacheAccessible(Thread::Current());
660 // Note that we don't need to lock `lock_` here, the compiler calling
661 // this method has already ensured the inline cache will not be deleted.
662 for (size_t in_cache = 0, in_array = 0;
663 in_cache < InlineCache::kIndividualCacheSize;
664 ++in_cache) {
665 mirror::Class* object = ic.classes_[in_cache].Read();
666 if (object != nullptr) {
667 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000668 }
669 }
670}
671
Mathieu Chartierf044c222017-05-31 15:27:54 -0700672static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
673 if (was_warm) {
Nicolas Geoffray34088e12018-03-08 10:56:09 +0000674 // Don't do any read barrier, as the declaring class of `method` may
675 // be in the process of being GC'ed (reading the declaring class is done
676 // when DCHECKing the declaring class is resolved, which we know it is
677 // at this point).
678 method->SetPreviouslyWarm<kWithoutReadBarrier>();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700679 }
680 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
681 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100682 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
683 // the warmup threshold is 1.
684 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
685 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700686}
687
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100688uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
689 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000690 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700691 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000692 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100693 size_t frame_size_in_bytes,
694 size_t core_spill_mask,
695 size_t fp_spill_mask,
696 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000697 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100698 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000699 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700700 Handle<mirror::ObjectArray<mirror::Object>> roots,
701 bool has_should_deoptimize_flag,
702 const ArenaSet<ArtMethod*>&
703 cha_single_implementation_list) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000704 DCHECK_NE(stack_map != nullptr, method->IsNative());
705 DCHECK(!method->IsNative() || !osr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100706 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
707 // Ensure the header ends up at expected instruction alignment.
708 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
709 size_t total_size = header_size + code_size;
710
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100711 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100712 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000713 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100714 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000715 ScopedThreadSuspension sts(self, kSuspended);
716 MutexLock mu(self, lock_);
717 WaitForPotentialCollectionToComplete(self);
718 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100719 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000720 memory = AllocateCode(total_size);
721 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000722 return nullptr;
723 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100724 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000725
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100726 std::copy(code, code + code_size, code_ptr);
727 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
728 new (method_header) OatQuickMethodHeader(
Vladimir Marko2196c652017-11-30 16:16:07 +0000729 (stack_map != nullptr) ? code_ptr - stack_map : 0u,
730 (method_info != nullptr) ? code_ptr - method_info : 0u,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000731 frame_size_in_bytes,
732 core_spill_mask,
733 fp_spill_mask,
734 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100735 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
736 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
737 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
738 // 6P) stop being supported or their kernels are fixed.
739 //
740 // For reference, this behavior is caused by this commit:
741 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
742 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
743 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700744 DCHECK(!Runtime::Current()->IsAotCompiler());
745 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100746 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700747 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100748 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100749
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000750 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100751 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000752 // We need to update the entry point in the runnable state for the instrumentation.
753 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700754 // Need cha_lock_ for checking all single-implementation flags and register
755 // dependencies.
756 MutexLock cha_mu(self, *Locks::cha_lock_);
757 bool single_impl_still_valid = true;
758 for (ArtMethod* single_impl : cha_single_implementation_list) {
759 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700760 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
761 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700762 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700763 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700764 break;
765 }
766 }
767
768 // Discard the code if any single-implementation assumptions are now invalid.
769 if (!single_impl_still_valid) {
770 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
771 return nullptr;
772 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000773 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800774 << "Should not be using cha on debuggable apps/runs!";
775
Mingyao Yang063fc772016-08-02 11:02:54 -0700776 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700777 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700778 single_impl, method, method_header);
779 }
780
781 // The following needs to be guarded by cha_lock_ also. Otherwise it's
782 // possible that the compiled code is considered invalidated by some class linking,
783 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000784 MutexLock mu(self, lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000785 if (UNLIKELY(method->IsNative())) {
786 DCHECK(stack_map == nullptr);
787 DCHECK(roots_data == nullptr);
788 auto it = jni_stubs_map_.find(JniStubKey(method));
789 DCHECK(it != jni_stubs_map_.end())
790 << "Entry inserted in NotifyCompilationOf() should be alive.";
791 JniStubData* data = &it->second;
792 DCHECK(ContainsElement(data->GetMethods(), method))
793 << "Entry inserted in NotifyCompilationOf() should contain this method.";
794 data->SetCode(code_ptr);
795 instrumentation::Instrumentation* instrum = Runtime::Current()->GetInstrumentation();
796 for (ArtMethod* m : data->GetMethods()) {
797 instrum->UpdateMethodsCode(m, method_header->GetEntryPoint());
798 }
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100799 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +0000800 // Fill the root table before updating the entry point.
801 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
802 DCHECK_LE(roots_data, stack_map);
803 FillRootTable(roots_data, roots);
804 {
805 // Flush data cache, as compiled code references literals in it.
Vladimir Marko2196c652017-11-30 16:16:07 +0000806 FlushDataCache(reinterpret_cast<char*>(roots_data),
807 reinterpret_cast<char*>(roots_data + data_size));
808 }
809 method_code_map_.Put(code_ptr, method);
810 if (osr) {
811 number_of_osr_compilations_++;
812 osr_code_map_.Put(method, code_ptr);
813 } else {
814 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
815 method, method_header->GetEntryPoint());
816 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000817 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000818 if (collection_in_progress_) {
819 // We need to update the live bitmap if there is a GC to ensure it sees this new
820 // code.
821 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
822 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000823 last_update_time_ns_.store(NanoTime(), std::memory_order_release);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000824 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100825 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700826 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000827 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
828 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
829 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700830 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
831 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000832 histogram_code_memory_use_.AddValue(code_size);
833 if (code_size > kCodeSizeLogThreshold) {
834 LOG(INFO) << "JIT allocated "
835 << PrettySize(code_size)
836 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700837 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000838 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000839 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100840
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100841 return reinterpret_cast<uint8_t*>(method_header);
842}
843
844size_t JitCodeCache::CodeCacheSize() {
845 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000846 return CodeCacheSizeLocked();
847}
848
Orion Hodsoneced6922017-06-01 10:54:28 +0100849bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000850 // This function is used only for testing and only with non-native methods.
851 CHECK(!method->IsNative());
852
Orion Hodsoneced6922017-06-01 10:54:28 +0100853 MutexLock mu(Thread::Current(), lock_);
Orion Hodsoneced6922017-06-01 10:54:28 +0100854
Vladimir Marko2196c652017-11-30 16:16:07 +0000855 bool osr = osr_code_map_.find(method) != osr_code_map_.end();
856 bool in_cache = RemoveMethodLocked(method, release_memory);
Orion Hodsoneced6922017-06-01 10:54:28 +0100857
858 if (!in_cache) {
859 return false;
860 }
861
Orion Hodsoneced6922017-06-01 10:54:28 +0100862 method->ClearCounter();
863 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
864 method, GetQuickToInterpreterBridge());
865 VLOG(jit)
866 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
867 << ArtMethod::PrettyMethod(method) << "@" << method
868 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
869 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
870 return true;
871}
872
Vladimir Marko2196c652017-11-30 16:16:07 +0000873bool JitCodeCache::RemoveMethodLocked(ArtMethod* method, bool release_memory) {
874 if (LIKELY(!method->IsNative())) {
875 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
876 if (info != nullptr) {
877 RemoveElement(profiling_infos_, info);
878 }
879 method->SetProfilingInfo(nullptr);
880 }
881
882 bool in_cache = false;
883 ScopedCodeCacheWrite ccw(code_map_.get());
884 if (UNLIKELY(method->IsNative())) {
885 auto it = jni_stubs_map_.find(JniStubKey(method));
886 if (it != jni_stubs_map_.end() && it->second.RemoveMethod(method)) {
887 in_cache = true;
888 if (it->second.GetMethods().empty()) {
889 if (release_memory) {
890 FreeCode(it->second.GetCode());
891 }
892 jni_stubs_map_.erase(it);
893 } else {
894 it->first.UpdateShorty(it->second.GetMethods().front());
895 }
896 }
897 } else {
898 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
899 if (it->second == method) {
900 in_cache = true;
901 if (release_memory) {
902 FreeCode(it->first);
903 }
904 it = method_code_map_.erase(it);
905 } else {
906 ++it;
907 }
908 }
909
910 auto osr_it = osr_code_map_.find(method);
911 if (osr_it != osr_code_map_.end()) {
912 osr_code_map_.erase(osr_it);
913 }
914 }
915
916 return in_cache;
917}
918
Alex Lightdba61482016-12-21 08:20:29 -0800919// This notifies the code cache that the given method has been redefined and that it should remove
920// any cached information it has on the method. All threads must be suspended before calling this
921// method. The compiled code for the method (if there is any) must not be in any threads call stack.
922void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
923 MutexLock mu(Thread::Current(), lock_);
Vladimir Marko2196c652017-11-30 16:16:07 +0000924 RemoveMethodLocked(method, /* release_memory */ true);
Alex Lightdba61482016-12-21 08:20:29 -0800925}
926
927// This invalidates old_method. Once this function returns one can no longer use old_method to
928// execute code unless it is fixed up. This fixup will happen later in the process of installing a
929// class redefinition.
930// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
931// shouldn't be used since it is no longer logically in the jit code cache.
932// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
933void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000934 MutexLock mu(Thread::Current(), lock_);
Alex Lighteee0bd42017-02-14 15:31:45 +0000935 if (old_method->IsNative()) {
Vladimir Marko2196c652017-11-30 16:16:07 +0000936 // Update methods in jni_stubs_map_.
937 for (auto& entry : jni_stubs_map_) {
938 JniStubData& data = entry.second;
939 data.MoveObsoleteMethod(old_method, new_method);
940 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000941 return;
942 }
Alex Lightdba61482016-12-21 08:20:29 -0800943 // Update ProfilingInfo to the new one and remove it from the old_method.
944 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
945 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
946 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
947 old_method->SetProfilingInfo(nullptr);
948 // Since the JIT should be paused and all threads suspended by the time this is called these
949 // checks should always pass.
950 DCHECK(!info->IsInUseByCompiler());
951 new_method->SetProfilingInfo(info);
952 info->method_ = new_method;
953 }
954 // Update method_code_map_ to point to the new method.
955 for (auto& it : method_code_map_) {
956 if (it.second == old_method) {
957 it.second = new_method;
958 }
959 }
960 // Update osr_code_map_ to point to the new method.
961 auto code_map = osr_code_map_.find(old_method);
962 if (code_map != osr_code_map_.end()) {
963 osr_code_map_.Put(new_method, code_map->second);
964 osr_code_map_.erase(old_method);
965 }
966}
967
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000968size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000969 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100970}
971
972size_t JitCodeCache::DataCacheSize() {
973 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000974 return DataCacheSizeLocked();
975}
976
977size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000978 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800979}
980
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000981void JitCodeCache::ClearData(Thread* self,
982 uint8_t* stack_map_data,
983 uint8_t* roots_data) {
984 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000985 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000986 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000987}
988
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000989size_t JitCodeCache::ReserveData(Thread* self,
990 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700991 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000992 size_t number_of_roots,
993 ArtMethod* method,
994 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700995 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000996 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000997 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700998 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100999 uint8_t* result = nullptr;
1000
1001 {
1002 ScopedThreadSuspension sts(self, kSuspended);
1003 MutexLock mu(self, lock_);
1004 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001005 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001006 }
1007
1008 if (result == nullptr) {
1009 // Retry.
1010 GarbageCollectCache(self);
1011 ScopedThreadSuspension sts(self, kSuspended);
1012 MutexLock mu(self, lock_);
1013 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001014 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001015 }
1016
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001017 MutexLock mu(self, lock_);
1018 histogram_stack_map_memory_use_.AddValue(size);
1019 if (size > kStackMapSizeLogThreshold) {
1020 LOG(INFO) << "JIT allocated "
1021 << PrettySize(size)
1022 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -07001023 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001024 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001025 if (result != nullptr) {
1026 *roots_data = result;
1027 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001028 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001029 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001030 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001031 } else {
1032 *roots_data = nullptr;
1033 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001034 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +00001035 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +00001036 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001037}
1038
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001039class MarkCodeVisitor FINAL : public StackVisitor {
1040 public:
1041 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
1042 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
1043 code_cache_(code_cache_in),
1044 bitmap_(code_cache_->GetLiveBitmap()) {}
1045
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001046 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001047 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
1048 if (method_header == nullptr) {
1049 return true;
1050 }
1051 const void* code = method_header->GetCode();
1052 if (code_cache_->ContainsPc(code)) {
1053 // Use the atomic set version, as multiple threads are executing this code.
1054 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
1055 }
1056 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001057 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001058
1059 private:
1060 JitCodeCache* const code_cache_;
1061 CodeCacheBitmap* const bitmap_;
1062};
1063
1064class MarkCodeClosure FINAL : public Closure {
1065 public:
1066 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
1067 : code_cache_(code_cache), barrier_(barrier) {}
1068
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001069 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001070 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001071 DCHECK(thread == Thread::Current() || thread->IsSuspended());
1072 MarkCodeVisitor visitor(thread, code_cache_);
1073 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001074 if (kIsDebugBuild) {
1075 // The stack walking code queries the side instrumentation stack if it
1076 // sees an instrumentation exit pc, so the JIT code of methods in that stack
1077 // must have been seen. We sanity check this below.
1078 for (const instrumentation::InstrumentationStackFrame& frame
1079 : *thread->GetInstrumentationStack()) {
1080 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
1081 // its stack frame, it is not the method owning return_pc_. We just pass null to
1082 // LookupMethodHeader: the method is only checked against in debug builds.
1083 OatQuickMethodHeader* method_header =
Vladimir Marko2196c652017-11-30 16:16:07 +00001084 code_cache_->LookupMethodHeader(frame.return_pc_, /* method */ nullptr);
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001085 if (method_header != nullptr) {
1086 const void* code = method_header->GetCode();
1087 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
1088 }
1089 }
1090 }
Mathieu Chartier10d25082015-10-28 18:36:09 -07001091 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001092 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001093
1094 private:
1095 JitCodeCache* const code_cache_;
1096 Barrier* const barrier_;
1097};
1098
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001099void JitCodeCache::NotifyCollectionDone(Thread* self) {
1100 collection_in_progress_ = false;
1101 lock_cond_.Broadcast(self);
1102}
1103
1104void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
1105 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001106 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001107 DCHECK_EQ(per_space_footprint * 2, new_footprint);
1108 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
1109 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001110 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001111 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
1112 }
1113}
1114
1115bool JitCodeCache::IncreaseCodeCacheCapacity() {
1116 if (current_capacity_ == max_capacity_) {
1117 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001118 }
1119
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001120 // Double the capacity if we're below 1MB, or increase it by 1MB if
1121 // we're above.
1122 if (current_capacity_ < 1 * MB) {
1123 current_capacity_ *= 2;
1124 } else {
1125 current_capacity_ += 1 * MB;
1126 }
1127 if (current_capacity_ > max_capacity_) {
1128 current_capacity_ = max_capacity_;
1129 }
1130
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001131 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001132
1133 SetFootprintLimit(current_capacity_);
1134
1135 return true;
1136}
1137
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001138void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
1139 Barrier barrier(0);
1140 size_t threads_running_checkpoint = 0;
1141 MarkCodeClosure closure(this, &barrier);
1142 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
1143 // Now that we have run our checkpoint, move to a suspended state and wait
1144 // for other threads to run the checkpoint.
1145 ScopedThreadSuspension sts(self, kSuspended);
1146 if (threads_running_checkpoint != 0) {
1147 barrier.Increment(self, threads_running_checkpoint);
1148 }
1149}
1150
Nicolas Geoffray35122442016-03-02 12:05:30 +00001151bool JitCodeCache::ShouldDoFullCollection() {
1152 if (current_capacity_ == max_capacity_) {
1153 // Always do a full collection when the code cache is full.
1154 return true;
1155 } else if (current_capacity_ < kReservedCapacity) {
1156 // Always do partial collection when the code cache size is below the reserved
1157 // capacity.
1158 return false;
1159 } else if (last_collection_increased_code_cache_) {
1160 // This time do a full collection.
1161 return true;
1162 } else {
1163 // This time do a partial collection.
1164 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001165 }
1166}
1167
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001168void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001169 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001170 if (!garbage_collect_code_) {
1171 MutexLock mu(self, lock_);
1172 IncreaseCodeCacheCapacity();
1173 return;
1174 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001175
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001176 // Wait for an existing collection, or let everyone know we are starting one.
1177 {
1178 ScopedThreadSuspension sts(self, kSuspended);
1179 MutexLock mu(self, lock_);
1180 if (WaitForPotentialCollectionToComplete(self)) {
1181 return;
1182 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001183 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001184 live_bitmap_.reset(CodeCacheBitmap::Create(
1185 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001186 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1187 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001188 collection_in_progress_ = true;
1189 }
1190 }
1191
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001192 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001193 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001194 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001195
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001196 bool do_full_collection = false;
1197 {
1198 MutexLock mu(self, lock_);
1199 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001200 }
1201
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001202 VLOG(jit) << "Do "
1203 << (do_full_collection ? "full" : "partial")
1204 << " code cache collection, code="
1205 << PrettySize(CodeCacheSize())
1206 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001207
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001208 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1209
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001210 VLOG(jit) << "After code cache collection, code="
1211 << PrettySize(CodeCacheSize())
1212 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001213
1214 {
1215 MutexLock mu(self, lock_);
1216
1217 // Increase the code cache only when we do partial collections.
1218 // TODO: base this strategy on how full the code cache is?
1219 if (do_full_collection) {
1220 last_collection_increased_code_cache_ = false;
1221 } else {
1222 last_collection_increased_code_cache_ = true;
1223 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001224 }
1225
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001226 bool next_collection_will_be_full = ShouldDoFullCollection();
1227
1228 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001229 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001230 // Save the entry point of methods we have compiled, and update the entry
1231 // point of those methods to the interpreter. If the method is invoked, the
1232 // interpreter will update its entry point to the compiled code and call it.
1233 for (ProfilingInfo* info : profiling_infos_) {
1234 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1235 if (ContainsPc(entry_point)) {
1236 info->SetSavedEntryPoint(entry_point);
Vladimir Marko2196c652017-11-30 16:16:07 +00001237 // Don't call Instrumentation::UpdateMethodsCode(), as it can check the declaring
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001238 // class of the method. We may be concurrently running a GC which makes accessing
1239 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1240 // checked that the current entry point is JIT compiled code.
1241 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001242 }
1243 }
1244
1245 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Vladimir Marko2196c652017-11-30 16:16:07 +00001246
1247 // Change entry points of native methods back to the GenericJNI entrypoint.
1248 for (const auto& entry : jni_stubs_map_) {
1249 const JniStubData& data = entry.second;
1250 if (!data.IsCompiled()) {
1251 continue;
1252 }
1253 // Make sure a single invocation of the GenericJNI trampoline tries to recompile.
1254 uint16_t new_counter = Runtime::Current()->GetJit()->HotMethodThreshold() - 1u;
1255 const OatQuickMethodHeader* method_header =
1256 OatQuickMethodHeader::FromCodePointer(data.GetCode());
1257 for (ArtMethod* method : data.GetMethods()) {
1258 if (method->GetEntryPointFromQuickCompiledCode() == method_header->GetEntryPoint()) {
1259 // Don't call Instrumentation::UpdateMethodsCode(), same as for normal methods above.
1260 method->SetCounter(new_counter);
1261 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
1262 }
1263 }
1264 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001265 }
1266 live_bitmap_.reset(nullptr);
1267 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001268 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001269 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001270 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001271}
1272
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001273void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001274 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001275 std::unordered_set<OatQuickMethodHeader*> method_headers;
1276 {
1277 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001278 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001279 // Iterate over all compiled code and remove entries that are not marked.
Vladimir Marko2196c652017-11-30 16:16:07 +00001280 for (auto it = jni_stubs_map_.begin(); it != jni_stubs_map_.end();) {
1281 JniStubData* data = &it->second;
1282 if (!data->IsCompiled() || GetLiveBitmap()->Test(FromCodeToAllocation(data->GetCode()))) {
1283 ++it;
1284 } else {
1285 method_headers.insert(OatQuickMethodHeader::FromCodePointer(data->GetCode()));
1286 it = jni_stubs_map_.erase(it);
1287 }
1288 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001289 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1290 const void* code_ptr = it->first;
1291 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1292 if (GetLiveBitmap()->Test(allocation)) {
1293 ++it;
1294 } else {
Vladimir Marko2196c652017-11-30 16:16:07 +00001295 method_headers.insert(OatQuickMethodHeader::FromCodePointer(code_ptr));
Mingyao Yang063fc772016-08-02 11:02:54 -07001296 it = method_code_map_.erase(it);
1297 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001298 }
1299 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001300 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001301}
1302
1303void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001304 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001305 {
1306 MutexLock mu(self, lock_);
1307 if (collect_profiling_info) {
1308 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1309 // Also remove the saved entry point from the ProfilingInfo objects.
1310 for (ProfilingInfo* info : profiling_infos_) {
1311 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001312 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001313 info->GetMethod()->SetProfilingInfo(nullptr);
1314 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001315
1316 if (info->GetSavedEntryPoint() != nullptr) {
1317 info->SetSavedEntryPoint(nullptr);
1318 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001319 // give it a chance to be hot again.
1320 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001321 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001322 }
1323 } else if (kIsDebugBuild) {
1324 // Sanity check that the profiling infos do not have a dangling entry point.
1325 for (ProfilingInfo* info : profiling_infos_) {
1326 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001327 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001328 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001329
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001330 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1331 // an entry point is either:
1332 // - an osr compiled code, that will be removed if not in a thread call stack.
1333 // - discarded compiled code, that will be removed if not in a thread call stack.
Vladimir Marko2196c652017-11-30 16:16:07 +00001334 for (const auto& entry : jni_stubs_map_) {
1335 const JniStubData& data = entry.second;
1336 const void* code_ptr = data.GetCode();
1337 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1338 for (ArtMethod* method : data.GetMethods()) {
1339 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1340 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1341 break;
1342 }
1343 }
1344 }
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001345 for (const auto& it : method_code_map_) {
1346 ArtMethod* method = it.second;
1347 const void* code_ptr = it.first;
1348 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1349 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1350 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1351 }
1352 }
1353
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001354 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001355 // on thread stacks).
1356 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001357 }
1358
1359 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001360 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001361
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001362 // At this point, mutator threads are still running, and entrypoints of methods can
1363 // change. We do know they cannot change to a code cache entry that is not marked,
1364 // therefore we can safely remove those entries.
1365 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001366
Nicolas Geoffray35122442016-03-02 12:05:30 +00001367 if (collect_profiling_info) {
1368 MutexLock mu(self, lock_);
1369 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001370 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001371 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001372 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001373 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1374 // that the compiled code would not get revived. As mutator threads run concurrently,
1375 // they may have revived the compiled code, and now we are in the situation where
1376 // a method has compiled code but no ProfilingInfo.
1377 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1378 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001379 if (ContainsPc(ptr) &&
1380 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001381 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001382 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001383 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001384 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001385 return true;
1386 }
1387 return false;
1388 });
1389 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001390 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001391 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001392}
1393
Nicolas Geoffray35122442016-03-02 12:05:30 +00001394bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001395 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001396 // Check that methods we have compiled do have a ProfilingInfo object. We would
1397 // have memory leaks of compiled code otherwise.
1398 for (const auto& it : method_code_map_) {
1399 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001400 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001401 const void* code_ptr = it.first;
1402 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1403 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1404 // If the code is not dead, then we have a problem. Note that this can even
1405 // happen just after a collection, as mutator threads are running in parallel
1406 // and could deoptimize an existing compiled code.
1407 return false;
1408 }
1409 }
1410 }
1411 return true;
1412}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001413
1414OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001415 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1416 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001417 // On Thumb-2, the pc is offset by one.
1418 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001419 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001420 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1421 return nullptr;
1422 }
1423
Vladimir Marko2196c652017-11-30 16:16:07 +00001424 if (!kIsDebugBuild) {
1425 // Called with null `method` only from MarkCodeClosure::Run() in debug build.
1426 CHECK(method != nullptr);
Vladimir Marko47d31852017-11-28 18:36:12 +00001427 }
Vladimir Markoe7441632017-11-29 13:00:56 +00001428
Vladimir Marko2196c652017-11-30 16:16:07 +00001429 MutexLock mu(Thread::Current(), lock_);
1430 OatQuickMethodHeader* method_header = nullptr;
1431 ArtMethod* found_method = nullptr; // Only for DCHECK(), not for JNI stubs.
1432 if (method != nullptr && UNLIKELY(method->IsNative())) {
1433 auto it = jni_stubs_map_.find(JniStubKey(method));
1434 if (it == jni_stubs_map_.end() || !ContainsElement(it->second.GetMethods(), method)) {
1435 return nullptr;
1436 }
1437 const void* code_ptr = it->second.GetCode();
1438 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1439 if (!method_header->Contains(pc)) {
1440 return nullptr;
1441 }
1442 } else {
1443 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1444 if (it != method_code_map_.begin()) {
1445 --it;
1446 const void* code_ptr = it->first;
1447 if (OatQuickMethodHeader::FromCodePointer(code_ptr)->Contains(pc)) {
1448 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1449 found_method = it->second;
1450 }
1451 }
1452 if (method_header == nullptr && method == nullptr) {
1453 // Scan all compiled JNI stubs as well. This slow search is used only
1454 // for checks in debug build, for release builds the `method` is not null.
1455 for (auto&& entry : jni_stubs_map_) {
1456 const JniStubData& data = entry.second;
1457 if (data.IsCompiled() &&
1458 OatQuickMethodHeader::FromCodePointer(data.GetCode())->Contains(pc)) {
1459 method_header = OatQuickMethodHeader::FromCodePointer(data.GetCode());
1460 }
1461 }
1462 }
1463 if (method_header == nullptr) {
1464 return nullptr;
1465 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001466 }
Vladimir Marko2196c652017-11-30 16:16:07 +00001467
1468 if (kIsDebugBuild && method != nullptr && !method->IsNative()) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001469 // When we are walking the stack to redefine classes and creating obsolete methods it is
1470 // possible that we might have updated the method_code_map by making this method obsolete in a
1471 // previous frame. Therefore we should just check that the non-obsolete version of this method
1472 // is the one we expect. We change to the non-obsolete versions in the error message since the
1473 // obsolete version of the method might not be fully initialized yet. This situation can only
1474 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001475 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001476 // information.)
Vladimir Marko2196c652017-11-30 16:16:07 +00001477 DCHECK_EQ(found_method->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
Alex Light1ebe4fe2017-01-30 14:57:11 -08001478 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
Vladimir Marko2196c652017-11-30 16:16:07 +00001479 << ArtMethod::PrettyMethod(found_method->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001480 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001481 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001482 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001483}
1484
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001485OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1486 MutexLock mu(Thread::Current(), lock_);
1487 auto it = osr_code_map_.find(method);
1488 if (it == osr_code_map_.end()) {
1489 return nullptr;
1490 }
1491 return OatQuickMethodHeader::FromCodePointer(it->second);
1492}
1493
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001494ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1495 ArtMethod* method,
1496 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001497 bool retry_allocation)
1498 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1499 NO_THREAD_SAFETY_ANALYSIS {
1500 ProfilingInfo* info = nullptr;
1501 if (!retry_allocation) {
1502 // If we are allocating for the interpreter, just try to lock, to avoid
1503 // lock contention with the JIT.
1504 if (lock_.ExclusiveTryLock(self)) {
1505 info = AddProfilingInfoInternal(self, method, entries);
1506 lock_.ExclusiveUnlock(self);
1507 }
1508 } else {
1509 {
1510 MutexLock mu(self, lock_);
1511 info = AddProfilingInfoInternal(self, method, entries);
1512 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001513
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001514 if (info == nullptr) {
1515 GarbageCollectCache(self);
1516 MutexLock mu(self, lock_);
1517 info = AddProfilingInfoInternal(self, method, entries);
1518 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001519 }
1520 return info;
1521}
1522
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001523ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001524 ArtMethod* method,
1525 const std::vector<uint32_t>& entries) {
1526 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001527 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001528 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001529
1530 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001531 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001532 if (info != nullptr) {
1533 return info;
1534 }
1535
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001536 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001537 if (data == nullptr) {
1538 return nullptr;
1539 }
1540 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001541
1542 // Make sure other threads see the data in the profiling info object before the
1543 // store in the ArtMethod's ProfilingInfo pointer.
1544 QuasiAtomic::ThreadFenceRelease();
1545
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001546 method->SetProfilingInfo(info);
1547 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001548 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001549 return info;
1550}
1551
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001552// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1553// is already held.
1554void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1555 if (code_mspace_ == mspace) {
1556 size_t result = code_end_;
1557 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001558 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001559 } else {
1560 DCHECK_EQ(data_mspace_, mspace);
1561 size_t result = data_end_;
1562 data_end_ += increment;
1563 return reinterpret_cast<void*>(result + data_map_->Begin());
1564 }
1565}
1566
Calin Juravle99629622016-04-19 16:33:46 +01001567void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001568 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001569 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001570 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001571 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001572 for (const ProfilingInfo* info : profiling_infos_) {
1573 ArtMethod* method = info->GetMethod();
1574 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001575 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1576 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001577 // Skip dex files which are not profiled.
1578 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001579 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001580 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001581
1582 // If the method didn't reach the compilation threshold don't save the inline caches.
1583 // They might be incomplete and cause unnecessary deoptimizations.
1584 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1585 if (method->GetCounter() < jit_compile_threshold) {
1586 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001587 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001588 continue;
1589 }
1590
Calin Juravle940eb0c2017-01-30 19:30:44 -08001591 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001592 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001593 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001594 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001595 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001596 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1597 mirror::Class* cls = cache.classes_[k].Read();
1598 if (cls == nullptr) {
1599 break;
1600 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001601
Calin Juravle13439f02017-02-21 01:17:21 -08001602 // Check if the receiver is in the boot class path or if it's in the
1603 // same class loader as the caller. If not, skip it, as there is not
1604 // much we can do during AOT.
1605 if (!cls->IsBootStrapClassLoaded() &&
1606 caller->GetClassLoader() != cls->GetClassLoader()) {
1607 is_missing_types = true;
1608 continue;
1609 }
1610
Calin Juravle4ca70a32017-02-21 16:22:24 -08001611 const DexFile* class_dex_file = nullptr;
1612 dex::TypeIndex type_index;
1613
1614 if (cls->GetDexCache() == nullptr) {
1615 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001616 // Make a best effort to find the type index in the method's dex file.
1617 // We could search all open dex files but that might turn expensive
1618 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001619 class_dex_file = dex_file;
1620 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1621 } else {
1622 class_dex_file = &(cls->GetDexFile());
1623 type_index = cls->GetDexTypeIndex();
1624 }
1625 if (!type_index.IsValid()) {
1626 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001627 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001628 continue;
1629 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001630 if (ContainsElement(dex_base_locations,
1631 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001632 // Only consider classes from the same apk (including multidex).
1633 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001634 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001635 } else {
1636 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001637 }
1638 }
1639 if (!profile_classes.empty()) {
1640 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001641 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001642 }
1643 }
1644 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001645 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001646 }
1647}
1648
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001649uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
Orion Hodson88591fe2018-03-06 13:35:43 +00001650 return last_update_time_ns_.load(std::memory_order_acquire);
Calin Juravle31f2c152015-10-23 17:56:15 +01001651}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001652
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001653bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1654 MutexLock mu(Thread::Current(), lock_);
1655 return osr_code_map_.find(method) != osr_code_map_.end();
1656}
1657
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001658bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1659 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001660 return false;
1661 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001662
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001663 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001664 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1665 return false;
1666 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001667
Vladimir Marko2196c652017-11-30 16:16:07 +00001668 if (UNLIKELY(method->IsNative())) {
1669 JniStubKey key(method);
1670 auto it = jni_stubs_map_.find(key);
1671 bool new_compilation = false;
1672 if (it == jni_stubs_map_.end()) {
1673 // Create a new entry to mark the stub as being compiled.
1674 it = jni_stubs_map_.Put(key, JniStubData{});
1675 new_compilation = true;
1676 }
1677 JniStubData* data = &it->second;
1678 data->AddMethod(method);
1679 if (data->IsCompiled()) {
1680 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(data->GetCode());
1681 const void* entrypoint = method_header->GetEntryPoint();
1682 // Update also entrypoints of other methods held by the JniStubData.
1683 // We could simply update the entrypoint of `method` but if the last JIT GC has
1684 // changed these entrypoints to GenericJNI in preparation for a full GC, we may
1685 // as well change them back as this stub shall not be collected anyway and this
1686 // can avoid a few expensive GenericJNI calls.
1687 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1688 for (ArtMethod* m : data->GetMethods()) {
Nicolas Geoffraya6e0e7d2018-01-26 13:16:50 +00001689 // Call the dedicated method instead of the more generic UpdateMethodsCode, because
1690 // `m` might be in the process of being deleted.
1691 instrumentation->UpdateNativeMethodsCodeToJitCode(m, entrypoint);
Vladimir Marko2196c652017-11-30 16:16:07 +00001692 }
1693 if (collection_in_progress_) {
1694 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(data->GetCode()));
1695 }
1696 }
1697 return new_compilation;
1698 } else {
1699 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1700 if (info == nullptr) {
1701 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
1702 // Because the counter is not atomic, there are some rare cases where we may not hit the
1703 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
1704 ClearMethodCounter(method, /*was_warm*/ false);
1705 return false;
1706 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001707
Vladimir Marko2196c652017-11-30 16:16:07 +00001708 if (info->IsMethodBeingCompiled(osr)) {
1709 return false;
1710 }
Nicolas Geoffray056d7752017-11-30 09:12:13 +00001711
Vladimir Marko2196c652017-11-30 16:16:07 +00001712 info->SetIsMethodBeingCompiled(true, osr);
1713 return true;
1714 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001715}
1716
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001717ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001718 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001719 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001720 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001721 if (!info->IncrementInlineUse()) {
1722 // Overflow of inlining uses, just bail.
1723 return nullptr;
1724 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001725 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001726 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001727}
1728
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001729void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001730 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001731 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001732 DCHECK(info != nullptr);
1733 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001734}
1735
Vladimir Marko2196c652017-11-30 16:16:07 +00001736void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self, bool osr) {
1737 DCHECK_EQ(Thread::Current(), self);
1738 MutexLock mu(self, lock_);
1739 if (UNLIKELY(method->IsNative())) {
1740 auto it = jni_stubs_map_.find(JniStubKey(method));
1741 DCHECK(it != jni_stubs_map_.end());
1742 JniStubData* data = &it->second;
1743 DCHECK(ContainsElement(data->GetMethods(), method));
1744 if (UNLIKELY(!data->IsCompiled())) {
1745 // Failed to compile; the JNI compiler never fails, but the cache may be full.
1746 jni_stubs_map_.erase(it); // Remove the entry added in NotifyCompilationOf().
1747 } // else CommitCodeInternal() updated entrypoints of all methods in the JniStubData.
1748 } else {
1749 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
1750 DCHECK(info->IsMethodBeingCompiled(osr));
1751 info->SetIsMethodBeingCompiled(false, osr);
1752 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001753}
1754
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001755size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1756 MutexLock mu(Thread::Current(), lock_);
1757 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1758}
1759
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001760void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1761 const OatQuickMethodHeader* header) {
Vladimir Marko2196c652017-11-30 16:16:07 +00001762 DCHECK(!method->IsNative());
Andreas Gampe542451c2016-07-26 09:02:02 -07001763 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001764 if ((profiling_info != nullptr) &&
1765 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1766 // Prevent future uses of the compiled code.
1767 profiling_info->SetSavedEntryPoint(nullptr);
1768 }
1769
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001770 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001771 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001772 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001773 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1774 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001775 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001776 } else {
1777 MutexLock mu(Thread::Current(), lock_);
1778 auto it = osr_code_map_.find(method);
1779 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1780 // Remove the OSR method, to avoid using it again.
1781 osr_code_map_.erase(it);
1782 }
1783 }
1784}
1785
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001786uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1787 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1788 uint8_t* result = reinterpret_cast<uint8_t*>(
1789 mspace_memalign(code_mspace_, alignment, code_size));
1790 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1791 // Ensure the header ends up at expected instruction alignment.
1792 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1793 used_memory_for_code_ += mspace_usable_size(result);
1794 return result;
1795}
1796
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001797void JitCodeCache::FreeCode(uint8_t* code) {
1798 used_memory_for_code_ -= mspace_usable_size(code);
1799 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001800}
1801
1802uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1803 void* result = mspace_malloc(data_mspace_, data_size);
1804 used_memory_for_data_ += mspace_usable_size(result);
1805 return reinterpret_cast<uint8_t*>(result);
1806}
1807
1808void JitCodeCache::FreeData(uint8_t* data) {
1809 used_memory_for_data_ -= mspace_usable_size(data);
1810 mspace_free(data_mspace_, data);
1811}
1812
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001813void JitCodeCache::Dump(std::ostream& os) {
1814 MutexLock mu(Thread::Current(), lock_);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001815 MutexLock mu2(Thread::Current(), *Locks::native_debug_interface_lock_);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001816 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1817 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
David Srbecky440a9b32018-02-15 17:47:29 +00001818 << "Current JIT mini-debug-info size: " << PrettySize(GetJitNativeDebugInfoMemUsage()) << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001819 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
Vladimir Marko2196c652017-11-30 16:16:07 +00001820 << "Current number of JIT JNI stub entries: " << jni_stubs_map_.size() << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001821 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1822 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1823 << "Total number of JIT compilations for on stack replacement: "
1824 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001825 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001826 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1827 histogram_code_memory_use_.PrintMemoryUse(os);
1828 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001829}
1830
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001831} // namespace jit
1832} // namespace art