blob: 1ac57b1d840871f38f419fcae486fb93caf961ab [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,
52 std::string* error_msg) {
53 CHECK_GE(max_capacity, initial_capacity);
54 // We need to have 32 bit offsets from method headers in code cache which point to things
55 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
56 // Ensure we're below 1 GB to be safe.
57 if (max_capacity > 1 * GB) {
58 std::ostringstream oss;
59 oss << "Maxium code cache capacity is limited to 1 GB, "
60 << PrettySize(max_capacity) << " is too big";
61 *error_msg = oss.str();
62 return nullptr;
63 }
64
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080065 std::string error_str;
66 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010067 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000068 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010069 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080070 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000071 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080072 *error_msg = oss.str();
73 return nullptr;
74 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010075
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000076 // Align both capacities to page size, as that's the unit mspaces use.
77 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
78 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
79
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000080 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010081 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000082 size_t data_size = max_capacity / 2;
83 size_t code_size = max_capacity - data_size;
84 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010085 uint8_t* divider = data_map->Begin() + data_size;
86
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010087 MemMap* code_map = data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str);
88 if (code_map == nullptr) {
89 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000090 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010091 *error_msg = oss.str();
92 return nullptr;
93 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010094 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000095 data_size = initial_capacity / 2;
96 code_size = initial_capacity - data_size;
97 DCHECK_EQ(code_size + data_size, initial_capacity);
98 return new JitCodeCache(code_map, data_map, code_size, data_size, max_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080099}
100
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000101JitCodeCache::JitCodeCache(MemMap* code_map,
102 MemMap* data_map,
103 size_t initial_code_capacity,
104 size_t initial_data_capacity,
105 size_t max_capacity)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100106 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100107 lock_cond_("Jit code cache variable", lock_),
108 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100109 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000110 data_map_(data_map),
111 max_capacity_(max_capacity),
112 current_capacity_(initial_code_capacity + initial_data_capacity),
113 code_end_(initial_code_capacity),
114 data_end_(initial_data_capacity),
Calin Juravle31f2c152015-10-23 17:56:15 +0100115 has_done_one_collection_(false),
116 last_update_time_ns_(0) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100117
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000118 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
119 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120
121 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
122 PLOG(FATAL) << "create_mspace_with_base failed";
123 }
124
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000125 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100126
127 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
128 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100129
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000130 VLOG(jit) << "Created jit code cache: initial data size="
131 << PrettySize(initial_data_capacity)
132 << ", initial code size="
133 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800134}
135
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100136bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100137 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800138}
139
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000140bool JitCodeCache::ContainsMethod(ArtMethod* method) {
141 MutexLock mu(Thread::Current(), lock_);
142 for (auto& it : method_code_map_) {
143 if (it.second == method) {
144 return true;
145 }
146 }
147 return false;
148}
149
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100150class ScopedCodeCacheWrite {
151 public:
152 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
153 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800154 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100155 ~ScopedCodeCacheWrite() {
156 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
157 }
158 private:
159 MemMap* const code_map_;
160
161 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
162};
163
164uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100165 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100166 const uint8_t* mapping_table,
167 const uint8_t* vmap_table,
168 const uint8_t* gc_map,
169 size_t frame_size_in_bytes,
170 size_t core_spill_mask,
171 size_t fp_spill_mask,
172 const uint8_t* code,
173 size_t code_size) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100174 uint8_t* result = CommitCodeInternal(self,
175 method,
176 mapping_table,
177 vmap_table,
178 gc_map,
179 frame_size_in_bytes,
180 core_spill_mask,
181 fp_spill_mask,
182 code,
183 code_size);
184 if (result == nullptr) {
185 // Retry.
186 GarbageCollectCache(self);
187 result = CommitCodeInternal(self,
188 method,
189 mapping_table,
190 vmap_table,
191 gc_map,
192 frame_size_in_bytes,
193 core_spill_mask,
194 fp_spill_mask,
195 code,
196 code_size);
197 }
198 return result;
199}
200
201bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
202 bool in_collection = false;
203 while (collection_in_progress_) {
204 in_collection = true;
205 lock_cond_.Wait(self);
206 }
207 return in_collection;
208}
209
210static uintptr_t FromCodeToAllocation(const void* code) {
211 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
212 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
213}
214
215void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
216 uintptr_t allocation = FromCodeToAllocation(code_ptr);
217 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
218 const uint8_t* data = method_header->GetNativeGcMap();
David Srbecky5cc349f2015-12-18 15:04:48 +0000219 // Notify native debugger that we are about to remove the code.
220 // It does nothing if we are not using native debugger.
221 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100222 if (data != nullptr) {
223 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
224 }
225 data = method_header->GetMappingTable();
226 if (data != nullptr) {
227 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
228 }
229 // Use the offset directly to prevent sanity check that the method is
230 // compiled with optimizing.
231 // TODO(ngeoffray): Clean up.
232 if (method_header->vmap_table_offset_ != 0) {
233 data = method_header->code_ - method_header->vmap_table_offset_;
234 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
235 }
236 mspace_free(code_mspace_, reinterpret_cast<uint8_t*>(allocation));
237}
238
239void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
240 MutexLock mu(self, lock_);
241 // We do not check if a code cache GC is in progress, as this method comes
242 // with the classlinker_classes_lock_ held, and suspending ourselves could
243 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000244 {
245 ScopedCodeCacheWrite scc(code_map_.get());
246 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
247 if (alloc.ContainsUnsafe(it->second)) {
248 FreeCode(it->first, it->second);
249 it = method_code_map_.erase(it);
250 } else {
251 ++it;
252 }
253 }
254 }
255 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
256 ProfilingInfo* info = *it;
257 if (alloc.ContainsUnsafe(info->GetMethod())) {
258 info->GetMethod()->SetProfilingInfo(nullptr);
259 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
260 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100261 } else {
262 ++it;
263 }
264 }
265}
266
267uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
268 ArtMethod* method,
269 const uint8_t* mapping_table,
270 const uint8_t* vmap_table,
271 const uint8_t* gc_map,
272 size_t frame_size_in_bytes,
273 size_t core_spill_mask,
274 size_t fp_spill_mask,
275 const uint8_t* code,
276 size_t code_size) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100277 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
278 // Ensure the header ends up at expected instruction alignment.
279 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
280 size_t total_size = header_size + code_size;
281
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100282 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100283 uint8_t* code_ptr = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100284 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000285 ScopedThreadSuspension sts(self, kSuspended);
286 MutexLock mu(self, lock_);
287 WaitForPotentialCollectionToComplete(self);
288 {
289 ScopedCodeCacheWrite scc(code_map_.get());
290 uint8_t* result = reinterpret_cast<uint8_t*>(
291 mspace_memalign(code_mspace_, alignment, total_size));
292 if (result == nullptr) {
293 return nullptr;
294 }
295 code_ptr = result + header_size;
296 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(code_ptr), alignment);
297
298 std::copy(code, code + code_size, code_ptr);
299 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
300 new (method_header) OatQuickMethodHeader(
301 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
302 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
303 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
304 frame_size_in_bytes,
305 core_spill_mask,
306 fp_spill_mask,
307 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100308 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100309
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000310 __builtin___clear_cache(reinterpret_cast<char*>(code_ptr),
311 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100312 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000313 // We need to update the entry point in the runnable state for the instrumentation.
314 {
315 MutexLock mu(self, lock_);
316 method_code_map_.Put(code_ptr, method);
317 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
318 method, method_header->GetEntryPoint());
319 if (collection_in_progress_) {
320 // We need to update the live bitmap if there is a GC to ensure it sees this new
321 // code.
322 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
323 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000324 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000325 VLOG(jit)
326 << "JIT added "
327 << PrettyMethod(method) << "@" << method
328 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
329 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
330 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
331 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
332 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100333
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100334 return reinterpret_cast<uint8_t*>(method_header);
335}
336
337size_t JitCodeCache::CodeCacheSize() {
338 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000339 return CodeCacheSizeLocked();
340}
341
342size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100343 size_t bytes_allocated = 0;
344 mspace_inspect_all(code_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
345 return bytes_allocated;
346}
347
348size_t JitCodeCache::DataCacheSize() {
349 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000350 return DataCacheSizeLocked();
351}
352
353size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100354 size_t bytes_allocated = 0;
355 mspace_inspect_all(data_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
356 return bytes_allocated;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800357}
358
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100359size_t JitCodeCache::NumberOfCompiledCode() {
360 MutexLock mu(Thread::Current(), lock_);
361 return method_code_map_.size();
362}
363
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000364void JitCodeCache::ClearData(Thread* self, void* data) {
365 MutexLock mu(self, lock_);
366 mspace_free(data_mspace_, data);
367}
368
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100369uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100370 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100371 uint8_t* result = nullptr;
372
373 {
374 ScopedThreadSuspension sts(self, kSuspended);
375 MutexLock mu(self, lock_);
376 WaitForPotentialCollectionToComplete(self);
377 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
378 }
379
380 if (result == nullptr) {
381 // Retry.
382 GarbageCollectCache(self);
383 ScopedThreadSuspension sts(self, kSuspended);
384 MutexLock mu(self, lock_);
385 WaitForPotentialCollectionToComplete(self);
386 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
387 }
388
389 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100390}
391
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800392uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100393 uint8_t* result = ReserveData(self, end - begin);
394 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800395 return nullptr; // Out of space in the data cache.
396 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100397 std::copy(begin, end, result);
398 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800399}
400
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100401class MarkCodeVisitor FINAL : public StackVisitor {
402 public:
403 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
404 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
405 code_cache_(code_cache_in),
406 bitmap_(code_cache_->GetLiveBitmap()) {}
407
408 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
409 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
410 if (method_header == nullptr) {
411 return true;
412 }
413 const void* code = method_header->GetCode();
414 if (code_cache_->ContainsPc(code)) {
415 // Use the atomic set version, as multiple threads are executing this code.
416 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
417 }
418 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800419 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100420
421 private:
422 JitCodeCache* const code_cache_;
423 CodeCacheBitmap* const bitmap_;
424};
425
426class MarkCodeClosure FINAL : public Closure {
427 public:
428 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
429 : code_cache_(code_cache), barrier_(barrier) {}
430
431 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
432 DCHECK(thread == Thread::Current() || thread->IsSuspended());
433 MarkCodeVisitor visitor(thread, code_cache_);
434 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000435 if (kIsDebugBuild) {
436 // The stack walking code queries the side instrumentation stack if it
437 // sees an instrumentation exit pc, so the JIT code of methods in that stack
438 // must have been seen. We sanity check this below.
439 for (const instrumentation::InstrumentationStackFrame& frame
440 : *thread->GetInstrumentationStack()) {
441 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
442 // its stack frame, it is not the method owning return_pc_. We just pass null to
443 // LookupMethodHeader: the method is only checked against in debug builds.
444 OatQuickMethodHeader* method_header =
445 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
446 if (method_header != nullptr) {
447 const void* code = method_header->GetCode();
448 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
449 }
450 }
451 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700452 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800453 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100454
455 private:
456 JitCodeCache* const code_cache_;
457 Barrier* const barrier_;
458};
459
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000460void JitCodeCache::NotifyCollectionDone(Thread* self) {
461 collection_in_progress_ = false;
462 lock_cond_.Broadcast(self);
463}
464
465void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
466 size_t per_space_footprint = new_footprint / 2;
467 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
468 DCHECK_EQ(per_space_footprint * 2, new_footprint);
469 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
470 {
471 ScopedCodeCacheWrite scc(code_map_.get());
472 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
473 }
474}
475
476bool JitCodeCache::IncreaseCodeCacheCapacity() {
477 if (current_capacity_ == max_capacity_) {
478 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100479 }
480
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000481 // Double the capacity if we're below 1MB, or increase it by 1MB if
482 // we're above.
483 if (current_capacity_ < 1 * MB) {
484 current_capacity_ *= 2;
485 } else {
486 current_capacity_ += 1 * MB;
487 }
488 if (current_capacity_ > max_capacity_) {
489 current_capacity_ = max_capacity_;
490 }
491
492 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
493 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
494 }
495
496 SetFootprintLimit(current_capacity_);
497
498 return true;
499}
500
501void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000502 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100503
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000504 // Wait for an existing collection, or let everyone know we are starting one.
505 {
506 ScopedThreadSuspension sts(self, kSuspended);
507 MutexLock mu(self, lock_);
508 if (WaitForPotentialCollectionToComplete(self)) {
509 return;
510 } else {
511 collection_in_progress_ = true;
512 }
513 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000514
515 // Check if we just need to grow the capacity. If we don't, allocate the bitmap while
516 // we hold the lock.
517 {
518 MutexLock mu(self, lock_);
519 if (has_done_one_collection_ && IncreaseCodeCacheCapacity()) {
520 has_done_one_collection_ = false;
521 NotifyCollectionDone(self);
522 return;
523 } else {
524 live_bitmap_.reset(CodeCacheBitmap::Create(
525 "code-cache-bitmap",
526 reinterpret_cast<uintptr_t>(code_map_->Begin()),
527 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
528 }
529 }
530
531 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
532 LOG(INFO) << "Clearing code cache, code="
533 << PrettySize(CodeCacheSize())
534 << ", data=" << PrettySize(DataCacheSize());
535 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100536 // Walk over all compiled methods and set the entry points of these
537 // methods to interpreter.
538 {
539 MutexLock mu(self, lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100540 for (auto& it : method_code_map_) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000541 instrumentation->UpdateMethodsCode(it.second, GetQuickToInterpreterBridge());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100542 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000543 for (ProfilingInfo* info : profiling_infos_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100544 if (!info->IsMethodBeingCompiled()) {
545 info->GetMethod()->SetProfilingInfo(nullptr);
546 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000547 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100548 }
549
550 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
551 {
552 Barrier barrier(0);
Nicolas Geoffray62623402015-10-28 19:15:05 +0000553 size_t threads_running_checkpoint = 0;
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000554 MarkCodeClosure closure(this, &barrier);
555 threads_running_checkpoint =
556 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
557 // Now that we have run our checkpoint, move to a suspended state and wait
558 // for other threads to run the checkpoint.
559 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100560 if (threads_running_checkpoint != 0) {
561 barrier.Increment(self, threads_running_checkpoint);
562 }
563 }
564
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100565 {
566 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000567 // Free unused compiled code, and restore the entry point of used compiled code.
568 {
569 ScopedCodeCacheWrite scc(code_map_.get());
570 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
571 const void* code_ptr = it->first;
572 ArtMethod* method = it->second;
573 uintptr_t allocation = FromCodeToAllocation(code_ptr);
574 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
575 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000576 instrumentation->UpdateMethodsCode(method, method_header->GetEntryPoint());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000577 ++it;
578 } else {
579 method->ClearCounter();
580 DCHECK_NE(method->GetEntryPointFromQuickCompiledCode(), method_header->GetEntryPoint());
581 FreeCode(code_ptr, method);
582 it = method_code_map_.erase(it);
583 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100584 }
585 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000586
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100587 void* data_mspace = data_mspace_;
588 // Free all profiling infos of methods that were not being compiled.
589 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
590 [data_mspace] (ProfilingInfo* info) {
591 if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
592 mspace_free(data_mspace, reinterpret_cast<uint8_t*>(info));
593 return true;
594 }
595 return false;
596 });
597 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000598
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000599 live_bitmap_.reset(nullptr);
600 has_done_one_collection_ = true;
601 NotifyCollectionDone(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100602 }
603
604 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
605 LOG(INFO) << "After clearing code cache, code="
606 << PrettySize(CodeCacheSize())
607 << ", data=" << PrettySize(DataCacheSize());
608 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800609}
610
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100611
612OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
613 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
614 if (kRuntimeISA == kArm) {
615 // On Thumb-2, the pc is offset by one.
616 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800617 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100618 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
619 return nullptr;
620 }
621
622 MutexLock mu(Thread::Current(), lock_);
623 if (method_code_map_.empty()) {
624 return nullptr;
625 }
626 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
627 --it;
628
629 const void* code_ptr = it->first;
630 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
631 if (!method_header->Contains(pc)) {
632 return nullptr;
633 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000634 if (kIsDebugBuild && method != nullptr) {
635 DCHECK_EQ(it->second, method)
636 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
637 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100638 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800639}
640
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000641ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
642 ArtMethod* method,
643 const std::vector<uint32_t>& entries,
644 bool retry_allocation) {
645 ProfilingInfo* info = AddProfilingInfoInternal(self, method, entries);
646
647 if (info == nullptr && retry_allocation) {
648 GarbageCollectCache(self);
649 info = AddProfilingInfoInternal(self, method, entries);
650 }
651 return info;
652}
653
654ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self,
655 ArtMethod* method,
656 const std::vector<uint32_t>& entries) {
657 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100658 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000659 sizeof(void*));
660 ScopedThreadSuspension sts(self, kSuspended);
661 MutexLock mu(self, lock_);
662 WaitForPotentialCollectionToComplete(self);
663
664 // Check whether some other thread has concurrently created it.
665 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
666 if (info != nullptr) {
667 return info;
668 }
669
670 uint8_t* data = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, profile_info_size));
671 if (data == nullptr) {
672 return nullptr;
673 }
674 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000675
676 // Make sure other threads see the data in the profiling info object before the
677 // store in the ArtMethod's ProfilingInfo pointer.
678 QuasiAtomic::ThreadFenceRelease();
679
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000680 method->SetProfilingInfo(info);
681 profiling_infos_.push_back(info);
682 return info;
683}
684
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000685// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
686// is already held.
687void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
688 if (code_mspace_ == mspace) {
689 size_t result = code_end_;
690 code_end_ += increment;
691 return reinterpret_cast<void*>(result + code_map_->Begin());
692 } else {
693 DCHECK_EQ(data_mspace_, mspace);
694 size_t result = data_end_;
695 data_end_ += increment;
696 return reinterpret_cast<void*>(result + data_map_->Begin());
697 }
698}
699
Calin Juravle66f55232015-12-08 15:09:10 +0000700void JitCodeCache::GetCompiledArtMethods(const std::set<const std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000701 std::vector<ArtMethod*>& methods) {
Calin Juravle31f2c152015-10-23 17:56:15 +0100702 MutexLock mu(Thread::Current(), lock_);
703 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000704 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000705 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100706 }
707 }
708}
709
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000710uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
711 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100712}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100713
714bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self) {
715 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
716 return false;
717 }
718 MutexLock mu(self, lock_);
719 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
720 if (info == nullptr || info->IsMethodBeingCompiled()) {
721 return false;
722 }
723 info->SetIsMethodBeingCompiled(true);
724 return true;
725}
726
727void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
728 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
729 DCHECK(info->IsMethodBeingCompiled());
730 info->SetIsMethodBeingCompiled(false);
731}
732
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800733} // namespace jit
734} // namespace art