blob: 2c6b24930280cea7f8a77466ce2f266415f14a41 [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000023#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080024#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010025#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000026#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010027#include "entrypoints/runtime_asm_entrypoints.h"
28#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010029#include "gc/scoped_gc_critical_section.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000030#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000031#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080033#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "oat_file-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010036#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037
38namespace art {
39namespace jit {
40
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010041static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
42static constexpr int kProtData = PROT_READ | PROT_WRITE;
43static constexpr int kProtCode = PROT_READ | PROT_EXEC;
44
Nicolas Geoffray933330a2016-03-16 14:20:06 +000045static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
46static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
47
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010048#define CHECKED_MPROTECT(memory, size, prot) \
49 do { \
50 int rc = mprotect(memory, size, prot); \
51 if (UNLIKELY(rc != 0)) { \
52 errno = rc; \
53 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
54 } \
55 } while (false) \
56
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
58 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000059 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000060 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080061 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000063
64 // Generating debug information is mostly for using the 'perf' tool, which does
65 // not work with ashmem.
66 bool use_ashmem = !generate_debug_info;
67 // With 'perf', we want a 1-1 mapping between an address and a method.
68 bool garbage_collect_code = !generate_debug_info;
69
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000070 // We need to have 32 bit offsets from method headers in code cache which point to things
71 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
72 // Ensure we're below 1 GB to be safe.
73 if (max_capacity > 1 * GB) {
74 std::ostringstream oss;
75 oss << "Maxium code cache capacity is limited to 1 GB, "
76 << PrettySize(max_capacity) << " is too big";
77 *error_msg = oss.str();
78 return nullptr;
79 }
80
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 std::string error_str;
82 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010083 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000084 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010085 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080086 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000087 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080088 *error_msg = oss.str();
89 return nullptr;
90 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010091
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000092 // Align both capacities to page size, as that's the unit mspaces use.
93 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
94 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
95
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000096 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010097 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000098 size_t data_size = max_capacity / 2;
99 size_t code_size = max_capacity - data_size;
100 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100101 uint8_t* divider = data_map->Begin() + data_size;
102
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000103 MemMap* code_map =
104 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100105 if (code_map == nullptr) {
106 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000107 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100108 *error_msg = oss.str();
109 return nullptr;
110 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100111 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000112 data_size = initial_capacity / 2;
113 code_size = initial_capacity - data_size;
114 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000115 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000116 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800117}
118
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000119JitCodeCache::JitCodeCache(MemMap* code_map,
120 MemMap* data_map,
121 size_t initial_code_capacity,
122 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000123 size_t max_capacity,
124 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100125 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100126 lock_cond_("Jit code cache variable", lock_),
127 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100128 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000129 data_map_(data_map),
130 max_capacity_(max_capacity),
131 current_capacity_(initial_code_capacity + initial_data_capacity),
132 code_end_(initial_code_capacity),
133 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000134 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000135 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000136 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000137 used_memory_for_data_(0),
138 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000139 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000140 number_of_osr_compilations_(0),
141 number_of_deoptimizations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000142 number_of_collections_(0),
143 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
144 histogram_code_memory_use_("Memory used for compiled code", 16),
145 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100146
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000147 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000148 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
149 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100150
151 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
152 PLOG(FATAL) << "create_mspace_with_base failed";
153 }
154
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000155 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100156
157 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
158 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100159
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000160 VLOG(jit) << "Created jit code cache: initial data size="
161 << PrettySize(initial_data_capacity)
162 << ", initial code size="
163 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800164}
165
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100166bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100167 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800168}
169
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000170bool JitCodeCache::ContainsMethod(ArtMethod* method) {
171 MutexLock mu(Thread::Current(), lock_);
172 for (auto& it : method_code_map_) {
173 if (it.second == method) {
174 return true;
175 }
176 }
177 return false;
178}
179
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800180class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100181 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800182 explicit ScopedCodeCacheWrite(MemMap* code_map)
183 : ScopedTrace("ScopedCodeCacheWrite"),
184 code_map_(code_map) {
185 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100186 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800187 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100188 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800189 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100190 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
191 }
192 private:
193 MemMap* const code_map_;
194
195 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
196};
197
198uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100199 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 const uint8_t* vmap_table,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100201 size_t frame_size_in_bytes,
202 size_t core_spill_mask,
203 size_t fp_spill_mask,
204 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000205 size_t code_size,
206 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100207 uint8_t* result = CommitCodeInternal(self,
208 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100209 vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100210 frame_size_in_bytes,
211 core_spill_mask,
212 fp_spill_mask,
213 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000214 code_size,
215 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100216 if (result == nullptr) {
217 // Retry.
218 GarbageCollectCache(self);
219 result = CommitCodeInternal(self,
220 method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100221 vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100222 frame_size_in_bytes,
223 core_spill_mask,
224 fp_spill_mask,
225 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000226 code_size,
227 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100228 }
229 return result;
230}
231
232bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
233 bool in_collection = false;
234 while (collection_in_progress_) {
235 in_collection = true;
236 lock_cond_.Wait(self);
237 }
238 return in_collection;
239}
240
241static uintptr_t FromCodeToAllocation(const void* code) {
242 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
243 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
244}
245
246void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
247 uintptr_t allocation = FromCodeToAllocation(code_ptr);
248 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000249 // Notify native debugger that we are about to remove the code.
250 // It does nothing if we are not using native debugger.
251 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000252
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100253 // Use the offset directly to prevent sanity check that the method is
254 // compiled with optimizing.
255 // TODO(ngeoffray): Clean up.
256 if (method_header->vmap_table_offset_ != 0) {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000257 const uint8_t* data = method_header->code_ - method_header->vmap_table_offset_;
258 FreeData(const_cast<uint8_t*>(data));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100259 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000260 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100261}
262
263void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800264 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100265 MutexLock mu(self, lock_);
266 // We do not check if a code cache GC is in progress, as this method comes
267 // with the classlinker_classes_lock_ held, and suspending ourselves could
268 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000269 {
270 ScopedCodeCacheWrite scc(code_map_.get());
271 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
272 if (alloc.ContainsUnsafe(it->second)) {
273 FreeCode(it->first, it->second);
274 it = method_code_map_.erase(it);
275 } else {
276 ++it;
277 }
278 }
279 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000280 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
281 if (alloc.ContainsUnsafe(it->first)) {
282 // Note that the code has already been removed in the loop above.
283 it = osr_code_map_.erase(it);
284 } else {
285 ++it;
286 }
287 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000288 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
289 ProfilingInfo* info = *it;
290 if (alloc.ContainsUnsafe(info->GetMethod())) {
291 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000292 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000293 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100294 } else {
295 ++it;
296 }
297 }
298}
299
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000300void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
301 MutexLock mu(self, lock_);
302 for (ProfilingInfo* info : profiling_infos_) {
303 if (!info->IsInUseByCompiler()) {
304 info->ClearGcRootsInInlineCaches();
305 }
306 }
307}
308
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100309uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
310 ArtMethod* method,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100311 const uint8_t* vmap_table,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100312 size_t frame_size_in_bytes,
313 size_t core_spill_mask,
314 size_t fp_spill_mask,
315 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000316 size_t code_size,
317 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100318 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
319 // Ensure the header ends up at expected instruction alignment.
320 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
321 size_t total_size = header_size + code_size;
322
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100323 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100324 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000325 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100326 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000327 ScopedThreadSuspension sts(self, kSuspended);
328 MutexLock mu(self, lock_);
329 WaitForPotentialCollectionToComplete(self);
330 {
331 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000332 memory = AllocateCode(total_size);
333 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000334 return nullptr;
335 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000336 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000337
338 std::copy(code, code + code_size, code_ptr);
339 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
340 new (method_header) OatQuickMethodHeader(
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000341 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000342 frame_size_in_bytes,
343 core_spill_mask,
344 fp_spill_mask,
345 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100346 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100347
Roland Levillain32430262016-02-01 15:23:20 +0000348 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
349 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000350 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100351 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000352 // We need to update the entry point in the runnable state for the instrumentation.
353 {
354 MutexLock mu(self, lock_);
355 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000356 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000357 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000358 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100359 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000360 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
361 method, method_header->GetEntryPoint());
362 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000363 if (collection_in_progress_) {
364 // We need to update the live bitmap if there is a GC to ensure it sees this new
365 // code.
366 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
367 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000368 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000369 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100370 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000371 << PrettyMethod(method) << "@" << method
372 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
373 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
374 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
375 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000376 histogram_code_memory_use_.AddValue(code_size);
377 if (code_size > kCodeSizeLogThreshold) {
378 LOG(INFO) << "JIT allocated "
379 << PrettySize(code_size)
380 << " for compiled code of "
381 << PrettyMethod(method);
382 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000383 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100384
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100385 return reinterpret_cast<uint8_t*>(method_header);
386}
387
388size_t JitCodeCache::CodeCacheSize() {
389 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000390 return CodeCacheSizeLocked();
391}
392
393size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000394 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100395}
396
397size_t JitCodeCache::DataCacheSize() {
398 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000399 return DataCacheSizeLocked();
400}
401
402size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000403 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800404}
405
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000406void JitCodeCache::ClearData(Thread* self, void* data) {
407 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000408 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000409}
410
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000411uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size, ArtMethod* method) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100412 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100413 uint8_t* result = nullptr;
414
415 {
416 ScopedThreadSuspension sts(self, kSuspended);
417 MutexLock mu(self, lock_);
418 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000419 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100420 }
421
422 if (result == nullptr) {
423 // Retry.
424 GarbageCollectCache(self);
425 ScopedThreadSuspension sts(self, kSuspended);
426 MutexLock mu(self, lock_);
427 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000428 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100429 }
430
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000431 MutexLock mu(self, lock_);
432 histogram_stack_map_memory_use_.AddValue(size);
433 if (size > kStackMapSizeLogThreshold) {
434 LOG(INFO) << "JIT allocated "
435 << PrettySize(size)
436 << " for stack maps of "
437 << PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800438 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100439 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800440}
441
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100442class MarkCodeVisitor FINAL : public StackVisitor {
443 public:
444 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
445 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
446 code_cache_(code_cache_in),
447 bitmap_(code_cache_->GetLiveBitmap()) {}
448
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700449 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100450 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
451 if (method_header == nullptr) {
452 return true;
453 }
454 const void* code = method_header->GetCode();
455 if (code_cache_->ContainsPc(code)) {
456 // Use the atomic set version, as multiple threads are executing this code.
457 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
458 }
459 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800460 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100461
462 private:
463 JitCodeCache* const code_cache_;
464 CodeCacheBitmap* const bitmap_;
465};
466
467class MarkCodeClosure FINAL : public Closure {
468 public:
469 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
470 : code_cache_(code_cache), barrier_(barrier) {}
471
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700472 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800473 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100474 DCHECK(thread == Thread::Current() || thread->IsSuspended());
475 MarkCodeVisitor visitor(thread, code_cache_);
476 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000477 if (kIsDebugBuild) {
478 // The stack walking code queries the side instrumentation stack if it
479 // sees an instrumentation exit pc, so the JIT code of methods in that stack
480 // must have been seen. We sanity check this below.
481 for (const instrumentation::InstrumentationStackFrame& frame
482 : *thread->GetInstrumentationStack()) {
483 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
484 // its stack frame, it is not the method owning return_pc_. We just pass null to
485 // LookupMethodHeader: the method is only checked against in debug builds.
486 OatQuickMethodHeader* method_header =
487 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
488 if (method_header != nullptr) {
489 const void* code = method_header->GetCode();
490 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
491 }
492 }
493 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700494 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800495 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100496
497 private:
498 JitCodeCache* const code_cache_;
499 Barrier* const barrier_;
500};
501
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000502void JitCodeCache::NotifyCollectionDone(Thread* self) {
503 collection_in_progress_ = false;
504 lock_cond_.Broadcast(self);
505}
506
507void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
508 size_t per_space_footprint = new_footprint / 2;
509 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
510 DCHECK_EQ(per_space_footprint * 2, new_footprint);
511 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
512 {
513 ScopedCodeCacheWrite scc(code_map_.get());
514 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
515 }
516}
517
518bool JitCodeCache::IncreaseCodeCacheCapacity() {
519 if (current_capacity_ == max_capacity_) {
520 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100521 }
522
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000523 // Double the capacity if we're below 1MB, or increase it by 1MB if
524 // we're above.
525 if (current_capacity_ < 1 * MB) {
526 current_capacity_ *= 2;
527 } else {
528 current_capacity_ += 1 * MB;
529 }
530 if (current_capacity_ > max_capacity_) {
531 current_capacity_ = max_capacity_;
532 }
533
534 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
535 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
536 }
537
538 SetFootprintLimit(current_capacity_);
539
540 return true;
541}
542
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000543void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
544 Barrier barrier(0);
545 size_t threads_running_checkpoint = 0;
546 MarkCodeClosure closure(this, &barrier);
547 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
548 // Now that we have run our checkpoint, move to a suspended state and wait
549 // for other threads to run the checkpoint.
550 ScopedThreadSuspension sts(self, kSuspended);
551 if (threads_running_checkpoint != 0) {
552 barrier.Increment(self, threads_running_checkpoint);
553 }
554}
555
Nicolas Geoffray35122442016-03-02 12:05:30 +0000556bool JitCodeCache::ShouldDoFullCollection() {
557 if (current_capacity_ == max_capacity_) {
558 // Always do a full collection when the code cache is full.
559 return true;
560 } else if (current_capacity_ < kReservedCapacity) {
561 // Always do partial collection when the code cache size is below the reserved
562 // capacity.
563 return false;
564 } else if (last_collection_increased_code_cache_) {
565 // This time do a full collection.
566 return true;
567 } else {
568 // This time do a partial collection.
569 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000570 }
571}
572
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000573void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800574 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000575 if (!garbage_collect_code_) {
576 MutexLock mu(self, lock_);
577 IncreaseCodeCacheCapacity();
578 return;
579 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100580
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000581 // Wait for an existing collection, or let everyone know we are starting one.
582 {
583 ScopedThreadSuspension sts(self, kSuspended);
584 MutexLock mu(self, lock_);
585 if (WaitForPotentialCollectionToComplete(self)) {
586 return;
587 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000588 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000589 live_bitmap_.reset(CodeCacheBitmap::Create(
590 "code-cache-bitmap",
591 reinterpret_cast<uintptr_t>(code_map_->Begin()),
592 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000593 collection_in_progress_ = true;
594 }
595 }
596
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000597 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000598 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000599 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000600
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000601 bool do_full_collection = false;
602 {
603 MutexLock mu(self, lock_);
604 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000605 }
606
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000607 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
608 LOG(INFO) << "Do "
609 << (do_full_collection ? "full" : "partial")
610 << " code cache collection, code="
611 << PrettySize(CodeCacheSize())
612 << ", data=" << PrettySize(DataCacheSize());
613 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000614
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000615 DoCollection(self, /* collect_profiling_info */ do_full_collection);
616
617 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
618 LOG(INFO) << "After code cache collection, code="
619 << PrettySize(CodeCacheSize())
620 << ", data=" << PrettySize(DataCacheSize());
621 }
622
623 {
624 MutexLock mu(self, lock_);
625
626 // Increase the code cache only when we do partial collections.
627 // TODO: base this strategy on how full the code cache is?
628 if (do_full_collection) {
629 last_collection_increased_code_cache_ = false;
630 } else {
631 last_collection_increased_code_cache_ = true;
632 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000633 }
634
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000635 bool next_collection_will_be_full = ShouldDoFullCollection();
636
637 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100638 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000639 // Save the entry point of methods we have compiled, and update the entry
640 // point of those methods to the interpreter. If the method is invoked, the
641 // interpreter will update its entry point to the compiled code and call it.
642 for (ProfilingInfo* info : profiling_infos_) {
643 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
644 if (ContainsPc(entry_point)) {
645 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100646 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
647 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000648 }
649 }
650
651 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
652 }
653 live_bitmap_.reset(nullptr);
654 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000655 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000656 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000657 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000658}
659
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000660void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800661 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000662 MutexLock mu(self, lock_);
663 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000664 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000665 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
666 const void* code_ptr = it->first;
667 ArtMethod* method = it->second;
668 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000669 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000670 ++it;
671 } else {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000672 FreeCode(code_ptr, method);
673 it = method_code_map_.erase(it);
674 }
675 }
676}
677
678void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800679 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000680 {
681 MutexLock mu(self, lock_);
682 if (collect_profiling_info) {
683 // Clear the profiling info of methods that do not have compiled code as entrypoint.
684 // Also remove the saved entry point from the ProfilingInfo objects.
685 for (ProfilingInfo* info : profiling_infos_) {
686 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000687 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000688 info->GetMethod()->SetProfilingInfo(nullptr);
689 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000690
691 if (info->GetSavedEntryPoint() != nullptr) {
692 info->SetSavedEntryPoint(nullptr);
693 // We are going to move this method back to interpreter. Clear the counter now to
694 // give it a chance to be hot again.
695 info->GetMethod()->ClearCounter();
696 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000697 }
698 } else if (kIsDebugBuild) {
699 // Sanity check that the profiling infos do not have a dangling entry point.
700 for (ProfilingInfo* info : profiling_infos_) {
701 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100702 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000703 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000704
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000705 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
706 // an entry point is either:
707 // - an osr compiled code, that will be removed if not in a thread call stack.
708 // - discarded compiled code, that will be removed if not in a thread call stack.
709 for (const auto& it : method_code_map_) {
710 ArtMethod* method = it.second;
711 const void* code_ptr = it.first;
712 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
713 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
714 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
715 }
716 }
717
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000718 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000719 // on thread stacks).
720 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100721 }
722
723 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000724 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100725
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000726 // At this point, mutator threads are still running, and entrypoints of methods can
727 // change. We do know they cannot change to a code cache entry that is not marked,
728 // therefore we can safely remove those entries.
729 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000730
Nicolas Geoffray35122442016-03-02 12:05:30 +0000731 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +0100732 ScopedThreadSuspension sts(self, kSuspended);
733 gc::ScopedGCCriticalSection gcs(
734 self, gc::kGcCauseJitCodeCache, gc::kCollectorTypeJitCodeCache);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000735 MutexLock mu(self, lock_);
736 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100737 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000738 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000739 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000740 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
741 // that the compiled code would not get revived. As mutator threads run concurrently,
742 // they may have revived the compiled code, and now we are in the situation where
743 // a method has compiled code but no ProfilingInfo.
744 // We make sure compiled methods have a ProfilingInfo object. It is needed for
745 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -0700746 if (ContainsPc(ptr) &&
747 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000748 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000749 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000750 // Do a fence to make sure the clearing is seen before attaching to the method.
751 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000752 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -0700753 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000754 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000755 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100756 return true;
757 }
758 return false;
759 });
760 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000761 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100762 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800763}
764
Nicolas Geoffray35122442016-03-02 12:05:30 +0000765bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800766 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000767 // Check that methods we have compiled do have a ProfilingInfo object. We would
768 // have memory leaks of compiled code otherwise.
769 for (const auto& it : method_code_map_) {
770 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -0700771 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000772 const void* code_ptr = it.first;
773 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
774 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
775 // If the code is not dead, then we have a problem. Note that this can even
776 // happen just after a collection, as mutator threads are running in parallel
777 // and could deoptimize an existing compiled code.
778 return false;
779 }
780 }
781 }
782 return true;
783}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100784
785OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
786 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
787 if (kRuntimeISA == kArm) {
788 // On Thumb-2, the pc is offset by one.
789 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800790 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100791 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
792 return nullptr;
793 }
794
795 MutexLock mu(Thread::Current(), lock_);
796 if (method_code_map_.empty()) {
797 return nullptr;
798 }
799 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
800 --it;
801
802 const void* code_ptr = it->first;
803 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
804 if (!method_header->Contains(pc)) {
805 return nullptr;
806 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000807 if (kIsDebugBuild && method != nullptr) {
808 DCHECK_EQ(it->second, method)
809 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
810 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100811 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800812}
813
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000814OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
815 MutexLock mu(Thread::Current(), lock_);
816 auto it = osr_code_map_.find(method);
817 if (it == osr_code_map_.end()) {
818 return nullptr;
819 }
820 return OatQuickMethodHeader::FromCodePointer(it->second);
821}
822
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000823ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
824 ArtMethod* method,
825 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000826 bool retry_allocation)
827 // No thread safety analysis as we are using TryLock/Unlock explicitly.
828 NO_THREAD_SAFETY_ANALYSIS {
829 ProfilingInfo* info = nullptr;
830 if (!retry_allocation) {
831 // If we are allocating for the interpreter, just try to lock, to avoid
832 // lock contention with the JIT.
833 if (lock_.ExclusiveTryLock(self)) {
834 info = AddProfilingInfoInternal(self, method, entries);
835 lock_.ExclusiveUnlock(self);
836 }
837 } else {
838 {
839 MutexLock mu(self, lock_);
840 info = AddProfilingInfoInternal(self, method, entries);
841 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000842
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000843 if (info == nullptr) {
844 GarbageCollectCache(self);
845 MutexLock mu(self, lock_);
846 info = AddProfilingInfoInternal(self, method, entries);
847 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000848 }
849 return info;
850}
851
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000852ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000853 ArtMethod* method,
854 const std::vector<uint32_t>& entries) {
855 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100856 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000857 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000858
859 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -0700860 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000861 if (info != nullptr) {
862 return info;
863 }
864
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000865 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000866 if (data == nullptr) {
867 return nullptr;
868 }
869 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000870
871 // Make sure other threads see the data in the profiling info object before the
872 // store in the ArtMethod's ProfilingInfo pointer.
873 QuasiAtomic::ThreadFenceRelease();
874
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000875 method->SetProfilingInfo(info);
876 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000877 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000878 return info;
879}
880
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000881// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
882// is already held.
883void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
884 if (code_mspace_ == mspace) {
885 size_t result = code_end_;
886 code_end_ += increment;
887 return reinterpret_cast<void*>(result + code_map_->Begin());
888 } else {
889 DCHECK_EQ(data_mspace_, mspace);
890 size_t result = data_end_;
891 data_end_ += increment;
892 return reinterpret_cast<void*>(result + data_map_->Begin());
893 }
894}
895
Calin Juravle99629622016-04-19 16:33:46 +0100896void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
897 std::vector<MethodReference>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800898 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100899 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +0100900 for (const ProfilingInfo* info : profiling_infos_) {
901 ArtMethod* method = info->GetMethod();
902 const DexFile* dex_file = method->GetDexFile();
903 if (ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
904 methods.emplace_back(dex_file, method->GetDexMethodIndex());
Calin Juravle31f2c152015-10-23 17:56:15 +0100905 }
906 }
907}
908
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000909uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
910 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100911}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100912
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100913bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
914 MutexLock mu(Thread::Current(), lock_);
915 return osr_code_map_.find(method) != osr_code_map_.end();
916}
917
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000918bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
919 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100920 return false;
921 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000922
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000923 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000924 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
925 return false;
926 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000927
Andreas Gampe542451c2016-07-26 09:02:02 -0700928 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000929 if (info == nullptr) {
930 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000931 // Because the counter is not atomic, there are some rare cases where we may not
932 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
933 // "correct" this.
934 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100935 return false;
936 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000937
buzbee454b3b62016-04-07 14:42:47 -0700938 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000939 return false;
940 }
941
buzbee454b3b62016-04-07 14:42:47 -0700942 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100943 return true;
944}
945
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000946ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000947 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -0700948 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000949 if (info != nullptr) {
950 info->IncrementInlineUse();
951 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000952 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000953}
954
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000955void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000956 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -0700957 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000958 DCHECK(info != nullptr);
959 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000960}
961
buzbee454b3b62016-04-07 14:42:47 -0700962void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700963 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -0700964 DCHECK(info->IsMethodBeingCompiled(osr));
965 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100966}
967
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000968size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
969 MutexLock mu(Thread::Current(), lock_);
970 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
971}
972
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000973void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
974 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700975 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000976 if ((profiling_info != nullptr) &&
977 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
978 // Prevent future uses of the compiled code.
979 profiling_info->SetSavedEntryPoint(nullptr);
980 }
981
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000982 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
983 // The entrypoint is the one to invalidate, so we just update
984 // it to the interpreter entry point and clear the counter to get the method
985 // Jitted again.
986 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
987 method, GetQuickToInterpreterBridge());
988 method->ClearCounter();
989 } else {
990 MutexLock mu(Thread::Current(), lock_);
991 auto it = osr_code_map_.find(method);
992 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
993 // Remove the OSR method, to avoid using it again.
994 osr_code_map_.erase(it);
995 }
996 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000997 MutexLock mu(Thread::Current(), lock_);
998 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000999}
1000
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001001uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1002 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1003 uint8_t* result = reinterpret_cast<uint8_t*>(
1004 mspace_memalign(code_mspace_, alignment, code_size));
1005 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1006 // Ensure the header ends up at expected instruction alignment.
1007 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1008 used_memory_for_code_ += mspace_usable_size(result);
1009 return result;
1010}
1011
1012void JitCodeCache::FreeCode(uint8_t* code) {
1013 used_memory_for_code_ -= mspace_usable_size(code);
1014 mspace_free(code_mspace_, code);
1015}
1016
1017uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1018 void* result = mspace_malloc(data_mspace_, data_size);
1019 used_memory_for_data_ += mspace_usable_size(result);
1020 return reinterpret_cast<uint8_t*>(result);
1021}
1022
1023void JitCodeCache::FreeData(uint8_t* data) {
1024 used_memory_for_data_ -= mspace_usable_size(data);
1025 mspace_free(data_mspace_, data);
1026}
1027
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001028void JitCodeCache::Dump(std::ostream& os) {
1029 MutexLock mu(Thread::Current(), lock_);
1030 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1031 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1032 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1033 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1034 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1035 << "Total number of JIT compilations for on stack replacement: "
1036 << number_of_osr_compilations_ << "\n"
1037 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1038 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001039 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1040 histogram_code_memory_use_.PrintMemoryUse(os);
1041 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001042}
1043
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001044} // namespace jit
1045} // namespace art