blob: 2fbf5ef683fb821aefe0643690e7fc16864bef71 [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070022#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000023#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080024#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010025#include "base/time_utils.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000026#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010027#include "entrypoints/runtime_asm_entrypoints.h"
28#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010029#include "gc/scoped_gc_critical_section.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000030#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000031#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080033#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080034#include "oat_file-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010036#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037
38namespace art {
39namespace jit {
40
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010041static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
42static constexpr int kProtData = PROT_READ | PROT_WRITE;
43static constexpr int kProtCode = PROT_READ | PROT_EXEC;
44
Nicolas Geoffray933330a2016-03-16 14:20:06 +000045static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
46static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
47
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010048#define CHECKED_MPROTECT(memory, size, prot) \
49 do { \
50 int rc = mprotect(memory, size, prot); \
51 if (UNLIKELY(rc != 0)) { \
52 errno = rc; \
53 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
54 } \
55 } while (false) \
56
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000057JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
58 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000059 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000060 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080061 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000063
64 // Generating debug information is mostly for using the 'perf' tool, which does
65 // not work with ashmem.
66 bool use_ashmem = !generate_debug_info;
67 // With 'perf', we want a 1-1 mapping between an address and a method.
68 bool garbage_collect_code = !generate_debug_info;
69
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000070 // We need to have 32 bit offsets from method headers in code cache which point to things
71 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
72 // Ensure we're below 1 GB to be safe.
73 if (max_capacity > 1 * GB) {
74 std::ostringstream oss;
75 oss << "Maxium code cache capacity is limited to 1 GB, "
76 << PrettySize(max_capacity) << " is too big";
77 *error_msg = oss.str();
78 return nullptr;
79 }
80
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080081 std::string error_str;
82 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +010083 // Map in low 4gb to simplify accessing root tables for x86_64.
84 // We could do PC-relative addressing to avoid this problem, but that
85 // would require reserving code and data area before submitting, which
86 // means more windows for the code memory to be RWX.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010087 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +010088 "data-code-cache", nullptr,
89 max_capacity,
90 kProtAll,
91 /* low_4gb */ true,
92 /* reuse */ false,
93 &error_str,
94 use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010095 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080096 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000097 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080098 *error_msg = oss.str();
99 return nullptr;
100 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100101
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000102 // Align both capacities to page size, as that's the unit mspaces use.
103 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
104 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
105
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +0000106 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100107 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000108 size_t data_size = max_capacity / 2;
109 size_t code_size = max_capacity - data_size;
110 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100111 uint8_t* divider = data_map->Begin() + data_size;
112
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000113 MemMap* code_map =
114 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100115 if (code_map == nullptr) {
116 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000117 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100118 *error_msg = oss.str();
119 return nullptr;
120 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100121 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000122 data_size = initial_capacity / 2;
123 code_size = initial_capacity - data_size;
124 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000125 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000126 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800127}
128
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000129JitCodeCache::JitCodeCache(MemMap* code_map,
130 MemMap* data_map,
131 size_t initial_code_capacity,
132 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000133 size_t max_capacity,
134 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100135 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100136 lock_cond_("Jit code cache variable", lock_),
137 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100138 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000139 data_map_(data_map),
140 max_capacity_(max_capacity),
141 current_capacity_(initial_code_capacity + initial_data_capacity),
142 code_end_(initial_code_capacity),
143 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000144 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000145 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000146 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000147 used_memory_for_data_(0),
148 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000149 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000150 number_of_osr_compilations_(0),
151 number_of_deoptimizations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000152 number_of_collections_(0),
153 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
154 histogram_code_memory_use_("Memory used for compiled code", 16),
155 histogram_profiling_info_memory_use_("Memory used for profiling info", 16) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100156
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000157 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000158 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
159 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100160
161 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
162 PLOG(FATAL) << "create_mspace_with_base failed";
163 }
164
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000165 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100166
167 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
168 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100169
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000170 VLOG(jit) << "Created jit code cache: initial data size="
171 << PrettySize(initial_data_capacity)
172 << ", initial code size="
173 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800174}
175
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100176bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100177 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800178}
179
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000180bool JitCodeCache::ContainsMethod(ArtMethod* method) {
181 MutexLock mu(Thread::Current(), lock_);
182 for (auto& it : method_code_map_) {
183 if (it.second == method) {
184 return true;
185 }
186 }
187 return false;
188}
189
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800190class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100191 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800192 explicit ScopedCodeCacheWrite(MemMap* code_map)
193 : ScopedTrace("ScopedCodeCacheWrite"),
194 code_map_(code_map) {
195 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100196 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800197 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100198 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800199 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
201 }
202 private:
203 MemMap* const code_map_;
204
205 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
206};
207
208uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100209 ArtMethod* method,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100210 uint8_t* stack_map,
211 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100212 size_t frame_size_in_bytes,
213 size_t core_spill_mask,
214 size_t fp_spill_mask,
215 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000216 size_t code_size,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100217 bool osr,
218 Handle<mirror::ObjectArray<mirror::Object>> roots) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100219 uint8_t* result = CommitCodeInternal(self,
220 method,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100221 stack_map,
222 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100223 frame_size_in_bytes,
224 core_spill_mask,
225 fp_spill_mask,
226 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000227 code_size,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100228 osr,
229 roots);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100230 if (result == nullptr) {
231 // Retry.
232 GarbageCollectCache(self);
233 result = CommitCodeInternal(self,
234 method,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100235 stack_map,
236 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100237 frame_size_in_bytes,
238 core_spill_mask,
239 fp_spill_mask,
240 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000241 code_size,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100242 osr,
243 roots);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100244 }
245 return result;
246}
247
248bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
249 bool in_collection = false;
250 while (collection_in_progress_) {
251 in_collection = true;
252 lock_cond_.Wait(self);
253 }
254 return in_collection;
255}
256
257static uintptr_t FromCodeToAllocation(const void* code) {
258 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
259 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
260}
261
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100262static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
263 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
264}
265
266static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
267 // The length of the table is stored just before the stack map (and therefore at the end of
268 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
269 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
270}
271
272static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
273 REQUIRES_SHARED(Locks::mutator_lock_) {
274 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
275 uint32_t length = roots->GetLength();
276 // Put all roots in `roots_data`.
277 for (uint32_t i = 0; i < length; ++i) {
278 gc_roots[i] = GcRoot<mirror::Object>(roots->Get(i));
279 }
280 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
281 // pointer.
282 reinterpret_cast<uint32_t*>(gc_roots + length)[0] = length;
283}
284
285static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
286 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
287 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
288 uint32_t roots = GetNumberOfRoots(data);
289 if (number_of_roots != nullptr) {
290 *number_of_roots = roots;
291 }
292 return data - ComputeRootTableSize(roots);
293}
294
295void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
296 MutexLock mu(Thread::Current(), lock_);
297 for (const auto& entry : method_code_map_) {
298 uint32_t number_of_roots = 0;
299 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
300 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
301 for (uint32_t i = 0; i < number_of_roots; ++i) {
302 // This does not need a read barrier because this is called by GC.
303 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
304 DCHECK(object->IsString());
305 mirror::Object* new_string = visitor->IsMarked(object);
306 // We know the string is marked because it's a strongly-interned string that
307 // is always alive.
308 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
309 // out of the weak access/creation pause. b/32167580
310 DCHECK(new_string != nullptr);
311 roots[i] = GcRoot<mirror::Object>(new_string);
312 }
313 }
314}
315
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100316void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
317 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000318 // Notify native debugger that we are about to remove the code.
319 // It does nothing if we are not using native debugger.
320 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100321 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000322 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100323}
324
325void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800326 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100327 MutexLock mu(self, lock_);
328 // We do not check if a code cache GC is in progress, as this method comes
329 // with the classlinker_classes_lock_ held, and suspending ourselves could
330 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000331 {
332 ScopedCodeCacheWrite scc(code_map_.get());
333 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
334 if (alloc.ContainsUnsafe(it->second)) {
335 FreeCode(it->first, it->second);
336 it = method_code_map_.erase(it);
337 } else {
338 ++it;
339 }
340 }
341 }
Nicolas Geoffraya9b91312016-02-17 09:49:19 +0000342 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
343 if (alloc.ContainsUnsafe(it->first)) {
344 // Note that the code has already been removed in the loop above.
345 it = osr_code_map_.erase(it);
346 } else {
347 ++it;
348 }
349 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000350 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
351 ProfilingInfo* info = *it;
352 if (alloc.ContainsUnsafe(info->GetMethod())) {
353 info->GetMethod()->SetProfilingInfo(nullptr);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000354 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000355 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100356 } else {
357 ++it;
358 }
359 }
360}
361
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000362void JitCodeCache::ClearGcRootsInInlineCaches(Thread* self) {
363 MutexLock mu(self, lock_);
364 for (ProfilingInfo* info : profiling_infos_) {
365 if (!info->IsInUseByCompiler()) {
366 info->ClearGcRootsInInlineCaches();
367 }
368 }
369}
370
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100371uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
372 ArtMethod* method,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100373 uint8_t* stack_map,
374 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100375 size_t frame_size_in_bytes,
376 size_t core_spill_mask,
377 size_t fp_spill_mask,
378 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000379 size_t code_size,
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100380 bool osr,
381 Handle<mirror::ObjectArray<mirror::Object>> roots) {
382 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100383 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
384 // Ensure the header ends up at expected instruction alignment.
385 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
386 size_t total_size = header_size + code_size;
387
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100388 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100389 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000390 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100391 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000392 ScopedThreadSuspension sts(self, kSuspended);
393 MutexLock mu(self, lock_);
394 WaitForPotentialCollectionToComplete(self);
395 {
396 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000397 memory = AllocateCode(total_size);
398 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000399 return nullptr;
400 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000401 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000402
403 std::copy(code, code + code_size, code_ptr);
404 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
405 new (method_header) OatQuickMethodHeader(
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100406 code_ptr - stack_map,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000407 frame_size_in_bytes,
408 core_spill_mask,
409 fp_spill_mask,
410 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100411 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100412
Roland Levillain32430262016-02-01 15:23:20 +0000413 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
414 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000415 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100416 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000417 // We need to update the entry point in the runnable state for the instrumentation.
418 {
419 MutexLock mu(self, lock_);
420 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100421 // Fill the root table before updating the entry point.
422 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000423 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000424 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000425 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100426 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000427 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
428 method, method_header->GetEntryPoint());
429 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000430 if (collection_in_progress_) {
431 // We need to update the live bitmap if there is a GC to ensure it sees this new
432 // code.
433 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
434 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000435 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000436 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100437 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700438 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000439 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
440 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
441 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
442 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000443 histogram_code_memory_use_.AddValue(code_size);
444 if (code_size > kCodeSizeLogThreshold) {
445 LOG(INFO) << "JIT allocated "
446 << PrettySize(code_size)
447 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700448 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000449 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000450 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100451
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100452 return reinterpret_cast<uint8_t*>(method_header);
453}
454
455size_t JitCodeCache::CodeCacheSize() {
456 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000457 return CodeCacheSizeLocked();
458}
459
460size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000461 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100462}
463
464size_t JitCodeCache::DataCacheSize() {
465 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000466 return DataCacheSizeLocked();
467}
468
469size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000470 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800471}
472
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000473void JitCodeCache::ClearData(Thread* self, void* data) {
474 MutexLock mu(self, lock_);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000475 FreeData(reinterpret_cast<uint8_t*>(data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000476}
477
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100478void JitCodeCache::ReserveData(Thread* self,
479 size_t stack_map_size,
480 size_t number_of_roots,
481 ArtMethod* method,
482 uint8_t** stack_map_data,
483 uint8_t** roots_data) {
484 size_t table_size = ComputeRootTableSize(number_of_roots);
485 size_t size = RoundUp(stack_map_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100486 uint8_t* result = nullptr;
487
488 {
489 ScopedThreadSuspension sts(self, kSuspended);
490 MutexLock mu(self, lock_);
491 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000492 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100493 }
494
495 if (result == nullptr) {
496 // Retry.
497 GarbageCollectCache(self);
498 ScopedThreadSuspension sts(self, kSuspended);
499 MutexLock mu(self, lock_);
500 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000501 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100502 }
503
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000504 MutexLock mu(self, lock_);
505 histogram_stack_map_memory_use_.AddValue(size);
506 if (size > kStackMapSizeLogThreshold) {
507 LOG(INFO) << "JIT allocated "
508 << PrettySize(size)
509 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700510 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800511 }
Nicolas Geoffrayac3ebc32016-10-05 13:13:50 +0100512 *roots_data = result;
513 *stack_map_data = result + table_size;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800514}
515
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100516class MarkCodeVisitor FINAL : public StackVisitor {
517 public:
518 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
519 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
520 code_cache_(code_cache_in),
521 bitmap_(code_cache_->GetLiveBitmap()) {}
522
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700523 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100524 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
525 if (method_header == nullptr) {
526 return true;
527 }
528 const void* code = method_header->GetCode();
529 if (code_cache_->ContainsPc(code)) {
530 // Use the atomic set version, as multiple threads are executing this code.
531 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
532 }
533 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800534 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100535
536 private:
537 JitCodeCache* const code_cache_;
538 CodeCacheBitmap* const bitmap_;
539};
540
541class MarkCodeClosure FINAL : public Closure {
542 public:
543 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
544 : code_cache_(code_cache), barrier_(barrier) {}
545
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700546 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800547 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100548 DCHECK(thread == Thread::Current() || thread->IsSuspended());
549 MarkCodeVisitor visitor(thread, code_cache_);
550 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000551 if (kIsDebugBuild) {
552 // The stack walking code queries the side instrumentation stack if it
553 // sees an instrumentation exit pc, so the JIT code of methods in that stack
554 // must have been seen. We sanity check this below.
555 for (const instrumentation::InstrumentationStackFrame& frame
556 : *thread->GetInstrumentationStack()) {
557 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
558 // its stack frame, it is not the method owning return_pc_. We just pass null to
559 // LookupMethodHeader: the method is only checked against in debug builds.
560 OatQuickMethodHeader* method_header =
561 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
562 if (method_header != nullptr) {
563 const void* code = method_header->GetCode();
564 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
565 }
566 }
567 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700568 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800569 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100570
571 private:
572 JitCodeCache* const code_cache_;
573 Barrier* const barrier_;
574};
575
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000576void JitCodeCache::NotifyCollectionDone(Thread* self) {
577 collection_in_progress_ = false;
578 lock_cond_.Broadcast(self);
579}
580
581void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
582 size_t per_space_footprint = new_footprint / 2;
583 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
584 DCHECK_EQ(per_space_footprint * 2, new_footprint);
585 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
586 {
587 ScopedCodeCacheWrite scc(code_map_.get());
588 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
589 }
590}
591
592bool JitCodeCache::IncreaseCodeCacheCapacity() {
593 if (current_capacity_ == max_capacity_) {
594 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100595 }
596
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000597 // Double the capacity if we're below 1MB, or increase it by 1MB if
598 // we're above.
599 if (current_capacity_ < 1 * MB) {
600 current_capacity_ *= 2;
601 } else {
602 current_capacity_ += 1 * MB;
603 }
604 if (current_capacity_ > max_capacity_) {
605 current_capacity_ = max_capacity_;
606 }
607
608 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
609 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
610 }
611
612 SetFootprintLimit(current_capacity_);
613
614 return true;
615}
616
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000617void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
618 Barrier barrier(0);
619 size_t threads_running_checkpoint = 0;
620 MarkCodeClosure closure(this, &barrier);
621 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
622 // Now that we have run our checkpoint, move to a suspended state and wait
623 // for other threads to run the checkpoint.
624 ScopedThreadSuspension sts(self, kSuspended);
625 if (threads_running_checkpoint != 0) {
626 barrier.Increment(self, threads_running_checkpoint);
627 }
628}
629
Nicolas Geoffray35122442016-03-02 12:05:30 +0000630bool JitCodeCache::ShouldDoFullCollection() {
631 if (current_capacity_ == max_capacity_) {
632 // Always do a full collection when the code cache is full.
633 return true;
634 } else if (current_capacity_ < kReservedCapacity) {
635 // Always do partial collection when the code cache size is below the reserved
636 // capacity.
637 return false;
638 } else if (last_collection_increased_code_cache_) {
639 // This time do a full collection.
640 return true;
641 } else {
642 // This time do a partial collection.
643 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000644 }
645}
646
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000647void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800648 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000649 if (!garbage_collect_code_) {
650 MutexLock mu(self, lock_);
651 IncreaseCodeCacheCapacity();
652 return;
653 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100654
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000655 // Wait for an existing collection, or let everyone know we are starting one.
656 {
657 ScopedThreadSuspension sts(self, kSuspended);
658 MutexLock mu(self, lock_);
659 if (WaitForPotentialCollectionToComplete(self)) {
660 return;
661 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000662 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000663 live_bitmap_.reset(CodeCacheBitmap::Create(
664 "code-cache-bitmap",
665 reinterpret_cast<uintptr_t>(code_map_->Begin()),
666 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000667 collection_in_progress_ = true;
668 }
669 }
670
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000671 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000672 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000673 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000674
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000675 bool do_full_collection = false;
676 {
677 MutexLock mu(self, lock_);
678 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000679 }
680
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000681 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
682 LOG(INFO) << "Do "
683 << (do_full_collection ? "full" : "partial")
684 << " code cache collection, code="
685 << PrettySize(CodeCacheSize())
686 << ", data=" << PrettySize(DataCacheSize());
687 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000688
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000689 DoCollection(self, /* collect_profiling_info */ do_full_collection);
690
691 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
692 LOG(INFO) << "After code cache collection, code="
693 << PrettySize(CodeCacheSize())
694 << ", data=" << PrettySize(DataCacheSize());
695 }
696
697 {
698 MutexLock mu(self, lock_);
699
700 // Increase the code cache only when we do partial collections.
701 // TODO: base this strategy on how full the code cache is?
702 if (do_full_collection) {
703 last_collection_increased_code_cache_ = false;
704 } else {
705 last_collection_increased_code_cache_ = true;
706 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000707 }
708
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000709 bool next_collection_will_be_full = ShouldDoFullCollection();
710
711 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100712 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000713 // Save the entry point of methods we have compiled, and update the entry
714 // point of those methods to the interpreter. If the method is invoked, the
715 // interpreter will update its entry point to the compiled code and call it.
716 for (ProfilingInfo* info : profiling_infos_) {
717 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
718 if (ContainsPc(entry_point)) {
719 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100720 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
721 info->GetMethod(), GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000722 }
723 }
724
725 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
726 }
727 live_bitmap_.reset(nullptr);
728 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000729 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000730 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000731 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000732}
733
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000734void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800735 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000736 MutexLock mu(self, lock_);
737 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000738 // Iterate over all compiled code and remove entries that are not marked.
Nicolas Geoffray35122442016-03-02 12:05:30 +0000739 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
740 const void* code_ptr = it->first;
741 ArtMethod* method = it->second;
742 uintptr_t allocation = FromCodeToAllocation(code_ptr);
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000743 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000744 ++it;
745 } else {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000746 FreeCode(code_ptr, method);
747 it = method_code_map_.erase(it);
748 }
749 }
750}
751
752void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800753 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000754 {
755 MutexLock mu(self, lock_);
756 if (collect_profiling_info) {
757 // Clear the profiling info of methods that do not have compiled code as entrypoint.
758 // Also remove the saved entry point from the ProfilingInfo objects.
759 for (ProfilingInfo* info : profiling_infos_) {
760 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000761 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000762 info->GetMethod()->SetProfilingInfo(nullptr);
763 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +0000764
765 if (info->GetSavedEntryPoint() != nullptr) {
766 info->SetSavedEntryPoint(nullptr);
767 // We are going to move this method back to interpreter. Clear the counter now to
768 // give it a chance to be hot again.
769 info->GetMethod()->ClearCounter();
770 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000771 }
772 } else if (kIsDebugBuild) {
773 // Sanity check that the profiling infos do not have a dangling entry point.
774 for (ProfilingInfo* info : profiling_infos_) {
775 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100776 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000777 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000778
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000779 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
780 // an entry point is either:
781 // - an osr compiled code, that will be removed if not in a thread call stack.
782 // - discarded compiled code, that will be removed if not in a thread call stack.
783 for (const auto& it : method_code_map_) {
784 ArtMethod* method = it.second;
785 const void* code_ptr = it.first;
786 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
787 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
788 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
789 }
790 }
791
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000792 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000793 // on thread stacks).
794 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100795 }
796
797 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000798 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100799
Nicolas Geoffray9abb2972016-03-04 14:32:59 +0000800 // At this point, mutator threads are still running, and entrypoints of methods can
801 // change. We do know they cannot change to a code cache entry that is not marked,
802 // therefore we can safely remove those entries.
803 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000804
Nicolas Geoffray35122442016-03-02 12:05:30 +0000805 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +0100806 ScopedThreadSuspension sts(self, kSuspended);
807 gc::ScopedGCCriticalSection gcs(
808 self, gc::kGcCauseJitCodeCache, gc::kCollectorTypeJitCodeCache);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000809 MutexLock mu(self, lock_);
810 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100811 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000812 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000813 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000814 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
815 // that the compiled code would not get revived. As mutator threads run concurrently,
816 // they may have revived the compiled code, and now we are in the situation where
817 // a method has compiled code but no ProfilingInfo.
818 // We make sure compiled methods have a ProfilingInfo object. It is needed for
819 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -0700820 if (ContainsPc(ptr) &&
821 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000822 // We clear the inline caches as classes in it might be stalled.
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000823 info->ClearGcRootsInInlineCaches();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +0000824 // Do a fence to make sure the clearing is seen before attaching to the method.
825 QuasiAtomic::ThreadFenceRelease();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000826 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -0700827 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000828 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000829 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100830 return true;
831 }
832 return false;
833 });
834 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +0000835 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100836 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800837}
838
Nicolas Geoffray35122442016-03-02 12:05:30 +0000839bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800840 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +0000841 // Check that methods we have compiled do have a ProfilingInfo object. We would
842 // have memory leaks of compiled code otherwise.
843 for (const auto& it : method_code_map_) {
844 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -0700845 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +0000846 const void* code_ptr = it.first;
847 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
848 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
849 // If the code is not dead, then we have a problem. Note that this can even
850 // happen just after a collection, as mutator threads are running in parallel
851 // and could deoptimize an existing compiled code.
852 return false;
853 }
854 }
855 }
856 return true;
857}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100858
859OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
860 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
861 if (kRuntimeISA == kArm) {
862 // On Thumb-2, the pc is offset by one.
863 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800864 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100865 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
866 return nullptr;
867 }
868
869 MutexLock mu(Thread::Current(), lock_);
870 if (method_code_map_.empty()) {
871 return nullptr;
872 }
873 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
874 --it;
875
876 const void* code_ptr = it->first;
877 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
878 if (!method_header->Contains(pc)) {
879 return nullptr;
880 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000881 if (kIsDebugBuild && method != nullptr) {
882 DCHECK_EQ(it->second, method)
David Sehr709b0702016-10-13 09:12:37 -0700883 << ArtMethod::PrettyMethod(method) << " " << ArtMethod::PrettyMethod(it->second) << " "
884 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000885 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100886 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800887}
888
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000889OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
890 MutexLock mu(Thread::Current(), lock_);
891 auto it = osr_code_map_.find(method);
892 if (it == osr_code_map_.end()) {
893 return nullptr;
894 }
895 return OatQuickMethodHeader::FromCodePointer(it->second);
896}
897
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000898ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
899 ArtMethod* method,
900 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000901 bool retry_allocation)
902 // No thread safety analysis as we are using TryLock/Unlock explicitly.
903 NO_THREAD_SAFETY_ANALYSIS {
904 ProfilingInfo* info = nullptr;
905 if (!retry_allocation) {
906 // If we are allocating for the interpreter, just try to lock, to avoid
907 // lock contention with the JIT.
908 if (lock_.ExclusiveTryLock(self)) {
909 info = AddProfilingInfoInternal(self, method, entries);
910 lock_.ExclusiveUnlock(self);
911 }
912 } else {
913 {
914 MutexLock mu(self, lock_);
915 info = AddProfilingInfoInternal(self, method, entries);
916 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000917
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000918 if (info == nullptr) {
919 GarbageCollectCache(self);
920 MutexLock mu(self, lock_);
921 info = AddProfilingInfoInternal(self, method, entries);
922 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000923 }
924 return info;
925}
926
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +0000927ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000928 ArtMethod* method,
929 const std::vector<uint32_t>& entries) {
930 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100931 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000932 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000933
934 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -0700935 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000936 if (info != nullptr) {
937 return info;
938 }
939
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000940 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000941 if (data == nullptr) {
942 return nullptr;
943 }
944 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000945
946 // Make sure other threads see the data in the profiling info object before the
947 // store in the ArtMethod's ProfilingInfo pointer.
948 QuasiAtomic::ThreadFenceRelease();
949
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000950 method->SetProfilingInfo(info);
951 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000952 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000953 return info;
954}
955
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000956// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
957// is already held.
958void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
959 if (code_mspace_ == mspace) {
960 size_t result = code_end_;
961 code_end_ += increment;
962 return reinterpret_cast<void*>(result + code_map_->Begin());
963 } else {
964 DCHECK_EQ(data_mspace_, mspace);
965 size_t result = data_end_;
966 data_end_ += increment;
967 return reinterpret_cast<void*>(result + data_map_->Begin());
968 }
969}
970
Calin Juravle99629622016-04-19 16:33:46 +0100971void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
972 std::vector<MethodReference>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800973 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +0100974 MutexLock mu(Thread::Current(), lock_);
Calin Juravle99629622016-04-19 16:33:46 +0100975 for (const ProfilingInfo* info : profiling_infos_) {
976 ArtMethod* method = info->GetMethod();
977 const DexFile* dex_file = method->GetDexFile();
978 if (ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
979 methods.emplace_back(dex_file, method->GetDexMethodIndex());
Calin Juravle31f2c152015-10-23 17:56:15 +0100980 }
981 }
982}
983
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000984uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
985 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100986}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100987
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100988bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
989 MutexLock mu(Thread::Current(), lock_);
990 return osr_code_map_.find(method) != osr_code_map_.end();
991}
992
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000993bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
994 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100995 return false;
996 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000997
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000998 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000999 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1000 return false;
1001 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001002
Andreas Gampe542451c2016-07-26 09:02:02 -07001003 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001004 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001005 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001006 // Because the counter is not atomic, there are some rare cases where we may not
1007 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1008 // "correct" this.
1009 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001010 return false;
1011 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001012
buzbee454b3b62016-04-07 14:42:47 -07001013 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001014 return false;
1015 }
1016
buzbee454b3b62016-04-07 14:42:47 -07001017 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001018 return true;
1019}
1020
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001021ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001022 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001023 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001024 if (info != nullptr) {
1025 info->IncrementInlineUse();
1026 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001027 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001028}
1029
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001030void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001031 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001032 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001033 DCHECK(info != nullptr);
1034 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001035}
1036
buzbee454b3b62016-04-07 14:42:47 -07001037void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001038 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001039 DCHECK(info->IsMethodBeingCompiled(osr));
1040 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001041}
1042
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001043size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1044 MutexLock mu(Thread::Current(), lock_);
1045 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1046}
1047
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001048void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1049 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001050 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001051 if ((profiling_info != nullptr) &&
1052 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1053 // Prevent future uses of the compiled code.
1054 profiling_info->SetSavedEntryPoint(nullptr);
1055 }
1056
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001057 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1058 // The entrypoint is the one to invalidate, so we just update
1059 // it to the interpreter entry point and clear the counter to get the method
1060 // Jitted again.
1061 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1062 method, GetQuickToInterpreterBridge());
1063 method->ClearCounter();
1064 } else {
1065 MutexLock mu(Thread::Current(), lock_);
1066 auto it = osr_code_map_.find(method);
1067 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1068 // Remove the OSR method, to avoid using it again.
1069 osr_code_map_.erase(it);
1070 }
1071 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001072 MutexLock mu(Thread::Current(), lock_);
1073 number_of_deoptimizations_++;
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001074}
1075
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001076uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1077 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1078 uint8_t* result = reinterpret_cast<uint8_t*>(
1079 mspace_memalign(code_mspace_, alignment, code_size));
1080 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1081 // Ensure the header ends up at expected instruction alignment.
1082 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1083 used_memory_for_code_ += mspace_usable_size(result);
1084 return result;
1085}
1086
1087void JitCodeCache::FreeCode(uint8_t* code) {
1088 used_memory_for_code_ -= mspace_usable_size(code);
1089 mspace_free(code_mspace_, code);
1090}
1091
1092uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1093 void* result = mspace_malloc(data_mspace_, data_size);
1094 used_memory_for_data_ += mspace_usable_size(result);
1095 return reinterpret_cast<uint8_t*>(result);
1096}
1097
1098void JitCodeCache::FreeData(uint8_t* data) {
1099 used_memory_for_data_ -= mspace_usable_size(data);
1100 mspace_free(data_mspace_, data);
1101}
1102
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001103void JitCodeCache::Dump(std::ostream& os) {
1104 MutexLock mu(Thread::Current(), lock_);
1105 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1106 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1107 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1108 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1109 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1110 << "Total number of JIT compilations for on stack replacement: "
1111 << number_of_osr_compilations_ << "\n"
1112 << "Total number of deoptimizations: " << number_of_deoptimizations_ << "\n"
1113 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001114 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1115 histogram_code_memory_use_.PrintMemoryUse(os);
1116 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001117}
1118
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001119} // namespace jit
1120} // namespace art