blob: 74ff741d931d681265afe20f9b479cb1baac5f98 [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"
Calin Juravle66f55232015-12-08 15:09:10 +000022#include "base/stl_util.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010023#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000024#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010025#include "entrypoints/runtime_asm_entrypoints.h"
26#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000027#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010028#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080029#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080030#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000031#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080033
34namespace art {
35namespace jit {
36
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010037static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
38static constexpr int kProtData = PROT_READ | PROT_WRITE;
39static constexpr int kProtCode = PROT_READ | PROT_EXEC;
40
41#define CHECKED_MPROTECT(memory, size, prot) \
42 do { \
43 int rc = mprotect(memory, size, prot); \
44 if (UNLIKELY(rc != 0)) { \
45 errno = rc; \
46 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
47 } \
48 } while (false) \
49
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000050JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
51 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000052 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000053 std::string* error_msg) {
54 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000055
56 // Generating debug information is mostly for using the 'perf' tool, which does
57 // not work with ashmem.
58 bool use_ashmem = !generate_debug_info;
59 // With 'perf', we want a 1-1 mapping between an address and a method.
60 bool garbage_collect_code = !generate_debug_info;
61
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 // We need to have 32 bit offsets from method headers in code cache which point to things
63 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
64 // Ensure we're below 1 GB to be safe.
65 if (max_capacity > 1 * GB) {
66 std::ostringstream oss;
67 oss << "Maxium code cache capacity is limited to 1 GB, "
68 << PrettySize(max_capacity) << " is too big";
69 *error_msg = oss.str();
70 return nullptr;
71 }
72
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080073 std::string error_str;
74 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010075 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000076 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010077 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080078 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000079 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080080 *error_msg = oss.str();
81 return nullptr;
82 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010083
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000084 // Align both capacities to page size, as that's the unit mspaces use.
85 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
86 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
87
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000088 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010089 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000090 size_t data_size = max_capacity / 2;
91 size_t code_size = max_capacity - data_size;
92 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010093 uint8_t* divider = data_map->Begin() + data_size;
94
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000095 MemMap* code_map =
96 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010097 if (code_map == nullptr) {
98 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000099 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100100 *error_msg = oss.str();
101 return nullptr;
102 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000104 data_size = initial_capacity / 2;
105 code_size = initial_capacity - data_size;
106 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000107 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000108 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800109}
110
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000111JitCodeCache::JitCodeCache(MemMap* code_map,
112 MemMap* data_map,
113 size_t initial_code_capacity,
114 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000115 size_t max_capacity,
116 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100117 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100118 lock_cond_("Jit code cache variable", lock_),
119 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000121 data_map_(data_map),
122 max_capacity_(max_capacity),
123 current_capacity_(initial_code_capacity + initial_data_capacity),
124 code_end_(initial_code_capacity),
125 data_end_(initial_data_capacity),
Calin Juravle31f2c152015-10-23 17:56:15 +0100126 has_done_one_collection_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000127 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000128 garbage_collect_code_(garbage_collect_code),
129 number_of_compilations_(0) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100130
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000131 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000132 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
133 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100134
135 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
136 PLOG(FATAL) << "create_mspace_with_base failed";
137 }
138
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000139 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100140
141 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
142 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100143
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000144 VLOG(jit) << "Created jit code cache: initial data size="
145 << PrettySize(initial_data_capacity)
146 << ", initial code size="
147 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800148}
149
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100150bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100151 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800152}
153
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000154bool JitCodeCache::ContainsMethod(ArtMethod* method) {
155 MutexLock mu(Thread::Current(), lock_);
156 for (auto& it : method_code_map_) {
157 if (it.second == method) {
158 return true;
159 }
160 }
161 return false;
162}
163
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100164class ScopedCodeCacheWrite {
165 public:
166 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
167 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800168 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100169 ~ScopedCodeCacheWrite() {
170 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
171 }
172 private:
173 MemMap* const code_map_;
174
175 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
176};
177
178uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100179 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100180 const uint8_t* mapping_table,
181 const uint8_t* vmap_table,
182 const uint8_t* gc_map,
183 size_t frame_size_in_bytes,
184 size_t core_spill_mask,
185 size_t fp_spill_mask,
186 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000187 size_t code_size,
188 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100189 uint8_t* result = CommitCodeInternal(self,
190 method,
191 mapping_table,
192 vmap_table,
193 gc_map,
194 frame_size_in_bytes,
195 core_spill_mask,
196 fp_spill_mask,
197 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000198 code_size,
199 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100200 if (result == nullptr) {
201 // Retry.
202 GarbageCollectCache(self);
203 result = CommitCodeInternal(self,
204 method,
205 mapping_table,
206 vmap_table,
207 gc_map,
208 frame_size_in_bytes,
209 core_spill_mask,
210 fp_spill_mask,
211 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000212 code_size,
213 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100214 }
215 return result;
216}
217
218bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
219 bool in_collection = false;
220 while (collection_in_progress_) {
221 in_collection = true;
222 lock_cond_.Wait(self);
223 }
224 return in_collection;
225}
226
227static uintptr_t FromCodeToAllocation(const void* code) {
228 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
229 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
230}
231
232void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
233 uintptr_t allocation = FromCodeToAllocation(code_ptr);
234 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
235 const uint8_t* data = method_header->GetNativeGcMap();
David Srbecky5cc349f2015-12-18 15:04:48 +0000236 // Notify native debugger that we are about to remove the code.
237 // It does nothing if we are not using native debugger.
238 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100239 if (data != nullptr) {
240 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
241 }
242 data = method_header->GetMappingTable();
243 if (data != nullptr) {
244 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
245 }
246 // Use the offset directly to prevent sanity check that the method is
247 // compiled with optimizing.
248 // TODO(ngeoffray): Clean up.
249 if (method_header->vmap_table_offset_ != 0) {
250 data = method_header->code_ - method_header->vmap_table_offset_;
251 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
252 }
253 mspace_free(code_mspace_, reinterpret_cast<uint8_t*>(allocation));
254}
255
256void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
257 MutexLock mu(self, lock_);
258 // We do not check if a code cache GC is in progress, as this method comes
259 // with the classlinker_classes_lock_ held, and suspending ourselves could
260 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000261 {
262 ScopedCodeCacheWrite scc(code_map_.get());
263 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
264 if (alloc.ContainsUnsafe(it->second)) {
265 FreeCode(it->first, it->second);
266 it = method_code_map_.erase(it);
267 } else {
268 ++it;
269 }
270 }
271 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000272 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
273 if (alloc.ContainsUnsafe(it->first)) {
274 // Note that the code has already been removed in the loop above.
275 it = osr_code_map_.erase(it);
276 } else {
277 ++it;
278 }
279 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000280 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
281 ProfilingInfo* info = *it;
282 if (alloc.ContainsUnsafe(info->GetMethod())) {
283 info->GetMethod()->SetProfilingInfo(nullptr);
284 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
285 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100286 } else {
287 ++it;
288 }
289 }
290}
291
292uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
293 ArtMethod* method,
294 const uint8_t* mapping_table,
295 const uint8_t* vmap_table,
296 const uint8_t* gc_map,
297 size_t frame_size_in_bytes,
298 size_t core_spill_mask,
299 size_t fp_spill_mask,
300 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000301 size_t code_size,
302 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100303 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
304 // Ensure the header ends up at expected instruction alignment.
305 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
306 size_t total_size = header_size + code_size;
307
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100308 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100309 uint8_t* code_ptr = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100310 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000311 ScopedThreadSuspension sts(self, kSuspended);
312 MutexLock mu(self, lock_);
313 WaitForPotentialCollectionToComplete(self);
314 {
315 ScopedCodeCacheWrite scc(code_map_.get());
316 uint8_t* result = reinterpret_cast<uint8_t*>(
317 mspace_memalign(code_mspace_, alignment, total_size));
318 if (result == nullptr) {
319 return nullptr;
320 }
321 code_ptr = result + header_size;
322 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(code_ptr), alignment);
323
324 std::copy(code, code + code_size, code_ptr);
325 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
326 new (method_header) OatQuickMethodHeader(
327 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
328 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
329 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
330 frame_size_in_bytes,
331 core_spill_mask,
332 fp_spill_mask,
333 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100334 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100335
Roland Levillain32430262016-02-01 15:23:20 +0000336 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
337 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000338 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100339 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000340 // We need to update the entry point in the runnable state for the instrumentation.
341 {
342 MutexLock mu(self, lock_);
343 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000344 if (osr) {
345 osr_code_map_.Put(method, code_ptr);
346 } else {
347 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
348 method, method_header->GetEntryPoint());
349 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000350 if (collection_in_progress_) {
351 // We need to update the live bitmap if there is a GC to ensure it sees this new
352 // code.
353 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
354 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000355 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000356 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000357 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000358 << PrettyMethod(method) << "@" << method
359 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
360 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
361 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
362 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
363 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100364
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100365 return reinterpret_cast<uint8_t*>(method_header);
366}
367
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000368size_t JitCodeCache::NumberOfCompilations() {
369 MutexLock mu(Thread::Current(), lock_);
370 return number_of_compilations_;
371}
372
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100373size_t JitCodeCache::CodeCacheSize() {
374 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000375 return CodeCacheSizeLocked();
376}
377
378size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100379 size_t bytes_allocated = 0;
380 mspace_inspect_all(code_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
381 return bytes_allocated;
382}
383
384size_t JitCodeCache::DataCacheSize() {
385 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000386 return DataCacheSizeLocked();
387}
388
389size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100390 size_t bytes_allocated = 0;
391 mspace_inspect_all(data_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
392 return bytes_allocated;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800393}
394
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100395size_t JitCodeCache::NumberOfCompiledCode() {
396 MutexLock mu(Thread::Current(), lock_);
397 return method_code_map_.size();
398}
399
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000400void JitCodeCache::ClearData(Thread* self, void* data) {
401 MutexLock mu(self, lock_);
402 mspace_free(data_mspace_, data);
403}
404
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100405uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100406 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100407 uint8_t* result = nullptr;
408
409 {
410 ScopedThreadSuspension sts(self, kSuspended);
411 MutexLock mu(self, lock_);
412 WaitForPotentialCollectionToComplete(self);
413 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
414 }
415
416 if (result == nullptr) {
417 // Retry.
418 GarbageCollectCache(self);
419 ScopedThreadSuspension sts(self, kSuspended);
420 MutexLock mu(self, lock_);
421 WaitForPotentialCollectionToComplete(self);
422 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
423 }
424
425 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100426}
427
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800428uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100429 uint8_t* result = ReserveData(self, end - begin);
430 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800431 return nullptr; // Out of space in the data cache.
432 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100433 std::copy(begin, end, result);
434 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800435}
436
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100437class MarkCodeVisitor FINAL : public StackVisitor {
438 public:
439 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
440 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
441 code_cache_(code_cache_in),
442 bitmap_(code_cache_->GetLiveBitmap()) {}
443
444 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
445 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
446 if (method_header == nullptr) {
447 return true;
448 }
449 const void* code = method_header->GetCode();
450 if (code_cache_->ContainsPc(code)) {
451 // Use the atomic set version, as multiple threads are executing this code.
452 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
453 }
454 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800455 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100456
457 private:
458 JitCodeCache* const code_cache_;
459 CodeCacheBitmap* const bitmap_;
460};
461
462class MarkCodeClosure FINAL : public Closure {
463 public:
464 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
465 : code_cache_(code_cache), barrier_(barrier) {}
466
467 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
468 DCHECK(thread == Thread::Current() || thread->IsSuspended());
469 MarkCodeVisitor visitor(thread, code_cache_);
470 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000471 if (kIsDebugBuild) {
472 // The stack walking code queries the side instrumentation stack if it
473 // sees an instrumentation exit pc, so the JIT code of methods in that stack
474 // must have been seen. We sanity check this below.
475 for (const instrumentation::InstrumentationStackFrame& frame
476 : *thread->GetInstrumentationStack()) {
477 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
478 // its stack frame, it is not the method owning return_pc_. We just pass null to
479 // LookupMethodHeader: the method is only checked against in debug builds.
480 OatQuickMethodHeader* method_header =
481 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
482 if (method_header != nullptr) {
483 const void* code = method_header->GetCode();
484 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
485 }
486 }
487 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700488 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800489 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100490
491 private:
492 JitCodeCache* const code_cache_;
493 Barrier* const barrier_;
494};
495
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000496void JitCodeCache::NotifyCollectionDone(Thread* self) {
497 collection_in_progress_ = false;
498 lock_cond_.Broadcast(self);
499}
500
501void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
502 size_t per_space_footprint = new_footprint / 2;
503 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
504 DCHECK_EQ(per_space_footprint * 2, new_footprint);
505 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
506 {
507 ScopedCodeCacheWrite scc(code_map_.get());
508 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
509 }
510}
511
512bool JitCodeCache::IncreaseCodeCacheCapacity() {
513 if (current_capacity_ == max_capacity_) {
514 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100515 }
516
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000517 // Double the capacity if we're below 1MB, or increase it by 1MB if
518 // we're above.
519 if (current_capacity_ < 1 * MB) {
520 current_capacity_ *= 2;
521 } else {
522 current_capacity_ += 1 * MB;
523 }
524 if (current_capacity_ > max_capacity_) {
525 current_capacity_ = max_capacity_;
526 }
527
528 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
529 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
530 }
531
532 SetFootprintLimit(current_capacity_);
533
534 return true;
535}
536
537void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000538 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100539
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000540 // Wait for an existing collection, or let everyone know we are starting one.
541 {
542 ScopedThreadSuspension sts(self, kSuspended);
543 MutexLock mu(self, lock_);
544 if (WaitForPotentialCollectionToComplete(self)) {
545 return;
546 } else {
547 collection_in_progress_ = true;
548 }
549 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000550
551 // Check if we just need to grow the capacity. If we don't, allocate the bitmap while
552 // we hold the lock.
553 {
554 MutexLock mu(self, lock_);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000555 if (!garbage_collect_code_) {
556 IncreaseCodeCacheCapacity();
557 NotifyCollectionDone(self);
558 return;
559 } else if (has_done_one_collection_ && IncreaseCodeCacheCapacity()) {
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000560 has_done_one_collection_ = false;
561 NotifyCollectionDone(self);
562 return;
563 } else {
564 live_bitmap_.reset(CodeCacheBitmap::Create(
565 "code-cache-bitmap",
566 reinterpret_cast<uintptr_t>(code_map_->Begin()),
567 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
568 }
569 }
570
571 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
572 LOG(INFO) << "Clearing code cache, code="
573 << PrettySize(CodeCacheSize())
574 << ", data=" << PrettySize(DataCacheSize());
575 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100576 // Walk over all compiled methods and set the entry points of these
577 // methods to interpreter.
578 {
579 MutexLock mu(self, lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100580 for (auto& it : method_code_map_) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000581 instrumentation->UpdateMethodsCode(it.second, GetQuickToInterpreterBridge());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100582 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000583 for (ProfilingInfo* info : profiling_infos_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100584 if (!info->IsMethodBeingCompiled()) {
585 info->GetMethod()->SetProfilingInfo(nullptr);
586 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000587 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000588
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000589 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000590 // on thread stacks).
591 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100592 }
593
594 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
595 {
596 Barrier barrier(0);
Nicolas Geoffray62623402015-10-28 19:15:05 +0000597 size_t threads_running_checkpoint = 0;
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000598 MarkCodeClosure closure(this, &barrier);
599 threads_running_checkpoint =
600 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
601 // Now that we have run our checkpoint, move to a suspended state and wait
602 // for other threads to run the checkpoint.
603 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100604 if (threads_running_checkpoint != 0) {
605 barrier.Increment(self, threads_running_checkpoint);
606 }
607 }
608
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100609 {
610 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000611 // Free unused compiled code, and restore the entry point of used compiled code.
612 {
613 ScopedCodeCacheWrite scc(code_map_.get());
614 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
615 const void* code_ptr = it->first;
616 ArtMethod* method = it->second;
617 uintptr_t allocation = FromCodeToAllocation(code_ptr);
618 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
619 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000620 instrumentation->UpdateMethodsCode(method, method_header->GetEntryPoint());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000621 ++it;
622 } else {
623 method->ClearCounter();
624 DCHECK_NE(method->GetEntryPointFromQuickCompiledCode(), method_header->GetEntryPoint());
625 FreeCode(code_ptr, method);
626 it = method_code_map_.erase(it);
627 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100628 }
629 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000630
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100631 void* data_mspace = data_mspace_;
632 // Free all profiling infos of methods that were not being compiled.
633 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
634 [data_mspace] (ProfilingInfo* info) {
635 if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
636 mspace_free(data_mspace, reinterpret_cast<uint8_t*>(info));
637 return true;
638 }
639 return false;
640 });
641 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000642
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000643 live_bitmap_.reset(nullptr);
644 has_done_one_collection_ = true;
645 NotifyCollectionDone(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100646 }
647
648 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
649 LOG(INFO) << "After clearing code cache, code="
650 << PrettySize(CodeCacheSize())
651 << ", data=" << PrettySize(DataCacheSize());
652 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800653}
654
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100655
656OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
657 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
658 if (kRuntimeISA == kArm) {
659 // On Thumb-2, the pc is offset by one.
660 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800661 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100662 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
663 return nullptr;
664 }
665
666 MutexLock mu(Thread::Current(), lock_);
667 if (method_code_map_.empty()) {
668 return nullptr;
669 }
670 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
671 --it;
672
673 const void* code_ptr = it->first;
674 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
675 if (!method_header->Contains(pc)) {
676 return nullptr;
677 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000678 if (kIsDebugBuild && method != nullptr) {
679 DCHECK_EQ(it->second, method)
680 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
681 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100682 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800683}
684
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000685OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
686 MutexLock mu(Thread::Current(), lock_);
687 auto it = osr_code_map_.find(method);
688 if (it == osr_code_map_.end()) {
689 return nullptr;
690 }
691 return OatQuickMethodHeader::FromCodePointer(it->second);
692}
693
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000694ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
695 ArtMethod* method,
696 const std::vector<uint32_t>& entries,
697 bool retry_allocation) {
698 ProfilingInfo* info = AddProfilingInfoInternal(self, method, entries);
699
700 if (info == nullptr && retry_allocation) {
701 GarbageCollectCache(self);
702 info = AddProfilingInfoInternal(self, method, entries);
703 }
704 return info;
705}
706
707ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self,
708 ArtMethod* method,
709 const std::vector<uint32_t>& entries) {
710 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100711 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000712 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000713 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000714
715 // Check whether some other thread has concurrently created it.
716 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
717 if (info != nullptr) {
718 return info;
719 }
720
721 uint8_t* data = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, profile_info_size));
722 if (data == nullptr) {
723 return nullptr;
724 }
725 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000726
727 // Make sure other threads see the data in the profiling info object before the
728 // store in the ArtMethod's ProfilingInfo pointer.
729 QuasiAtomic::ThreadFenceRelease();
730
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000731 method->SetProfilingInfo(info);
732 profiling_infos_.push_back(info);
733 return info;
734}
735
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000736// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
737// is already held.
738void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
739 if (code_mspace_ == mspace) {
740 size_t result = code_end_;
741 code_end_ += increment;
742 return reinterpret_cast<void*>(result + code_map_->Begin());
743 } else {
744 DCHECK_EQ(data_mspace_, mspace);
745 size_t result = data_end_;
746 data_end_ += increment;
747 return reinterpret_cast<void*>(result + data_map_->Begin());
748 }
749}
750
Calin Juravleb4eddd22016-01-13 15:52:33 -0800751void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000752 std::vector<ArtMethod*>& methods) {
Calin Juravle31f2c152015-10-23 17:56:15 +0100753 MutexLock mu(Thread::Current(), lock_);
754 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000755 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000756 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100757 }
758 }
759}
760
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000761uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
762 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100763}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100764
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000765bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
766 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100767 return false;
768 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000769
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000770 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000771 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
772 return false;
773 }
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000774 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100775 if (info == nullptr || info->IsMethodBeingCompiled()) {
776 return false;
777 }
778 info->SetIsMethodBeingCompiled(true);
779 return true;
780}
781
782void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
783 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
784 DCHECK(info->IsMethodBeingCompiled());
785 info->SetIsMethodBeingCompiled(false);
786}
787
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000788size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
789 MutexLock mu(Thread::Current(), lock_);
790 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
791}
792
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000793void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
794 const OatQuickMethodHeader* header) {
795 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
796 // The entrypoint is the one to invalidate, so we just update
797 // it to the interpreter entry point and clear the counter to get the method
798 // Jitted again.
799 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
800 method, GetQuickToInterpreterBridge());
801 method->ClearCounter();
802 } else {
803 MutexLock mu(Thread::Current(), lock_);
804 auto it = osr_code_map_.find(method);
805 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
806 // Remove the OSR method, to avoid using it again.
807 osr_code_map_.erase(it);
808 }
809 }
810}
811
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800812} // namespace jit
813} // namespace art