blob: a39b7a3143f4614798c98310cde0392d2c297fe8 [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
Andreas Gampe5629d2d2017-05-15 16:28:13 -070021#include "arch/context.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070022#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070023#include "base/enums.h"
Calin Juravle66f55232015-12-08 15:09:10 +000024#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010026#include "base/time_utils.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070027#include "cha.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000028#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "entrypoints/runtime_asm_entrypoints.h"
30#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010031#include "gc/scoped_gc_critical_section.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000032#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000033#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010034#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080035#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080036#include "oat_file-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070037#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010038#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080039
40namespace art {
41namespace jit {
42
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010043static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
44static constexpr int kProtData = PROT_READ | PROT_WRITE;
45static constexpr int kProtCode = PROT_READ | PROT_EXEC;
46
Nicolas Geoffray933330a2016-03-16 14:20:06 +000047static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
48static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
49
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010050#define CHECKED_MPROTECT(memory, size, prot) \
51 do { \
52 int rc = mprotect(memory, size, prot); \
53 if (UNLIKELY(rc != 0)) { \
54 errno = rc; \
55 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
56 } \
57 } while (false) \
58
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000059JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
60 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000061 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080063 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000064 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000065
66 // Generating debug information is mostly for using the 'perf' tool, which does
67 // not work with ashmem.
68 bool use_ashmem = !generate_debug_info;
69 // With 'perf', we want a 1-1 mapping between an address and a method.
70 bool garbage_collect_code = !generate_debug_info;
71
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000072 // We need to have 32 bit offsets from method headers in code cache which point to things
73 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
74 // Ensure we're below 1 GB to be safe.
75 if (max_capacity > 1 * GB) {
76 std::ostringstream oss;
77 oss << "Maxium code cache capacity is limited to 1 GB, "
78 << PrettySize(max_capacity) << " is too big";
79 *error_msg = oss.str();
80 return nullptr;
81 }
82
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080083 std::string error_str;
84 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray132d8362016-11-16 09:19:42 +000085 // Map in low 4gb to simplify accessing root tables for x86_64.
86 // We could do PC-relative addressing to avoid this problem, but that
87 // would require reserving code and data area before submitting, which
88 // means more windows for the code memory to be RWX.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010089 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000090 "data-code-cache", nullptr,
91 max_capacity,
92 kProtAll,
93 /* low_4gb */ true,
94 /* reuse */ false,
95 &error_str,
96 use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010097 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080098 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000099 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800100 *error_msg = oss.str();
101 return nullptr;
102 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000104 // Align both capacities to page size, as that's the unit mspaces use.
105 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
106 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
107
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +0000108 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100109 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000110 size_t data_size = max_capacity / 2;
111 size_t code_size = max_capacity - data_size;
112 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100113 uint8_t* divider = data_map->Begin() + data_size;
114
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000115 MemMap* code_map =
116 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100117 if (code_map == nullptr) {
118 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000119 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120 *error_msg = oss.str();
121 return nullptr;
122 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100123 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000124 data_size = initial_capacity / 2;
125 code_size = initial_capacity - data_size;
126 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000127 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000128 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800129}
130
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000131JitCodeCache::JitCodeCache(MemMap* code_map,
132 MemMap* data_map,
133 size_t initial_code_capacity,
134 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000135 size_t max_capacity,
136 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100137 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000138 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100139 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100140 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000141 data_map_(data_map),
142 max_capacity_(max_capacity),
143 current_capacity_(initial_code_capacity + initial_data_capacity),
144 code_end_(initial_code_capacity),
145 data_end_(initial_data_capacity),
Nicolas Geoffray35122442016-03-02 12:05:30 +0000146 last_collection_increased_code_cache_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000147 last_update_time_ns_(0),
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000148 garbage_collect_code_(garbage_collect_code),
Nicolas Geoffrayb0d22082016-02-24 17:18:25 +0000149 used_memory_for_data_(0),
150 used_memory_for_code_(0),
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000151 number_of_compilations_(0),
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000152 number_of_osr_compilations_(0),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000153 number_of_collections_(0),
154 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
155 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000156 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
157 is_weak_access_enabled_(true),
158 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100159
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000160 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000161 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
162 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100163
164 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
165 PLOG(FATAL) << "create_mspace_with_base failed";
166 }
167
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000168 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100169
170 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
171 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100172
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000173 VLOG(jit) << "Created jit code cache: initial data size="
174 << PrettySize(initial_data_capacity)
175 << ", initial code size="
176 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800177}
178
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100179bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100180 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800181}
182
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000183bool JitCodeCache::ContainsMethod(ArtMethod* method) {
184 MutexLock mu(Thread::Current(), lock_);
185 for (auto& it : method_code_map_) {
186 if (it.second == method) {
187 return true;
188 }
189 }
190 return false;
191}
192
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800193class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100194 public:
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800195 explicit ScopedCodeCacheWrite(MemMap* code_map)
196 : ScopedTrace("ScopedCodeCacheWrite"),
197 code_map_(code_map) {
198 ScopedTrace trace("mprotect all");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100199 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800200 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100201 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800202 ScopedTrace trace("mprotect code");
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100203 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
204 }
205 private:
206 MemMap* const code_map_;
207
208 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
209};
210
211uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100212 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000213 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700214 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000215 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100216 size_t frame_size_in_bytes,
217 size_t core_spill_mask,
218 size_t fp_spill_mask,
219 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000220 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000221 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000222 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700223 Handle<mirror::ObjectArray<mirror::Object>> roots,
224 bool has_should_deoptimize_flag,
225 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100226 uint8_t* result = CommitCodeInternal(self,
227 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000228 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700229 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000230 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100231 frame_size_in_bytes,
232 core_spill_mask,
233 fp_spill_mask,
234 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000235 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000236 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000237 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700238 roots,
239 has_should_deoptimize_flag,
240 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100241 if (result == nullptr) {
242 // Retry.
243 GarbageCollectCache(self);
244 result = CommitCodeInternal(self,
245 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000246 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700247 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000248 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100249 frame_size_in_bytes,
250 core_spill_mask,
251 fp_spill_mask,
252 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000253 code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000254 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000255 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700256 roots,
257 has_should_deoptimize_flag,
258 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100259 }
260 return result;
261}
262
263bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
264 bool in_collection = false;
265 while (collection_in_progress_) {
266 in_collection = true;
267 lock_cond_.Wait(self);
268 }
269 return in_collection;
270}
271
272static uintptr_t FromCodeToAllocation(const void* code) {
273 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
274 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
275}
276
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000277static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
278 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
279}
280
281static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
282 // The length of the table is stored just before the stack map (and therefore at the end of
283 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
284 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
285}
286
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800287static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
288 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
289 // pointer.
290 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
291}
292
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000293static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
294 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
295}
296
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000297static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
298 REQUIRES_SHARED(Locks::mutator_lock_) {
299 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800300 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000301 // Put all roots in `roots_data`.
302 for (uint32_t i = 0; i < length; ++i) {
303 ObjPtr<mirror::Object> object = roots->Get(i);
304 if (kIsDebugBuild) {
305 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000306 if (object->IsString()) {
307 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
308 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
309 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
310 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000311 }
312 gc_roots[i] = GcRoot<mirror::Object>(object);
313 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000314}
315
316static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
317 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
318 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
319 uint32_t roots = GetNumberOfRoots(data);
320 if (number_of_roots != nullptr) {
321 *number_of_roots = roots;
322 }
323 return data - ComputeRootTableSize(roots);
324}
325
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100326// Use a sentinel for marking entries in the JIT table that have been cleared.
327// This helps diagnosing in case the compiled code tries to wrongly access such
328// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700329static mirror::Class* const weak_sentinel =
330 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100331
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000332// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100333static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
334 IsMarkedVisitor* visitor,
335 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000336 REQUIRES_SHARED(Locks::mutator_lock_) {
337 // This does not need a read barrier because this is called by GC.
338 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100339 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000340 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
341 // Look at the classloader of the class to know if it has been unloaded.
342 // This does not need a read barrier because this is called by GC.
343 mirror::Object* class_loader =
344 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
345 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
346 // The class loader is live, update the entry if the class has moved.
347 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
348 // Note that new_object can be null for CMS and newly allocated objects.
349 if (new_cls != nullptr && new_cls != cls) {
350 *root_ptr = GcRoot<mirror::Class>(new_cls);
351 }
352 } else {
353 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100354 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000355 }
356 }
357}
358
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000359void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
360 MutexLock mu(Thread::Current(), lock_);
361 for (const auto& entry : method_code_map_) {
362 uint32_t number_of_roots = 0;
363 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
364 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
365 for (uint32_t i = 0; i < number_of_roots; ++i) {
366 // This does not need a read barrier because this is called by GC.
367 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100368 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000369 // entry got deleted in a previous sweep.
370 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
371 mirror::Object* new_object = visitor->IsMarked(object);
372 // We know the string is marked because it's a strongly-interned string that
373 // is always alive. The IsMarked implementation of the CMS collector returns
374 // null for newly allocated objects, but we know those haven't moved. Therefore,
375 // only update the entry if we get a different non-null string.
376 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
377 // out of the weak access/creation pause. b/32167580
378 if (new_object != nullptr && new_object != object) {
379 DCHECK(new_object->IsString());
380 roots[i] = GcRoot<mirror::Object>(new_object);
381 }
382 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100383 ProcessWeakClass(
384 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000385 }
386 }
387 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000388 // Walk over inline caches to clear entries containing unloaded classes.
389 for (ProfilingInfo* info : profiling_infos_) {
390 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
391 InlineCache* cache = &info->cache_[i];
392 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100393 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000394 }
395 }
396 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000397}
398
Mingyao Yang063fc772016-08-02 11:02:54 -0700399void JitCodeCache::FreeCode(const void* code_ptr) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100400 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000401 // Notify native debugger that we are about to remove the code.
402 // It does nothing if we are not using native debugger.
403 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000404 FreeData(GetRootTable(code_ptr));
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000405 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100406}
407
Mingyao Yang063fc772016-08-02 11:02:54 -0700408void JitCodeCache::FreeAllMethodHeaders(
409 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
410 {
411 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
412 Runtime::Current()->GetClassHierarchyAnalysis()
413 ->RemoveDependentsWithMethodHeaders(method_headers);
414 }
415
416 // We need to remove entries in method_headers from CHA dependencies
417 // first since once we do FreeCode() below, the memory can be reused
418 // so it's possible for the same method_header to start representing
419 // different compile code.
420 MutexLock mu(Thread::Current(), lock_);
421 ScopedCodeCacheWrite scc(code_map_.get());
422 for (const OatQuickMethodHeader* method_header : method_headers) {
423 FreeCode(method_header->GetCode());
424 }
425}
426
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100427void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800428 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700429 // We use a set to first collect all method_headers whose code need to be
430 // removed. We need to free the underlying code after we remove CHA dependencies
431 // for entries in this set. And it's more efficient to iterate through
432 // the CHA dependency map just once with an unordered_set.
433 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000434 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700435 MutexLock mu(self, lock_);
436 // We do not check if a code cache GC is in progress, as this method comes
437 // with the classlinker_classes_lock_ held, and suspending ourselves could
438 // lead to a deadlock.
439 {
440 ScopedCodeCacheWrite scc(code_map_.get());
441 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
442 if (alloc.ContainsUnsafe(it->second)) {
443 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
444 it = method_code_map_.erase(it);
445 } else {
446 ++it;
447 }
448 }
449 }
450 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
451 if (alloc.ContainsUnsafe(it->first)) {
452 // Note that the code has already been pushed to method_headers in the loop
453 // above and is going to be removed in FreeCode() below.
454 it = osr_code_map_.erase(it);
455 } else {
456 ++it;
457 }
458 }
459 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
460 ProfilingInfo* info = *it;
461 if (alloc.ContainsUnsafe(info->GetMethod())) {
462 info->GetMethod()->SetProfilingInfo(nullptr);
463 FreeData(reinterpret_cast<uint8_t*>(info));
464 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000465 } else {
466 ++it;
467 }
468 }
469 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700470 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100471}
472
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000473bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
474 return kUseReadBarrier
475 ? self->GetWeakRefAccessEnabled()
476 : is_weak_access_enabled_.LoadSequentiallyConsistent();
477}
478
479void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
480 if (IsWeakAccessEnabled(self)) {
481 return;
482 }
483 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000484 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000485 while (!IsWeakAccessEnabled(self)) {
486 inline_cache_cond_.Wait(self);
487 }
488}
489
490void JitCodeCache::BroadcastForInlineCacheAccess() {
491 Thread* self = Thread::Current();
492 MutexLock mu(self, lock_);
493 inline_cache_cond_.Broadcast(self);
494}
495
496void JitCodeCache::AllowInlineCacheAccess() {
497 DCHECK(!kUseReadBarrier);
498 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
499 BroadcastForInlineCacheAccess();
500}
501
502void JitCodeCache::DisallowInlineCacheAccess() {
503 DCHECK(!kUseReadBarrier);
504 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
505}
506
507void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
508 Handle<mirror::ObjectArray<mirror::Class>> array) {
509 WaitUntilInlineCacheAccessible(Thread::Current());
510 // Note that we don't need to lock `lock_` here, the compiler calling
511 // this method has already ensured the inline cache will not be deleted.
512 for (size_t in_cache = 0, in_array = 0;
513 in_cache < InlineCache::kIndividualCacheSize;
514 ++in_cache) {
515 mirror::Class* object = ic.classes_[in_cache].Read();
516 if (object != nullptr) {
517 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000518 }
519 }
520}
521
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100522uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
523 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000524 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700525 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000526 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100527 size_t frame_size_in_bytes,
528 size_t core_spill_mask,
529 size_t fp_spill_mask,
530 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000531 size_t code_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000532 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000533 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700534 Handle<mirror::ObjectArray<mirror::Object>> roots,
535 bool has_should_deoptimize_flag,
536 const ArenaSet<ArtMethod*>&
537 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000538 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100539 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
540 // Ensure the header ends up at expected instruction alignment.
541 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
542 size_t total_size = header_size + code_size;
543
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100544 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100545 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000546 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100547 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000548 ScopedThreadSuspension sts(self, kSuspended);
549 MutexLock mu(self, lock_);
550 WaitForPotentialCollectionToComplete(self);
551 {
552 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000553 memory = AllocateCode(total_size);
554 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000555 return nullptr;
556 }
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000557 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000558
559 std::copy(code, code + code_size, code_ptr);
560 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
561 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000562 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700563 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000564 frame_size_in_bytes,
565 core_spill_mask,
566 fp_spill_mask,
567 code_size);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000568 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
569 DCHECK_LE(roots_data, stack_map);
570 // Flush data cache, as compiled code references literals in it.
571 FlushDataCache(reinterpret_cast<char*>(roots_data),
572 reinterpret_cast<char*>(roots_data + data_size));
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000573 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
574 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
575 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
576 // 6P) stop being supported or their kernels are fixed.
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300577 //
Kevin Brodskyb93ce182016-12-15 14:23:09 +0000578 // For reference, this behavior is caused by this commit:
579 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
Artem Udovichenkob18a6692016-11-17 10:51:58 +0300580 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
581 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700582 DCHECK(!Runtime::Current()->IsAotCompiler());
583 if (has_should_deoptimize_flag) {
584 method_header->SetHasShouldDeoptimizeFlag();
585 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100586 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100587
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000588 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100589 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000590 // We need to update the entry point in the runnable state for the instrumentation.
591 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700592 // Need cha_lock_ for checking all single-implementation flags and register
593 // dependencies.
594 MutexLock cha_mu(self, *Locks::cha_lock_);
595 bool single_impl_still_valid = true;
596 for (ArtMethod* single_impl : cha_single_implementation_list) {
597 if (!single_impl->HasSingleImplementation()) {
598 // We simply discard the compiled code. Clear the
599 // counter so that it may be recompiled later. Hopefully the
600 // class hierarchy will be more stable when compilation is retried.
601 single_impl_still_valid = false;
602 method->ClearCounter();
603 break;
604 }
605 }
606
607 // Discard the code if any single-implementation assumptions are now invalid.
608 if (!single_impl_still_valid) {
609 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
610 return nullptr;
611 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000612 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800613 << "Should not be using cha on debuggable apps/runs!";
614
Mingyao Yang063fc772016-08-02 11:02:54 -0700615 for (ArtMethod* single_impl : cha_single_implementation_list) {
616 Runtime::Current()->GetClassHierarchyAnalysis()->AddDependency(
617 single_impl, method, method_header);
618 }
619
620 // The following needs to be guarded by cha_lock_ also. Otherwise it's
621 // possible that the compiled code is considered invalidated by some class linking,
622 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000623 MutexLock mu(self, lock_);
624 method_code_map_.Put(code_ptr, method);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000625 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000626 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000627 FillRootTable(roots_data, roots);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000628 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000629 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000630 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100631 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000632 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
633 method, method_header->GetEntryPoint());
634 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000635 if (collection_in_progress_) {
636 // We need to update the live bitmap if there is a GC to ensure it sees this new
637 // code.
638 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
639 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000640 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000641 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100642 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700643 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000644 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
645 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
646 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700647 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
648 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000649 histogram_code_memory_use_.AddValue(code_size);
650 if (code_size > kCodeSizeLogThreshold) {
651 LOG(INFO) << "JIT allocated "
652 << PrettySize(code_size)
653 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700654 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000655 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000656 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100657
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100658 return reinterpret_cast<uint8_t*>(method_header);
659}
660
661size_t JitCodeCache::CodeCacheSize() {
662 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000663 return CodeCacheSizeLocked();
664}
665
Alex Lightdba61482016-12-21 08:20:29 -0800666// This notifies the code cache that the given method has been redefined and that it should remove
667// any cached information it has on the method. All threads must be suspended before calling this
668// method. The compiled code for the method (if there is any) must not be in any threads call stack.
669void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
670 MutexLock mu(Thread::Current(), lock_);
671 if (method->IsNative()) {
672 return;
673 }
674 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
675 if (info != nullptr) {
676 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
677 DCHECK(profile != profiling_infos_.end());
678 profiling_infos_.erase(profile);
679 }
680 method->SetProfilingInfo(nullptr);
681 ScopedCodeCacheWrite ccw(code_map_.get());
Andreas Gampe39e67382017-05-15 19:26:38 -0700682 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800683 if (code_iter->second == method) {
684 FreeCode(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700685 code_iter = method_code_map_.erase(code_iter);
686 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800687 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700688 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800689 }
690 auto code_map = osr_code_map_.find(method);
691 if (code_map != osr_code_map_.end()) {
692 osr_code_map_.erase(code_map);
693 }
694}
695
696// This invalidates old_method. Once this function returns one can no longer use old_method to
697// execute code unless it is fixed up. This fixup will happen later in the process of installing a
698// class redefinition.
699// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
700// shouldn't be used since it is no longer logically in the jit code cache.
701// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
702void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000703 // Native methods have no profiling info and need no special handling from the JIT code cache.
704 if (old_method->IsNative()) {
705 return;
706 }
Alex Lightdba61482016-12-21 08:20:29 -0800707 MutexLock mu(Thread::Current(), lock_);
708 // Update ProfilingInfo to the new one and remove it from the old_method.
709 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
710 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
711 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
712 old_method->SetProfilingInfo(nullptr);
713 // Since the JIT should be paused and all threads suspended by the time this is called these
714 // checks should always pass.
715 DCHECK(!info->IsInUseByCompiler());
716 new_method->SetProfilingInfo(info);
717 info->method_ = new_method;
718 }
719 // Update method_code_map_ to point to the new method.
720 for (auto& it : method_code_map_) {
721 if (it.second == old_method) {
722 it.second = new_method;
723 }
724 }
725 // Update osr_code_map_ to point to the new method.
726 auto code_map = osr_code_map_.find(old_method);
727 if (code_map != osr_code_map_.end()) {
728 osr_code_map_.Put(new_method, code_map->second);
729 osr_code_map_.erase(old_method);
730 }
731}
732
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000733size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000734 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100735}
736
737size_t JitCodeCache::DataCacheSize() {
738 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000739 return DataCacheSizeLocked();
740}
741
742size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000743 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800744}
745
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000746void JitCodeCache::ClearData(Thread* self,
747 uint8_t* stack_map_data,
748 uint8_t* roots_data) {
749 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000750 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000751 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000752}
753
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000754size_t JitCodeCache::ReserveData(Thread* self,
755 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700756 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000757 size_t number_of_roots,
758 ArtMethod* method,
759 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700760 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000761 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000762 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700763 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100764 uint8_t* result = nullptr;
765
766 {
767 ScopedThreadSuspension sts(self, kSuspended);
768 MutexLock mu(self, lock_);
769 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000770 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100771 }
772
773 if (result == nullptr) {
774 // Retry.
775 GarbageCollectCache(self);
776 ScopedThreadSuspension sts(self, kSuspended);
777 MutexLock mu(self, lock_);
778 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000779 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100780 }
781
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000782 MutexLock mu(self, lock_);
783 histogram_stack_map_memory_use_.AddValue(size);
784 if (size > kStackMapSizeLogThreshold) {
785 LOG(INFO) << "JIT allocated "
786 << PrettySize(size)
787 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700788 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800789 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000790 if (result != nullptr) {
791 *roots_data = result;
792 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700793 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000794 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000795 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000796 } else {
797 *roots_data = nullptr;
798 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700799 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000800 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000801 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800802}
803
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100804class MarkCodeVisitor FINAL : public StackVisitor {
805 public:
806 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
807 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
808 code_cache_(code_cache_in),
809 bitmap_(code_cache_->GetLiveBitmap()) {}
810
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700811 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100812 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
813 if (method_header == nullptr) {
814 return true;
815 }
816 const void* code = method_header->GetCode();
817 if (code_cache_->ContainsPc(code)) {
818 // Use the atomic set version, as multiple threads are executing this code.
819 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
820 }
821 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800822 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100823
824 private:
825 JitCodeCache* const code_cache_;
826 CodeCacheBitmap* const bitmap_;
827};
828
829class MarkCodeClosure FINAL : public Closure {
830 public:
831 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
832 : code_cache_(code_cache), barrier_(barrier) {}
833
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700834 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800835 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100836 DCHECK(thread == Thread::Current() || thread->IsSuspended());
837 MarkCodeVisitor visitor(thread, code_cache_);
838 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000839 if (kIsDebugBuild) {
840 // The stack walking code queries the side instrumentation stack if it
841 // sees an instrumentation exit pc, so the JIT code of methods in that stack
842 // must have been seen. We sanity check this below.
843 for (const instrumentation::InstrumentationStackFrame& frame
844 : *thread->GetInstrumentationStack()) {
845 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
846 // its stack frame, it is not the method owning return_pc_. We just pass null to
847 // LookupMethodHeader: the method is only checked against in debug builds.
848 OatQuickMethodHeader* method_header =
849 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
850 if (method_header != nullptr) {
851 const void* code = method_header->GetCode();
852 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
853 }
854 }
855 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700856 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800857 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100858
859 private:
860 JitCodeCache* const code_cache_;
861 Barrier* const barrier_;
862};
863
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000864void JitCodeCache::NotifyCollectionDone(Thread* self) {
865 collection_in_progress_ = false;
866 lock_cond_.Broadcast(self);
867}
868
869void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
870 size_t per_space_footprint = new_footprint / 2;
871 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
872 DCHECK_EQ(per_space_footprint * 2, new_footprint);
873 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
874 {
875 ScopedCodeCacheWrite scc(code_map_.get());
876 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
877 }
878}
879
880bool JitCodeCache::IncreaseCodeCacheCapacity() {
881 if (current_capacity_ == max_capacity_) {
882 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100883 }
884
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000885 // Double the capacity if we're below 1MB, or increase it by 1MB if
886 // we're above.
887 if (current_capacity_ < 1 * MB) {
888 current_capacity_ *= 2;
889 } else {
890 current_capacity_ += 1 * MB;
891 }
892 if (current_capacity_ > max_capacity_) {
893 current_capacity_ = max_capacity_;
894 }
895
896 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
897 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
898 }
899
900 SetFootprintLimit(current_capacity_);
901
902 return true;
903}
904
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000905void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
906 Barrier barrier(0);
907 size_t threads_running_checkpoint = 0;
908 MarkCodeClosure closure(this, &barrier);
909 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
910 // Now that we have run our checkpoint, move to a suspended state and wait
911 // for other threads to run the checkpoint.
912 ScopedThreadSuspension sts(self, kSuspended);
913 if (threads_running_checkpoint != 0) {
914 barrier.Increment(self, threads_running_checkpoint);
915 }
916}
917
Nicolas Geoffray35122442016-03-02 12:05:30 +0000918bool JitCodeCache::ShouldDoFullCollection() {
919 if (current_capacity_ == max_capacity_) {
920 // Always do a full collection when the code cache is full.
921 return true;
922 } else if (current_capacity_ < kReservedCapacity) {
923 // Always do partial collection when the code cache size is below the reserved
924 // capacity.
925 return false;
926 } else if (last_collection_increased_code_cache_) {
927 // This time do a full collection.
928 return true;
929 } else {
930 // This time do a partial collection.
931 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000932 }
933}
934
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000935void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800936 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000937 if (!garbage_collect_code_) {
938 MutexLock mu(self, lock_);
939 IncreaseCodeCacheCapacity();
940 return;
941 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100942
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000943 // Wait for an existing collection, or let everyone know we are starting one.
944 {
945 ScopedThreadSuspension sts(self, kSuspended);
946 MutexLock mu(self, lock_);
947 if (WaitForPotentialCollectionToComplete(self)) {
948 return;
949 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000950 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000951 live_bitmap_.reset(CodeCacheBitmap::Create(
952 "code-cache-bitmap",
953 reinterpret_cast<uintptr_t>(code_map_->Begin()),
954 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000955 collection_in_progress_ = true;
956 }
957 }
958
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000959 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000960 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000961 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000962
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000963 bool do_full_collection = false;
964 {
965 MutexLock mu(self, lock_);
966 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +0000967 }
968
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000969 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
970 LOG(INFO) << "Do "
971 << (do_full_collection ? "full" : "partial")
972 << " code cache collection, code="
973 << PrettySize(CodeCacheSize())
974 << ", data=" << PrettySize(DataCacheSize());
975 }
Nicolas Geoffray35122442016-03-02 12:05:30 +0000976
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000977 DoCollection(self, /* collect_profiling_info */ do_full_collection);
978
979 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
980 LOG(INFO) << "After code cache collection, code="
981 << PrettySize(CodeCacheSize())
982 << ", data=" << PrettySize(DataCacheSize());
983 }
984
985 {
986 MutexLock mu(self, lock_);
987
988 // Increase the code cache only when we do partial collections.
989 // TODO: base this strategy on how full the code cache is?
990 if (do_full_collection) {
991 last_collection_increased_code_cache_ = false;
992 } else {
993 last_collection_increased_code_cache_ = true;
994 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +0000995 }
996
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +0000997 bool next_collection_will_be_full = ShouldDoFullCollection();
998
999 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001000 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001001 // Save the entry point of methods we have compiled, and update the entry
1002 // point of those methods to the interpreter. If the method is invoked, the
1003 // interpreter will update its entry point to the compiled code and call it.
1004 for (ProfilingInfo* info : profiling_infos_) {
1005 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1006 if (ContainsPc(entry_point)) {
1007 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001008 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1009 // class of the method. We may be concurrently running a GC which makes accessing
1010 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1011 // checked that the current entry point is JIT compiled code.
1012 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001013 }
1014 }
1015
1016 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1017 }
1018 live_bitmap_.reset(nullptr);
1019 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001020 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001021 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001022 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001023}
1024
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001025void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001026 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001027 std::unordered_set<OatQuickMethodHeader*> method_headers;
1028 {
1029 MutexLock mu(self, lock_);
1030 ScopedCodeCacheWrite scc(code_map_.get());
1031 // Iterate over all compiled code and remove entries that are not marked.
1032 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1033 const void* code_ptr = it->first;
1034 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1035 if (GetLiveBitmap()->Test(allocation)) {
1036 ++it;
1037 } else {
1038 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1039 it = method_code_map_.erase(it);
1040 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001041 }
1042 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001043 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001044}
1045
1046void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001047 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001048 {
1049 MutexLock mu(self, lock_);
1050 if (collect_profiling_info) {
1051 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1052 // Also remove the saved entry point from the ProfilingInfo objects.
1053 for (ProfilingInfo* info : profiling_infos_) {
1054 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001055 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001056 info->GetMethod()->SetProfilingInfo(nullptr);
1057 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001058
1059 if (info->GetSavedEntryPoint() != nullptr) {
1060 info->SetSavedEntryPoint(nullptr);
1061 // We are going to move this method back to interpreter. Clear the counter now to
1062 // give it a chance to be hot again.
1063 info->GetMethod()->ClearCounter();
1064 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001065 }
1066 } else if (kIsDebugBuild) {
1067 // Sanity check that the profiling infos do not have a dangling entry point.
1068 for (ProfilingInfo* info : profiling_infos_) {
1069 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001070 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001071 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001072
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001073 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1074 // an entry point is either:
1075 // - an osr compiled code, that will be removed if not in a thread call stack.
1076 // - discarded compiled code, that will be removed if not in a thread call stack.
1077 for (const auto& it : method_code_map_) {
1078 ArtMethod* method = it.second;
1079 const void* code_ptr = it.first;
1080 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1081 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1082 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1083 }
1084 }
1085
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001086 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001087 // on thread stacks).
1088 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001089 }
1090
1091 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001092 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001093
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001094 // At this point, mutator threads are still running, and entrypoints of methods can
1095 // change. We do know they cannot change to a code cache entry that is not marked,
1096 // therefore we can safely remove those entries.
1097 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001098
Nicolas Geoffray35122442016-03-02 12:05:30 +00001099 if (collect_profiling_info) {
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +01001100 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001101 MutexLock mu(self, lock_);
1102 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001103 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001104 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001105 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001106 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1107 // that the compiled code would not get revived. As mutator threads run concurrently,
1108 // they may have revived the compiled code, and now we are in the situation where
1109 // a method has compiled code but no ProfilingInfo.
1110 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1111 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001112 if (ContainsPc(ptr) &&
1113 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001114 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001115 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001116 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001117 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001118 return true;
1119 }
1120 return false;
1121 });
1122 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001123 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001124 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001125}
1126
Nicolas Geoffray35122442016-03-02 12:05:30 +00001127bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001128 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001129 // Check that methods we have compiled do have a ProfilingInfo object. We would
1130 // have memory leaks of compiled code otherwise.
1131 for (const auto& it : method_code_map_) {
1132 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001133 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001134 const void* code_ptr = it.first;
1135 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1136 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1137 // If the code is not dead, then we have a problem. Note that this can even
1138 // happen just after a collection, as mutator threads are running in parallel
1139 // and could deoptimize an existing compiled code.
1140 return false;
1141 }
1142 }
1143 }
1144 return true;
1145}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001146
1147OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
1148 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
1149 if (kRuntimeISA == kArm) {
1150 // On Thumb-2, the pc is offset by one.
1151 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001152 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001153 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1154 return nullptr;
1155 }
1156
1157 MutexLock mu(Thread::Current(), lock_);
1158 if (method_code_map_.empty()) {
1159 return nullptr;
1160 }
1161 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1162 --it;
1163
1164 const void* code_ptr = it->first;
1165 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1166 if (!method_header->Contains(pc)) {
1167 return nullptr;
1168 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001169 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001170 // When we are walking the stack to redefine classes and creating obsolete methods it is
1171 // possible that we might have updated the method_code_map by making this method obsolete in a
1172 // previous frame. Therefore we should just check that the non-obsolete version of this method
1173 // is the one we expect. We change to the non-obsolete versions in the error message since the
1174 // obsolete version of the method might not be fully initialized yet. This situation can only
1175 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
1176 // method and it->second should be identical. (See runtime/openjdkjvmti/ti_redefine.cc for more
1177 // information.)
1178 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1179 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1180 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001181 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001182 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001183 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001184}
1185
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001186OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1187 MutexLock mu(Thread::Current(), lock_);
1188 auto it = osr_code_map_.find(method);
1189 if (it == osr_code_map_.end()) {
1190 return nullptr;
1191 }
1192 return OatQuickMethodHeader::FromCodePointer(it->second);
1193}
1194
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001195ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1196 ArtMethod* method,
1197 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001198 bool retry_allocation)
1199 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1200 NO_THREAD_SAFETY_ANALYSIS {
1201 ProfilingInfo* info = nullptr;
1202 if (!retry_allocation) {
1203 // If we are allocating for the interpreter, just try to lock, to avoid
1204 // lock contention with the JIT.
1205 if (lock_.ExclusiveTryLock(self)) {
1206 info = AddProfilingInfoInternal(self, method, entries);
1207 lock_.ExclusiveUnlock(self);
1208 }
1209 } else {
1210 {
1211 MutexLock mu(self, lock_);
1212 info = AddProfilingInfoInternal(self, method, entries);
1213 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001214
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001215 if (info == nullptr) {
1216 GarbageCollectCache(self);
1217 MutexLock mu(self, lock_);
1218 info = AddProfilingInfoInternal(self, method, entries);
1219 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001220 }
1221 return info;
1222}
1223
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001224ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001225 ArtMethod* method,
1226 const std::vector<uint32_t>& entries) {
1227 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001228 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001229 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001230
1231 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001232 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001233 if (info != nullptr) {
1234 return info;
1235 }
1236
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001237 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001238 if (data == nullptr) {
1239 return nullptr;
1240 }
1241 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001242
1243 // Make sure other threads see the data in the profiling info object before the
1244 // store in the ArtMethod's ProfilingInfo pointer.
1245 QuasiAtomic::ThreadFenceRelease();
1246
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001247 method->SetProfilingInfo(info);
1248 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001249 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001250 return info;
1251}
1252
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001253// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1254// is already held.
1255void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1256 if (code_mspace_ == mspace) {
1257 size_t result = code_end_;
1258 code_end_ += increment;
1259 return reinterpret_cast<void*>(result + code_map_->Begin());
1260 } else {
1261 DCHECK_EQ(data_mspace_, mspace);
1262 size_t result = data_end_;
1263 data_end_ += increment;
1264 return reinterpret_cast<void*>(result + data_map_->Begin());
1265 }
1266}
1267
Calin Juravle99629622016-04-19 16:33:46 +01001268void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001269 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001270 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001271 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001272 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001273 for (const ProfilingInfo* info : profiling_infos_) {
1274 ArtMethod* method = info->GetMethod();
1275 const DexFile* dex_file = method->GetDexFile();
Calin Juravle940eb0c2017-01-30 19:30:44 -08001276 if (!ContainsElement(dex_base_locations, dex_file->GetBaseLocation())) {
1277 // Skip dex files which are not profiled.
1278 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001279 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001280 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001281
1282 // If the method didn't reach the compilation threshold don't save the inline caches.
1283 // They might be incomplete and cause unnecessary deoptimizations.
1284 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1285 if (method->GetCounter() < jit_compile_threshold) {
1286 methods.emplace_back(/*ProfileMethodInfo*/
1287 dex_file, method->GetDexMethodIndex(), inline_caches);
1288 continue;
1289 }
1290
Calin Juravle940eb0c2017-01-30 19:30:44 -08001291 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001292 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001293 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001294 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001295 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001296 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1297 mirror::Class* cls = cache.classes_[k].Read();
1298 if (cls == nullptr) {
1299 break;
1300 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001301
Calin Juravle13439f02017-02-21 01:17:21 -08001302 // Check if the receiver is in the boot class path or if it's in the
1303 // same class loader as the caller. If not, skip it, as there is not
1304 // much we can do during AOT.
1305 if (!cls->IsBootStrapClassLoaded() &&
1306 caller->GetClassLoader() != cls->GetClassLoader()) {
1307 is_missing_types = true;
1308 continue;
1309 }
1310
Calin Juravle4ca70a32017-02-21 16:22:24 -08001311 const DexFile* class_dex_file = nullptr;
1312 dex::TypeIndex type_index;
1313
1314 if (cls->GetDexCache() == nullptr) {
1315 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001316 // Make a best effort to find the type index in the method's dex file.
1317 // We could search all open dex files but that might turn expensive
1318 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001319 class_dex_file = dex_file;
1320 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1321 } else {
1322 class_dex_file = &(cls->GetDexFile());
1323 type_index = cls->GetDexTypeIndex();
1324 }
1325 if (!type_index.IsValid()) {
1326 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001327 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001328 continue;
1329 }
1330 if (ContainsElement(dex_base_locations, class_dex_file->GetBaseLocation())) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001331 // Only consider classes from the same apk (including multidex).
1332 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001333 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001334 } else {
1335 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001336 }
1337 }
1338 if (!profile_classes.empty()) {
1339 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001340 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001341 }
1342 }
1343 methods.emplace_back(/*ProfileMethodInfo*/
1344 dex_file, method->GetDexMethodIndex(), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001345 }
1346}
1347
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001348uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1349 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001350}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001351
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001352bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1353 MutexLock mu(Thread::Current(), lock_);
1354 return osr_code_map_.find(method) != osr_code_map_.end();
1355}
1356
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001357bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1358 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001359 return false;
1360 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001361
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001362 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001363 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1364 return false;
1365 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001366
Andreas Gampe542451c2016-07-26 09:02:02 -07001367 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001368 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001369 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001370 // Because the counter is not atomic, there are some rare cases where we may not
1371 // hit the threshold for creating the ProfilingInfo. Reset the counter now to
1372 // "correct" this.
1373 method->ClearCounter();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001374 return false;
1375 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001376
buzbee454b3b62016-04-07 14:42:47 -07001377 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001378 return false;
1379 }
1380
buzbee454b3b62016-04-07 14:42:47 -07001381 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001382 return true;
1383}
1384
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001385ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001386 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001387 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001388 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001389 if (!info->IncrementInlineUse()) {
1390 // Overflow of inlining uses, just bail.
1391 return nullptr;
1392 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001393 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001394 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001395}
1396
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001397void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001398 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001399 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001400 DCHECK(info != nullptr);
1401 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001402}
1403
buzbee454b3b62016-04-07 14:42:47 -07001404void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001405 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001406 DCHECK(info->IsMethodBeingCompiled(osr));
1407 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001408}
1409
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001410size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1411 MutexLock mu(Thread::Current(), lock_);
1412 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1413}
1414
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001415void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1416 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001417 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001418 if ((profiling_info != nullptr) &&
1419 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1420 // Prevent future uses of the compiled code.
1421 profiling_info->SetSavedEntryPoint(nullptr);
1422 }
1423
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001424 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
1425 // The entrypoint is the one to invalidate, so we just update
1426 // it to the interpreter entry point and clear the counter to get the method
1427 // Jitted again.
1428 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1429 method, GetQuickToInterpreterBridge());
1430 method->ClearCounter();
1431 } else {
1432 MutexLock mu(Thread::Current(), lock_);
1433 auto it = osr_code_map_.find(method);
1434 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1435 // Remove the OSR method, to avoid using it again.
1436 osr_code_map_.erase(it);
1437 }
1438 }
1439}
1440
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001441uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1442 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1443 uint8_t* result = reinterpret_cast<uint8_t*>(
1444 mspace_memalign(code_mspace_, alignment, code_size));
1445 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1446 // Ensure the header ends up at expected instruction alignment.
1447 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1448 used_memory_for_code_ += mspace_usable_size(result);
1449 return result;
1450}
1451
1452void JitCodeCache::FreeCode(uint8_t* code) {
1453 used_memory_for_code_ -= mspace_usable_size(code);
1454 mspace_free(code_mspace_, code);
1455}
1456
1457uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1458 void* result = mspace_malloc(data_mspace_, data_size);
1459 used_memory_for_data_ += mspace_usable_size(result);
1460 return reinterpret_cast<uint8_t*>(result);
1461}
1462
1463void JitCodeCache::FreeData(uint8_t* data) {
1464 used_memory_for_data_ -= mspace_usable_size(data);
1465 mspace_free(data_mspace_, data);
1466}
1467
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001468void JitCodeCache::Dump(std::ostream& os) {
1469 MutexLock mu(Thread::Current(), lock_);
1470 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1471 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1472 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1473 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1474 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1475 << "Total number of JIT compilations for on stack replacement: "
1476 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001477 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001478 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1479 histogram_code_memory_use_.PrintMemoryUse(os);
1480 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001481}
1482
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001483} // namespace jit
1484} // namespace art