blob: 4f87e5bab5990348435831a52963ecd95457be69 [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
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000296void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
297 MutexLock mu(self, lock_);
298 for (ProfilingInfo* info : profiling_infos_) {
299 if (!info->IsInUseByCompiler()) {
300 info->ClearGcRootsInInlineCaches();
301 }
302 }
303}
304
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100305uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
306 ArtMethod* method,
307 const uint8_t* mapping_table,
308 const uint8_t* vmap_table,
309 const uint8_t* gc_map,
310 size_t frame_size_in_bytes,
311 size_t core_spill_mask,
312 size_t fp_spill_mask,
313 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000314 size_t code_size,
315 bool osr) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100316 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
317 // Ensure the header ends up at expected instruction alignment.
318 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
319 size_t total_size = header_size + code_size;
320
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100321 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100322 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000323 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100324 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000325 ScopedThreadSuspension sts(self, kSuspended);
326 MutexLock mu(self, lock_);
327 WaitForPotentialCollectionToComplete(self);
328 {
329 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000330 memory = AllocateCode(total_size);
331 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000332 return nullptr;
333 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000334 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000335
336 std::copy(code, code + code_size, code_ptr);
337 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
338 new (method_header) OatQuickMethodHeader(
339 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
340 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
341 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
342 frame_size_in_bytes,
343 core_spill_mask,
344 fp_spill_mask,
345 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100346 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100347
Roland Levillain32430262016-02-01 15:23:20 +0000348 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
349 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000350 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100351 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000352 // We need to update the entry point in the runnable state for the instrumentation.
353 {
354 MutexLock mu(self, lock_);
355 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000356 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000357 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000358 osr_code_map_.Put(method, code_ptr);
359 } else {
360 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
361 method, method_header->GetEntryPoint());
362 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000363 if (collection_in_progress_) {
364 // We need to update the live bitmap if there is a GC to ensure it sees this new
365 // code.
366 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
367 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000368 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000369 VLOG(jit)
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000370 << "JIT added (osr = " << std::boolalpha << osr << std::noboolalpha << ") "
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000371 << PrettyMethod(method) << "@" << method
372 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
373 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
374 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
375 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
376 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100377
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100378 return reinterpret_cast<uint8_t*>(method_header);
379}
380
381size_t JitCodeCache::CodeCacheSize() {
382 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000383 return CodeCacheSizeLocked();
384}
385
386size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000387 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100388}
389
390size_t JitCodeCache::DataCacheSize() {
391 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000392 return DataCacheSizeLocked();
393}
394
395size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000396 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800397}
398
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000399void JitCodeCache::ClearData(Thread* self, void* data) {
400 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000401 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000402}
403
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100404uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100405 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100406 uint8_t* result = nullptr;
407
408 {
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 if (result == nullptr) {
416 // Retry.
417 GarbageCollectCache(self);
418 ScopedThreadSuspension sts(self, kSuspended);
419 MutexLock mu(self, lock_);
420 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000421 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100422 }
423
424 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100425}
426
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800427uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100428 uint8_t* result = ReserveData(self, end - begin);
429 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800430 return nullptr; // Out of space in the data cache.
431 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100432 std::copy(begin, end, result);
433 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800434}
435
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100436class MarkCodeVisitor FINAL : public StackVisitor {
437 public:
438 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
439 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
440 code_cache_(code_cache_in),
441 bitmap_(code_cache_->GetLiveBitmap()) {}
442
443 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
444 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
445 if (method_header == nullptr) {
446 return true;
447 }
448 const void* code = method_header->GetCode();
449 if (code_cache_->ContainsPc(code)) {
450 // Use the atomic set version, as multiple threads are executing this code.
451 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
452 }
453 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800454 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100455
456 private:
457 JitCodeCache* const code_cache_;
458 CodeCacheBitmap* const bitmap_;
459};
460
461class MarkCodeClosure FINAL : public Closure {
462 public:
463 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
464 : code_cache_(code_cache), barrier_(barrier) {}
465
466 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800467 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100468 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
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000537void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
538 Barrier barrier(0);
539 size_t threads_running_checkpoint = 0;
540 MarkCodeClosure closure(this, &barrier);
541 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
542 // Now that we have run our checkpoint, move to a suspended state and wait
543 // for other threads to run the checkpoint.
544 ScopedThreadSuspension sts(self, kSuspended);
545 if (threads_running_checkpoint != 0) {
546 barrier.Increment(self, threads_running_checkpoint);
547 }
548}
549
Nicolas Geoffray35122442016-03-02 12:05:30 +0000550bool JitCodeCache::ShouldDoFullCollection() {
551 if (current_capacity_ == max_capacity_) {
552 // Always do a full collection when the code cache is full.
553 return true;
554 } else if (current_capacity_ < kReservedCapacity) {
555 // Always do partial collection when the code cache size is below the reserved
556 // capacity.
557 return false;
558 } else if (last_collection_increased_code_cache_) {
559 // This time do a full collection.
560 return true;
561 } else {
562 // This time do a partial collection.
563 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000564 }
565}
566
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000567void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800568 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000569 if (!garbage_collect_code_) {
570 MutexLock mu(self, lock_);
571 IncreaseCodeCacheCapacity();
572 return;
573 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100574
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000575 // Wait for an existing collection, or let everyone know we are starting one.
576 {
577 ScopedThreadSuspension sts(self, kSuspended);
578 MutexLock mu(self, lock_);
579 if (WaitForPotentialCollectionToComplete(self)) {
580 return;
581 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000582 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000583 live_bitmap_.reset(CodeCacheBitmap::Create(
584 "code-cache-bitmap",
585 reinterpret_cast<uintptr_t>(code_map_->Begin()),
586 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000587 collection_in_progress_ = true;
588 }
589 }
590
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000591 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000592 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000593 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000594
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000595 bool do_full_collection = false;
596 {
597 MutexLock mu(self, lock_);
598 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000599 }
600
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000601 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
602 LOG(INFO) << "Do "
603 << (do_full_collection ? "full" : "partial")
604 << " code cache collection, code="
605 << PrettySize(CodeCacheSize())
606 << ", data=" << PrettySize(DataCacheSize());
607 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000608
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000609 DoCollection(self, /* collect_profiling_info */ do_full_collection);
610
611 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
612 LOG(INFO) << "After code cache collection, code="
613 << PrettySize(CodeCacheSize())
614 << ", data=" << PrettySize(DataCacheSize());
615 }
616
617 {
618 MutexLock mu(self, lock_);
619
620 // Increase the code cache only when we do partial collections.
621 // TODO: base this strategy on how full the code cache is?
622 if (do_full_collection) {
623 last_collection_increased_code_cache_ = false;
624 } else {
625 last_collection_increased_code_cache_ = true;
626 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000627 }
628
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000629 bool next_collection_will_be_full = ShouldDoFullCollection();
630
631 // Start polling the liveness of compiled code to prepare for the next full collection.
632 // We avoid doing this if exit stubs are installed to not mess with the instrumentation.
633 // TODO(ngeoffray): Clean up instrumentation and code cache interactions.
634 if (!Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled() &&
635 next_collection_will_be_full) {
636 // Save the entry point of methods we have compiled, and update the entry
637 // point of those methods to the interpreter. If the method is invoked, the
638 // interpreter will update its entry point to the compiled code and call it.
639 for (ProfilingInfo* info : profiling_infos_) {
640 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
641 if (ContainsPc(entry_point)) {
642 info->SetSavedEntryPoint(entry_point);
643 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
644 }
645 }
646
647 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
648 }
649 live_bitmap_.reset(nullptr);
650 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000651 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000652 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000653 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000654}
655
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000656void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800657 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000658 MutexLock mu(self, lock_);
659 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000660 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000661 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
662 const void* code_ptr = it->first;
663 ArtMethod* method = it->second;
664 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000665 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000666 ++it;
667 } else {
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000668 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
669 if (method_header->GetEntryPoint() == GetQuickToInterpreterBridge()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000670 method->ClearCounter();
671 }
672 FreeCode(code_ptr, method);
673 it = method_code_map_.erase(it);
674 }
675 }
676}
677
678void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800679 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000680 {
681 MutexLock mu(self, lock_);
682 if (collect_profiling_info) {
683 // Clear the profiling info of methods that do not have compiled code as entrypoint.
684 // Also remove the saved entry point from the ProfilingInfo objects.
685 for (ProfilingInfo* info : profiling_infos_) {
686 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000687 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000688 info->GetMethod()->SetProfilingInfo(nullptr);
689 }
690 info->SetSavedEntryPoint(nullptr);
691 }
692 } else if (kIsDebugBuild) {
693 // Sanity check that the profiling infos do not have a dangling entry point.
694 for (ProfilingInfo* info : profiling_infos_) {
695 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100696 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000697 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000698
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000699 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
700 // an entry point is either:
701 // - an osr compiled code, that will be removed if not in a thread call stack.
702 // - discarded compiled code, that will be removed if not in a thread call stack.
703 for (const auto& it : method_code_map_) {
704 ArtMethod* method = it.second;
705 const void* code_ptr = it.first;
706 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
707 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
708 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
709 }
710 }
711
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000712 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000713 // on thread stacks).
714 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100715 }
716
717 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000718 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100719
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000720 // At this point, mutator threads are still running, and entrypoints of methods can
721 // change. We do know they cannot change to a code cache entry that is not marked,
722 // therefore we can safely remove those entries.
723 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000724
Nicolas Geoffray35122442016-03-02 12:05:30 +0000725 if (collect_profiling_info) {
726 MutexLock mu(self, lock_);
727 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100728 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000729 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000730 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000731 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
732 // that the compiled code would not get revived. As mutator threads run concurrently,
733 // they may have revived the compiled code, and now we are in the situation where
734 // a method has compiled code but no ProfilingInfo.
735 // We make sure compiled methods have a ProfilingInfo object. It is needed for
736 // code cache collection.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000737 if (ContainsPc(ptr) && info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000738 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000739 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000740 // Do a fence to make sure the clearing is seen before attaching to the method.
741 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000742 info->GetMethod()->SetProfilingInfo(info);
743 } else if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) != info) {
744 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000745 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100746 return true;
747 }
748 return false;
749 });
750 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000751 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100752 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800753}
754
Nicolas Geoffray35122442016-03-02 12:05:30 +0000755bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800756 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000757 // Check that methods we have compiled do have a ProfilingInfo object. We would
758 // have memory leaks of compiled code otherwise.
759 for (const auto& it : method_code_map_) {
760 ArtMethod* method = it.second;
761 if (method->GetProfilingInfo(sizeof(void*)) == nullptr) {
762 const void* code_ptr = it.first;
763 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
764 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
765 // If the code is not dead, then we have a problem. Note that this can even
766 // happen just after a collection, as mutator threads are running in parallel
767 // and could deoptimize an existing compiled code.
768 return false;
769 }
770 }
771 }
772 return true;
773}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100774
775OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
776 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
777 if (kRuntimeISA == kArm) {
778 // On Thumb-2, the pc is offset by one.
779 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800780 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100781 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
782 return nullptr;
783 }
784
785 MutexLock mu(Thread::Current(), lock_);
786 if (method_code_map_.empty()) {
787 return nullptr;
788 }
789 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
790 --it;
791
792 const void* code_ptr = it->first;
793 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
794 if (!method_header->Contains(pc)) {
795 return nullptr;
796 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000797 if (kIsDebugBuild && method != nullptr) {
798 DCHECK_EQ(it->second, method)
799 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
800 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100801 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800802}
803
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000804OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
805 MutexLock mu(Thread::Current(), lock_);
806 auto it = osr_code_map_.find(method);
807 if (it == osr_code_map_.end()) {
808 return nullptr;
809 }
810 return OatQuickMethodHeader::FromCodePointer(it->second);
811}
812
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000813ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
814 ArtMethod* method,
815 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000816 bool retry_allocation)
817 // No thread safety analysis as we are using TryLock/Unlock explicitly.
818 NO_THREAD_SAFETY_ANALYSIS {
819 ProfilingInfo* info = nullptr;
820 if (!retry_allocation) {
821 // If we are allocating for the interpreter, just try to lock, to avoid
822 // lock contention with the JIT.
823 if (lock_.ExclusiveTryLock(self)) {
824 info = AddProfilingInfoInternal(self, method, entries);
825 lock_.ExclusiveUnlock(self);
826 }
827 } else {
828 {
829 MutexLock mu(self, lock_);
830 info = AddProfilingInfoInternal(self, method, entries);
831 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000832
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000833 if (info == nullptr) {
834 GarbageCollectCache(self);
835 MutexLock mu(self, lock_);
836 info = AddProfilingInfoInternal(self, method, entries);
837 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000838 }
839 return info;
840}
841
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000842ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000843 ArtMethod* method,
844 const std::vector<uint32_t>& entries) {
845 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100846 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000847 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000848
849 // Check whether some other thread has concurrently created it.
850 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
851 if (info != nullptr) {
852 return info;
853 }
854
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000855 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000856 if (data == nullptr) {
857 return nullptr;
858 }
859 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000860
861 // Make sure other threads see the data in the profiling info object before the
862 // store in the ArtMethod's ProfilingInfo pointer.
863 QuasiAtomic::ThreadFenceRelease();
864
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000865 method->SetProfilingInfo(info);
866 profiling_infos_.push_back(info);
867 return info;
868}
869
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000870// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
871// is already held.
872void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
873 if (code_mspace_ == mspace) {
874 size_t result = code_end_;
875 code_end_ += increment;
876 return reinterpret_cast<void*>(result + code_map_->Begin());
877 } else {
878 DCHECK_EQ(data_mspace_, mspace);
879 size_t result = data_end_;
880 data_end_ += increment;
881 return reinterpret_cast<void*>(result + data_map_->Begin());
882 }
883}
884
Calin Juravleb4eddd22016-01-13 15:52:33 -0800885void JitCodeCache::GetCompiledArtMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000886 std::vector<ArtMethod*>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800887 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100888 MutexLock mu(Thread::Current(), lock_);
889 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000890 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000891 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100892 }
893 }
894}
895
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000896uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
897 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100898}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100899
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000900bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
901 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000902 VLOG(jit) << PrettyMethod(method) << " is already compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100903 return false;
904 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000905
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000906 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000907 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000908 VLOG(jit) << PrettyMethod(method) << " is already osr compiled";
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000909 return false;
910 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000911
Nicolas Geoffrayc26f1282016-01-29 11:41:25 +0000912 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000913 if (info == nullptr) {
914 VLOG(jit) << PrettyMethod(method) << " needs a ProfilingInfo to be compiled";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100915 return false;
916 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000917
918 if (info->IsMethodBeingCompiled()) {
919 VLOG(jit) << PrettyMethod(method) << " is already being compiled";
920 return false;
921 }
922
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100923 info->SetIsMethodBeingCompiled(true);
924 return true;
925}
926
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000927void JitCodeCache::NotifyInliningOf(ArtMethod* method, Thread* self) {
928 MutexLock mu(self, lock_);
929 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
930 if (info != nullptr) {
931 info->IncrementInlineUse();
932 }
933}
934
935void JitCodeCache::DoneInlining(ArtMethod* method, Thread* self) {
936 MutexLock mu(self, lock_);
937 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
938 if (info != nullptr) {
939 info->DecrementInlineUse();
940 }
941}
942
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100943void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
944 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
945 DCHECK(info->IsMethodBeingCompiled());
946 info->SetIsMethodBeingCompiled(false);
947}
948
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000949size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
950 MutexLock mu(Thread::Current(), lock_);
951 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
952}
953
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000954void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
955 const OatQuickMethodHeader* header) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000956 ProfilingInfo* profiling_info = method->GetProfilingInfo(sizeof(void*));
957 if ((profiling_info != nullptr) &&
958 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
959 // Prevent future uses of the compiled code.
960 profiling_info->SetSavedEntryPoint(nullptr);
961 }
962
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000963 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
964 // The entrypoint is the one to invalidate, so we just update
965 // it to the interpreter entry point and clear the counter to get the method
966 // Jitted again.
967 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
968 method, GetQuickToInterpreterBridge());
969 method->ClearCounter();
970 } else {
971 MutexLock mu(Thread::Current(), lock_);
972 auto it = osr_code_map_.find(method);
973 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
974 // Remove the OSR method, to avoid using it again.
975 osr_code_map_.erase(it);
976 }
977 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000978 MutexLock mu(Thread::Current(), lock_);
979 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +0000980}
981
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000982uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
983 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
984 uint8_t* result = reinterpret_cast<uint8_t*>(
985 mspace_memalign(code_mspace_, alignment, code_size));
986 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
987 // Ensure the header ends up at expected instruction alignment.
988 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
989 used_memory_for_code_ += mspace_usable_size(result);
990 return result;
991}
992
993void JitCodeCache::FreeCode(uint8_t* code) {
994 used_memory_for_code_ -= mspace_usable_size(code);
995 mspace_free(code_mspace_, code);
996}
997
998uint8_t* JitCodeCache::AllocateData(size_t data_size) {
999 void* result = mspace_malloc(data_mspace_, data_size);
1000 used_memory_for_data_ += mspace_usable_size(result);
1001 return reinterpret_cast<uint8_t*>(result);
1002}
1003
1004void JitCodeCache::FreeData(uint8_t* data) {
1005 used_memory_for_data_ -= mspace_usable_size(data);
1006 mspace_free(data_mspace_, data);
1007}
1008
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001009void JitCodeCache::Dump(std::ostream& os) {
1010 MutexLock mu(Thread::Current(), lock_);
1011 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1012 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1013 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1014 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1015 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1016 << "Total number of JIT compilations for on stack replacement: "
1017 << number_of_osr_compilations_ << "\n"
1018 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1019 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
1020}
1021
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001022} // namespace jit
1023} // namespace art