blob: 1545cb7f01a27f40efb733037f14ea9bcc639b5d [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"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080023#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010024#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000025#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010026#include "entrypoints/runtime_asm_entrypoints.h"
27#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000028#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000029#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010030#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080031#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000033#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010034#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035
36namespace art {
37namespace jit {
38
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010039static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
40static constexpr int kProtData = PROT_READ | PROT_WRITE;
41static constexpr int kProtCode = PROT_READ | PROT_EXEC;
42
43#define CHECKED_MPROTECT(memory, size, prot) \
44 do { \
45 int rc = mprotect(memory, size, prot); \
46 if (UNLIKELY(rc != 0)) { \
47 errno = rc; \
48 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
49 } \
50 } while (false) \
51
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000052JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
53 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000054 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000055 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080056 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000058
59 // Generating debug information is mostly for using the 'perf' tool, which does
60 // not work with ashmem.
61 bool use_ashmem = !generate_debug_info;
62 // With 'perf', we want a 1-1 mapping between an address and a method.
63 bool garbage_collect_code = !generate_debug_info;
64
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000065 // We need to have 32 bit offsets from method headers in code cache which point to things
66 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
67 // Ensure we're below 1 GB to be safe.
68 if (max_capacity > 1 * GB) {
69 std::ostringstream oss;
70 oss << "Maxium code cache capacity is limited to 1 GB, "
71 << PrettySize(max_capacity) << " is too big";
72 *error_msg = oss.str();
73 return nullptr;
74 }
75
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080076 std::string error_str;
77 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010078 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000079 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010080 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000082 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080083 *error_msg = oss.str();
84 return nullptr;
85 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010086
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000087 // Align both capacities to page size, as that's the unit mspaces use.
88 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
89 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
90
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000091 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010092 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000093 size_t data_size = max_capacity / 2;
94 size_t code_size = max_capacity - data_size;
95 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010096 uint8_t* divider = data_map->Begin() + data_size;
97
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000098 MemMap* code_map =
99 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100100 if (code_map == nullptr) {
101 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000102 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 *error_msg = oss.str();
104 return nullptr;
105 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100106 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000107 data_size = initial_capacity / 2;
108 code_size = initial_capacity - data_size;
109 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000110 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000111 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800112}
113
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000114JitCodeCache::JitCodeCache(MemMap* code_map,
115 MemMap* data_map,
116 size_t initial_code_capacity,
117 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000118 size_t max_capacity,
119 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100121 lock_cond_("Jit code cache variable", lock_),
122 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100123 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000124 data_map_(data_map),
125 max_capacity_(max_capacity),
126 current_capacity_(initial_code_capacity + initial_data_capacity),
127 code_end_(initial_code_capacity),
128 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000129 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000130 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000131 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000132 used_memory_for_data_(0),
133 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000134 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000135 number_of_osr_compilations_(0),
136 number_of_deoptimizations_(0),
137 number_of_collections_(0) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000139 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000140 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
141 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100142
143 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
144 PLOG(FATAL) << "create_mspace_with_base failed";
145 }
146
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000147 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148
149 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
150 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100151
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000152 VLOG(jit) << "Created jit code cache: initial data size="
153 << PrettySize(initial_data_capacity)
154 << ", initial code size="
155 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800156}
157
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100158bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100159 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800160}
161
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000162bool JitCodeCache::ContainsMethod(ArtMethod* method) {
163 MutexLock mu(Thread::Current(), lock_);
164 for (auto& it : method_code_map_) {
165 if (it.second == method) {
166 return true;
167 }
168 }
169 return false;
170}
171
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100172class ScopedCodeCacheWrite {
173 public:
174 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
175 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800176 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100177 ~ScopedCodeCacheWrite() {
178 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
179 }
180 private:
181 MemMap* const code_map_;
182
183 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
184};
185
186uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100187 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100188 const uint8_t* mapping_table,
189 const uint8_t* vmap_table,
190 const uint8_t* gc_map,
191 size_t frame_size_in_bytes,
192 size_t core_spill_mask,
193 size_t fp_spill_mask,
194 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000195 size_t code_size,
196 bool osr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100197 uint8_t* result = CommitCodeInternal(self,
198 method,
199 mapping_table,
200 vmap_table,
201 gc_map,
202 frame_size_in_bytes,
203 core_spill_mask,
204 fp_spill_mask,
205 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000206 code_size,
207 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100208 if (result == nullptr) {
209 // Retry.
210 GarbageCollectCache(self);
211 result = CommitCodeInternal(self,
212 method,
213 mapping_table,
214 vmap_table,
215 gc_map,
216 frame_size_in_bytes,
217 core_spill_mask,
218 fp_spill_mask,
219 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000220 code_size,
221 osr);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100222 }
223 return result;
224}
225
226bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
227 bool in_collection = false;
228 while (collection_in_progress_) {
229 in_collection = true;
230 lock_cond_.Wait(self);
231 }
232 return in_collection;
233}
234
235static uintptr_t FromCodeToAllocation(const void* code) {
236 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
237 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
238}
239
240void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
241 uintptr_t allocation = FromCodeToAllocation(code_ptr);
242 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000243 // Notify native debugger that we are about to remove the code.
244 // It does nothing if we are not using native debugger.
245 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000246
247 FreeData(const_cast<uint8_t*>(method_header->GetNativeGcMap()));
248 FreeData(const_cast<uint8_t*>(method_header->GetMappingTable()));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100249 // Use the offset directly to prevent sanity check that the method is
250 // compiled with optimizing.
251 // TODO(ngeoffray): Clean up.
252 if (method_header->vmap_table_offset_ != 0) {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000253 const uint8_t* data = method_header->code_ - method_header->vmap_table_offset_;
254 FreeData(const_cast<uint8_t*>(data));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100255 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000256 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100257}
258
259void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800260 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100261 MutexLock mu(self, lock_);
262 // We do not check if a code cache GC is in progress, as this method comes
263 // with the classlinker_classes_lock_ held, and suspending ourselves could
264 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000265 {
266 ScopedCodeCacheWrite scc(code_map_.get());
267 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
268 if (alloc.ContainsUnsafe(it->second)) {
269 FreeCode(it->first, it->second);
270 it = method_code_map_.erase(it);
271 } else {
272 ++it;
273 }
274 }
275 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000276 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
277 if (alloc.ContainsUnsafe(it->first)) {
278 // Note that the code has already been removed in the loop above.
279 it = osr_code_map_.erase(it);
280 } else {
281 ++it;
282 }
283 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000284 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
285 ProfilingInfo* info = *it;
286 if (alloc.ContainsUnsafe(info->GetMethod())) {
287 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000288 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000289 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100290 } else {
291 ++it;
292 }
293 }
294}
295
296uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
297 ArtMethod* method,
298 const uint8_t* mapping_table,
299 const uint8_t* vmap_table,
300 const uint8_t* gc_map,
301 size_t frame_size_in_bytes,
302 size_t core_spill_mask,
303 size_t fp_spill_mask,
304 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000305 size_t code_size,
306 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100307 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
308 // Ensure the header ends up at expected instruction alignment.
309 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
310 size_t total_size = header_size + code_size;
311
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100312 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100313 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000314 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100315 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000316 ScopedThreadSuspension sts(self, kSuspended);
317 MutexLock mu(self, lock_);
318 WaitForPotentialCollectionToComplete(self);
319 {
320 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000321 memory = AllocateCode(total_size);
322 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000323 return nullptr;
324 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000325 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000326
327 std::copy(code, code + code_size, code_ptr);
328 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
329 new (method_header) OatQuickMethodHeader(
330 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
331 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
332 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
333 frame_size_in_bytes,
334 core_spill_mask,
335 fp_spill_mask,
336 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100337 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100338
Roland Levillain32430262016-02-01 15:23:20 +0000339 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
340 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000341 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100342 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000343 // We need to update the entry point in the runnable state for the instrumentation.
344 {
345 MutexLock mu(self, lock_);
346 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000347 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000348 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000349 osr_code_map_.Put(method, code_ptr);
350 } else {
351 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
352 method, method_header->GetEntryPoint());
353 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000354 if (collection_in_progress_) {
355 // We need to update the live bitmap if there is a GC to ensure it sees this new
356 // code.
357 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
358 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000359 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000360 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000361 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000362 << PrettyMethod(method) << "@" << method
363 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
364 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
365 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
366 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
367 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100368
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100369 return reinterpret_cast<uint8_t*>(method_header);
370}
371
372size_t JitCodeCache::CodeCacheSize() {
373 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000374 return CodeCacheSizeLocked();
375}
376
377size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000378 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100379}
380
381size_t JitCodeCache::DataCacheSize() {
382 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000383 return DataCacheSizeLocked();
384}
385
386size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000387 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800388}
389
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000390void JitCodeCache::ClearData(Thread* self, void* data) {
391 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000392 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000393}
394
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100395uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100396 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100397 uint8_t* result = nullptr;
398
399 {
400 ScopedThreadSuspension sts(self, kSuspended);
401 MutexLock mu(self, lock_);
402 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000403 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100404 }
405
406 if (result == nullptr) {
407 // Retry.
408 GarbageCollectCache(self);
409 ScopedThreadSuspension sts(self, kSuspended);
410 MutexLock mu(self, lock_);
411 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000412 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100413 }
414
415 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100416}
417
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800418uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100419 uint8_t* result = ReserveData(self, end - begin);
420 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800421 return nullptr; // Out of space in the data cache.
422 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100423 std::copy(begin, end, result);
424 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800425}
426
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100427class MarkCodeVisitor FINAL : public StackVisitor {
428 public:
429 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
430 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
431 code_cache_(code_cache_in),
432 bitmap_(code_cache_->GetLiveBitmap()) {}
433
434 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
435 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
436 if (method_header == nullptr) {
437 return true;
438 }
439 const void* code = method_header->GetCode();
440 if (code_cache_->ContainsPc(code)) {
441 // Use the atomic set version, as multiple threads are executing this code.
442 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
443 }
444 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800445 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100446
447 private:
448 JitCodeCache* const code_cache_;
449 CodeCacheBitmap* const bitmap_;
450};
451
452class MarkCodeClosure FINAL : public Closure {
453 public:
454 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
455 : code_cache_(code_cache), barrier_(barrier) {}
456
457 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800458 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100459 DCHECK(thread == Thread::Current() || thread->IsSuspended());
460 MarkCodeVisitor visitor(thread, code_cache_);
461 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000462 if (kIsDebugBuild) {
463 // The stack walking code queries the side instrumentation stack if it
464 // sees an instrumentation exit pc, so the JIT code of methods in that stack
465 // must have been seen. We sanity check this below.
466 for (const instrumentation::InstrumentationStackFrame& frame
467 : *thread->GetInstrumentationStack()) {
468 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
469 // its stack frame, it is not the method owning return_pc_. We just pass null to
470 // LookupMethodHeader: the method is only checked against in debug builds.
471 OatQuickMethodHeader* method_header =
472 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
473 if (method_header != nullptr) {
474 const void* code = method_header->GetCode();
475 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
476 }
477 }
478 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700479 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800480 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100481
482 private:
483 JitCodeCache* const code_cache_;
484 Barrier* const barrier_;
485};
486
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000487void JitCodeCache::NotifyCollectionDone(Thread* self) {
488 collection_in_progress_ = false;
489 lock_cond_.Broadcast(self);
490}
491
492void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
493 size_t per_space_footprint = new_footprint / 2;
494 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
495 DCHECK_EQ(per_space_footprint * 2, new_footprint);
496 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
497 {
498 ScopedCodeCacheWrite scc(code_map_.get());
499 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
500 }
501}
502
503bool JitCodeCache::IncreaseCodeCacheCapacity() {
504 if (current_capacity_ == max_capacity_) {
505 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100506 }
507
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000508 // Double the capacity if we're below 1MB, or increase it by 1MB if
509 // we're above.
510 if (current_capacity_ < 1 * MB) {
511 current_capacity_ *= 2;
512 } else {
513 current_capacity_ += 1 * MB;
514 }
515 if (current_capacity_ > max_capacity_) {
516 current_capacity_ = max_capacity_;
517 }
518
519 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
520 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
521 }
522
523 SetFootprintLimit(current_capacity_);
524
525 return true;
526}
527
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000528void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
529 Barrier barrier(0);
530 size_t threads_running_checkpoint = 0;
531 MarkCodeClosure closure(this, &barrier);
532 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
533 // Now that we have run our checkpoint, move to a suspended state and wait
534 // for other threads to run the checkpoint.
535 ScopedThreadSuspension sts(self, kSuspended);
536 if (threads_running_checkpoint != 0) {
537 barrier.Increment(self, threads_running_checkpoint);
538 }
539}
540
Nicolas Geoffray35122442016-03-02 12:05:30 +0000541bool JitCodeCache::ShouldDoFullCollection() {
542 if (current_capacity_ == max_capacity_) {
543 // Always do a full collection when the code cache is full.
544 return true;
545 } else if (current_capacity_ < kReservedCapacity) {
546 // Always do partial collection when the code cache size is below the reserved
547 // capacity.
548 return false;
549 } else if (last_collection_increased_code_cache_) {
550 // This time do a full collection.
551 return true;
552 } else {
553 // This time do a partial collection.
554 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000555 }
556}
557
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000558void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800559 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000560 if (!garbage_collect_code_) {
561 MutexLock mu(self, lock_);
562 IncreaseCodeCacheCapacity();
563 return;
564 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100565
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000566 // Wait for an existing collection, or let everyone know we are starting one.
567 {
568 ScopedThreadSuspension sts(self, kSuspended);
569 MutexLock mu(self, lock_);
570 if (WaitForPotentialCollectionToComplete(self)) {
571 return;
572 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000573 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000574 live_bitmap_.reset(CodeCacheBitmap::Create(
575 "code-cache-bitmap",
576 reinterpret_cast<uintptr_t>(code_map_->Begin()),
577 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000578 collection_in_progress_ = true;
579 }
580 }
581
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000582 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000583 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000584 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000585
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000586 bool do_full_collection = false;
587 {
588 MutexLock mu(self, lock_);
589 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000590 }
591
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000592 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
593 LOG(INFO) << "Do "
594 << (do_full_collection ? "full" : "partial")
595 << " code cache collection, code="
596 << PrettySize(CodeCacheSize())
597 << ", data=" << PrettySize(DataCacheSize());
598 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000599
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000600 DoCollection(self, /* collect_profiling_info */ do_full_collection);
601
602 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
603 LOG(INFO) << "After code cache collection, code="
604 << PrettySize(CodeCacheSize())
605 << ", data=" << PrettySize(DataCacheSize());
606 }
607
608 {
609 MutexLock mu(self, lock_);
610
611 // Increase the code cache only when we do partial collections.
612 // TODO: base this strategy on how full the code cache is?
613 if (do_full_collection) {
614 last_collection_increased_code_cache_ = false;
615 } else {
616 last_collection_increased_code_cache_ = true;
617 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000618 }
619
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000620 bool next_collection_will_be_full = ShouldDoFullCollection();
621
622 // Start polling the liveness of compiled code to prepare for the next full collection.
623 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
624 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
625 if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled() &&
626 next_collection_will_be_full) {
627 // Save the entry point of methods we have compiled, and update the entry
628 // point of those methods to the interpreter. If the method is invoked, the
629 // interpreter will update its entry point to the compiled code and call it.
630 for (ProfilingInfo* info : profiling_infos_) {
631 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
632 if (ContainsPc(entry_point)) {
633 info->SetSavedEntryPoint(entry_point);
634 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
635 }
636 }
637
638 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
639 }
640 live_bitmap_.reset(nullptr);
641 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000642 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000643 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000644 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000645}
646
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000647void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800648 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000649 MutexLock mu(self, lock_);
650 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000651 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000652 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
653 const void* code_ptr = it->first;
654 ArtMethod* method = it->second;
655 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000656 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000657 ++it;
658 } else {
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000659 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
660 if (method_header->GetEntryPoint() == GetQuickToInterpreterBridge()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000661 method->ClearCounter();
662 }
663 FreeCode(code_ptr, method);
664 it = method_code_map_.erase(it);
665 }
666 }
667}
668
669void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800670 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000671 {
672 MutexLock mu(self, lock_);
673 if (collect_profiling_info) {
674 // Clear the profiling info of methods that do not have compiled code as entrypoint.
675 // Also remove the saved entry point from the ProfilingInfo objects.
676 for (ProfilingInfo* info : profiling_infos_) {
677 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
678 if (!ContainsPc(ptr) && !info->IsMethodBeingCompiled()) {
679 info->GetMethod()->SetProfilingInfo(nullptr);
680 }
681 info->SetSavedEntryPoint(nullptr);
682 }
683 } else if (kIsDebugBuild) {
684 // Sanity check that the profiling infos do not have a dangling entry point.
685 for (ProfilingInfo* info : profiling_infos_) {
686 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100687 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000688 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000689
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000690 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
691 // an entry point is either:
692 // - an osr compiled code, that will be removed if not in a thread call stack.
693 // - discarded compiled code, that will be removed if not in a thread call stack.
694 for (const auto& it : method_code_map_) {
695 ArtMethod* method = it.second;
696 const void* code_ptr = it.first;
697 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
698 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
699 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
700 }
701 }
702
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000703 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000704 // on thread stacks).
705 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100706 }
707
708 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000709 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100710
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000711 // At this point, mutator threads are still running, and entrypoints of methods can
712 // change. We do know they cannot change to a code cache entry that is not marked,
713 // therefore we can safely remove those entries.
714 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000715
Nicolas Geoffray35122442016-03-02 12:05:30 +0000716 if (collect_profiling_info) {
717 MutexLock mu(self, lock_);
718 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100719 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000720 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000721 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000722 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
723 // that the compiled code would not get revived. As mutator threads run concurrently,
724 // they may have revived the compiled code, and now we are in the situation where
725 // a method has compiled code but no ProfilingInfo.
726 // We make sure compiled methods have a ProfilingInfo object. It is needed for
727 // code cache collection.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000728 if (ContainsPc(ptr) && info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000729 // We clear the inline caches as classes in it might be stalled.
730 info->ClearInlineCaches();
731 // Do a fence to make sure the clearing is seen before attaching to the method.
732 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000733 info->GetMethod()->SetProfilingInfo(info);
734 } else if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) != info) {
735 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000736 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100737 return true;
738 }
739 return false;
740 });
741 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000742 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100743 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800744}
745
Nicolas Geoffray35122442016-03-02 12:05:30 +0000746bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800747 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000748 // Check that methods we have compiled do have a ProfilingInfo object. We would
749 // have memory leaks of compiled code otherwise.
750 for (const auto& it : method_code_map_) {
751 ArtMethod* method = it.second;
752 if (method->GetProfilingInfo(sizeof(void*)) == nullptr) {
753 const void* code_ptr = it.first;
754 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
755 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
756 // If the code is not dead, then we have a problem. Note that this can even
757 // happen just after a collection, as mutator threads are running in parallel
758 // and could deoptimize an existing compiled code.
759 return false;
760 }
761 }
762 }
763 return true;
764}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100765
766OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
767 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
768 if (kRuntimeISA == kArm) {
769 // On Thumb-2, the pc is offset by one.
770 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800771 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100772 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
773 return nullptr;
774 }
775
776 MutexLock mu(Thread::Current(), lock_);
777 if (method_code_map_.empty()) {
778 return nullptr;
779 }
780 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
781 --it;
782
783 const void* code_ptr = it->first;
784 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
785 if (!method_header->Contains(pc)) {
786 return nullptr;
787 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000788 if (kIsDebugBuild && method != nullptr) {
789 DCHECK_EQ(it->second, method)
790 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
791 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100792 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800793}
794
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000795OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
796 MutexLock mu(Thread::Current(), lock_);
797 auto it = osr_code_map_.find(method);
798 if (it == osr_code_map_.end()) {
799 return nullptr;
800 }
801 return OatQuickMethodHeader::FromCodePointer(it->second);
802}
803
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000804ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
805 ArtMethod* method,
806 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000807 bool retry_allocation)
808 // No thread safety analysis as we are using TryLock/Unlock explicitly.
809 NO_THREAD_SAFETY_ANALYSIS {
810 ProfilingInfo* info = nullptr;
811 if (!retry_allocation) {
812 // If we are allocating for the interpreter, just try to lock, to avoid
813 // lock contention with the JIT.
814 if (lock_.ExclusiveTryLock(self)) {
815 info = AddProfilingInfoInternal(self, method, entries);
816 lock_.ExclusiveUnlock(self);
817 }
818 } else {
819 {
820 MutexLock mu(self, lock_);
821 info = AddProfilingInfoInternal(self, method, entries);
822 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000823
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000824 if (info == nullptr) {
825 GarbageCollectCache(self);
826 MutexLock mu(self, lock_);
827 info = AddProfilingInfoInternal(self, method, entries);
828 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000829 }
830 return info;
831}
832
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000833ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000834 ArtMethod* method,
835 const std::vector<uint32_t>& entries) {
836 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100837 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000838 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000839
840 // Check whether some other thread has concurrently created it.
841 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
842 if (info != nullptr) {
843 return info;
844 }
845
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000846 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000847 if (data == nullptr) {
848 return nullptr;
849 }
850 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000851
852 // Make sure other threads see the data in the profiling info object before the
853 // store in the ArtMethod's ProfilingInfo pointer.
854 QuasiAtomic::ThreadFenceRelease();
855
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000856 method->SetProfilingInfo(info);
857 profiling_infos_.push_back(info);
858 return info;
859}
860
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000861// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
862// is already held.
863void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
864 if (code_mspace_ == mspace) {
865 size_t result = code_end_;
866 code_end_ += increment;
867 return reinterpret_cast<void*>(result + code_map_->Begin());
868 } else {
869 DCHECK_EQ(data_mspace_, mspace);
870 size_t result = data_end_;
871 data_end_ += increment;
872 return reinterpret_cast<void*>(result + data_map_->Begin());
873 }
874}
875
Calin Juravleb4eddd22016-01-13 15:52:33 -0800876void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000877 std::vector<ArtMethod*>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800878 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100879 MutexLock mu(Thread::Current(), lock_);
880 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000881 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000882 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100883 }
884 }
885}
886
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000887uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
888 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100889}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100890
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000891bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
892 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000893 VLOG(jit) << PrettyMethod(method) << " is already compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100894 return false;
895 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000896
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000897 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000898 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000899 VLOG(jit) << PrettyMethod(method) << " is already osr compiled";
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000900 return false;
901 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000902
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000903 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000904 if (info == nullptr) {
905 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100906 return false;
907 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000908
909 if (info->IsMethodBeingCompiled()) {
910 VLOG(jit) << PrettyMethod(method) << " is already being compiled";
911 return false;
912 }
913
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100914 info->SetIsMethodBeingCompiled(true);
915 return true;
916}
917
918void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
919 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
920 DCHECK(info->IsMethodBeingCompiled());
921 info->SetIsMethodBeingCompiled(false);
922}
923
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000924size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
925 MutexLock mu(Thread::Current(), lock_);
926 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
927}
928
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000929void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
930 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000931 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
932 if ((profiling_info != nullptr) &&
933 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
934 // Prevent future uses of the compiled code.
935 profiling_info->SetSavedEntryPoint(nullptr);
936 }
937
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000938 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
939 // The entrypoint is the one to invalidate, so we just update
940 // it to the interpreter entry point and clear the counter to get the method
941 // Jitted again.
942 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
943 method, GetQuickToInterpreterBridge());
944 method->ClearCounter();
945 } else {
946 MutexLock mu(Thread::Current(), lock_);
947 auto it = osr_code_map_.find(method);
948 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
949 // Remove the OSR method, to avoid using it again.
950 osr_code_map_.erase(it);
951 }
952 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000953 MutexLock mu(Thread::Current(), lock_);
954 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000955}
956
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000957uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
958 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
959 uint8_t* result = reinterpret_cast<uint8_t*>(
960 mspace_memalign(code_mspace_, alignment, code_size));
961 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
962 // Ensure the header ends up at expected instruction alignment.
963 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
964 used_memory_for_code_ += mspace_usable_size(result);
965 return result;
966}
967
968void JitCodeCache::FreeCode(uint8_t* code) {
969 used_memory_for_code_ -= mspace_usable_size(code);
970 mspace_free(code_mspace_, code);
971}
972
973uint8_t* JitCodeCache::AllocateData(size_t data_size) {
974 void* result = mspace_malloc(data_mspace_, data_size);
975 used_memory_for_data_ += mspace_usable_size(result);
976 return reinterpret_cast<uint8_t*>(result);
977}
978
979void JitCodeCache::FreeData(uint8_t* data) {
980 used_memory_for_data_ -= mspace_usable_size(data);
981 mspace_free(data_mspace_, data);
982}
983
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000984void JitCodeCache::Dump(std::ostream& os) {
985 MutexLock mu(Thread::Current(), lock_);
986 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
987 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
988 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
989 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
990 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
991 << "Total number of JIT compilations for on stack replacement: "
992 << number_of_osr_compilations_ << "\n"
993 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
994 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
995}
996
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800997} // namespace jit
998} // namespace art