blob: e1807525ea26049815654ae36c808100974d901d [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"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070029#include "dex_file_loader.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010030#include "entrypoints/runtime_asm_entrypoints.h"
31#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffraycf48fa02016-07-30 22:49:11 +010032#include "gc/scoped_gc_critical_section.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070033#include "intern_table.h"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +000034#include "jit/jit.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000035#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010036#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080037#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080038#include "oat_file-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070039#include "oat_quick_method_header.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070040#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070041#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070042#include "stack.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010043#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080044
45namespace art {
46namespace jit {
47
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010048static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
49static constexpr int kProtData = PROT_READ | PROT_WRITE;
50static constexpr int kProtCode = PROT_READ | PROT_EXEC;
51
Nicolas Geoffray933330a2016-03-16 14:20:06 +000052static constexpr size_t kCodeSizeLogThreshold = 50 * KB;
53static constexpr size_t kStackMapSizeLogThreshold = 50 * KB;
54
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000055JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
56 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000057 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000058 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080059 ScopedTrace trace(__PRETTY_FUNCTION__);
Orion Hodsondbd05fe2017-08-10 11:41:35 +010060 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000061
David Sehrd1dbb742017-07-17 11:20:38 -070062 // Generating debug information is for using the Linux perf tool on
63 // host which does not work with ashmem.
Nicolas Geoffray520dadf2017-07-19 15:33:11 +010064 // Also, target linux does not support ashmem.
65 bool use_ashmem = !generate_debug_info && !kIsTargetLinux;
David Sehrd1dbb742017-07-17 11:20:38 -070066
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000067 // 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 Geoffray132d8362016-11-16 09:19:42 +000083 // 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.
Andreas Gampee4deaf32017-06-09 15:27:15 -070087 std::unique_ptr<MemMap> data_map(MemMap::MapAnonymous(
Nicolas Geoffray132d8362016-11-16 09:19:42 +000088 "data-code-cache", nullptr,
89 max_capacity,
Andreas Gampee4deaf32017-06-09 15:27:15 -070090 kProtData,
Nicolas Geoffray132d8362016-11-16 09:19:42 +000091 /* low_4gb */ true,
92 /* reuse */ false,
93 &error_str,
Andreas Gampee4deaf32017-06-09 15:27:15 -070094 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;
Andreas Gampee4deaf32017-06-09 15:27:15 -070097 oss << "Failed to create read write 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
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100102 // 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);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100105
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100106 // Data cache is 1 / 2 of the map.
107 // TODO: Make this variable?
108 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);
111 uint8_t* divider = data_map->Begin() + data_size;
David Sehrd1dbb742017-07-17 11:20:38 -0700112
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100113 MemMap* code_map =
114 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
David Sehrd1dbb742017-07-17 11:20:38 -0700115 if (code_map == nullptr) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100116 std::ostringstream oss;
117 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
118 *error_msg = oss.str();
David Sehrd1dbb742017-07-17 11:20:38 -0700119 return nullptr;
120 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +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);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100125 return new JitCodeCache(
126 code_map, data_map.release(), code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800127}
128
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100129JitCodeCache::JitCodeCache(MemMap* code_map,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000130 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 Geoffraye51ca8b2016-11-22 14:49:31 +0000136 lock_cond_("Jit code cache condition variable", lock_),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100137 collection_in_progress_(false),
Orion Hodsondbd05fe2017-08-10 11:41:35 +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),
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000151 number_of_collections_(0),
152 histogram_stack_map_memory_use_("Memory used for stack maps", 16),
153 histogram_code_memory_use_("Memory used for compiled code", 16),
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000154 histogram_profiling_info_memory_use_("Memory used for profiling info", 16),
155 is_weak_access_enabled_(true),
156 inline_cache_cond_("Jit inline cache condition variable", lock_) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100157
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000158 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100159 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000160 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100161
162 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
163 PLOG(FATAL) << "create_mspace_with_base failed";
164 }
165
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000166 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100167
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700168 CheckedCall(mprotect,
169 "mprotect jit code cache",
170 code_map_->Begin(),
171 code_map_->Size(),
172 kProtCode);
173 CheckedCall(mprotect,
174 "mprotect jit data cache",
175 data_map_->Begin(),
176 data_map_->Size(),
177 kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100178
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000179 VLOG(jit) << "Created jit code cache: initial data size="
180 << PrettySize(initial_data_capacity)
181 << ", initial code size="
182 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800183}
184
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100185bool JitCodeCache::ContainsPc(const void* ptr) const {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100186 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800187}
188
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000189bool JitCodeCache::ContainsMethod(ArtMethod* method) {
190 MutexLock mu(Thread::Current(), lock_);
191 for (auto& it : method_code_map_) {
192 if (it.second == method) {
193 return true;
194 }
195 }
196 return false;
197}
198
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800199class ScopedCodeCacheWrite : ScopedTrace {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100200 public:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100201 explicit ScopedCodeCacheWrite(MemMap* code_map, bool only_for_tlb_shootdown = false)
202 : ScopedTrace("ScopedCodeCacheWrite"),
203 code_map_(code_map),
204 only_for_tlb_shootdown_(only_for_tlb_shootdown) {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800205 ScopedTrace trace("mprotect all");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700206 CheckedCall(mprotect,
207 "make code writable",
208 code_map_->Begin(),
209 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
210 kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800211 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100212 ~ScopedCodeCacheWrite() {
Mathieu Chartier33fbf372016-03-07 13:48:08 -0800213 ScopedTrace trace("mprotect code");
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700214 CheckedCall(mprotect,
215 "make code protected",
216 code_map_->Begin(),
217 only_for_tlb_shootdown_ ? kPageSize : code_map_->Size(),
218 kProtCode);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100219 }
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700220
David Sehrd1dbb742017-07-17 11:20:38 -0700221 private:
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100222 MemMap* const code_map_;
223
224 // If we're using ScopedCacheWrite only for TLB shootdown, we limit the scope of mprotect to
225 // one page.
226 const bool only_for_tlb_shootdown_;
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100227
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100228 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
229};
230
231uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100232 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000233 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700234 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000235 uint8_t* roots_data,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100236 size_t frame_size_in_bytes,
237 size_t core_spill_mask,
238 size_t fp_spill_mask,
239 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000240 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100241 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000242 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700243 Handle<mirror::ObjectArray<mirror::Object>> roots,
244 bool has_should_deoptimize_flag,
245 const ArenaSet<ArtMethod*>& cha_single_implementation_list) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100246 uint8_t* result = CommitCodeInternal(self,
247 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000248 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700249 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000250 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100251 frame_size_in_bytes,
252 core_spill_mask,
253 fp_spill_mask,
254 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000255 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100256 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000257 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700258 roots,
259 has_should_deoptimize_flag,
260 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100261 if (result == nullptr) {
262 // Retry.
263 GarbageCollectCache(self);
264 result = CommitCodeInternal(self,
265 method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000266 stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700267 method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000268 roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100269 frame_size_in_bytes,
270 core_spill_mask,
271 fp_spill_mask,
272 code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000273 code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100274 data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000275 osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700276 roots,
277 has_should_deoptimize_flag,
278 cha_single_implementation_list);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100279 }
280 return result;
281}
282
283bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
284 bool in_collection = false;
285 while (collection_in_progress_) {
286 in_collection = true;
287 lock_cond_.Wait(self);
288 }
289 return in_collection;
290}
291
292static uintptr_t FromCodeToAllocation(const void* code) {
293 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
294 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
295}
296
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000297static uint32_t ComputeRootTableSize(uint32_t number_of_roots) {
298 return sizeof(uint32_t) + number_of_roots * sizeof(GcRoot<mirror::Object>);
299}
300
301static uint32_t GetNumberOfRoots(const uint8_t* stack_map) {
302 // The length of the table is stored just before the stack map (and therefore at the end of
303 // the table itself), in order to be able to fetch it from a `stack_map` pointer.
304 return reinterpret_cast<const uint32_t*>(stack_map)[-1];
305}
306
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800307static void FillRootTableLength(uint8_t* roots_data, uint32_t length) {
308 // Store the length of the table at the end. This will allow fetching it from a `stack_map`
309 // pointer.
310 reinterpret_cast<uint32_t*>(roots_data)[length] = length;
311}
312
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000313static const uint8_t* FromStackMapToRoots(const uint8_t* stack_map_data) {
314 return stack_map_data - ComputeRootTableSize(GetNumberOfRoots(stack_map_data));
315}
316
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000317static void FillRootTable(uint8_t* roots_data, Handle<mirror::ObjectArray<mirror::Object>> roots)
318 REQUIRES_SHARED(Locks::mutator_lock_) {
319 GcRoot<mirror::Object>* gc_roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
Mathieu Chartier7a704be2016-11-22 13:24:40 -0800320 const uint32_t length = roots->GetLength();
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000321 // Put all roots in `roots_data`.
322 for (uint32_t i = 0; i < length; ++i) {
323 ObjPtr<mirror::Object> object = roots->Get(i);
324 if (kIsDebugBuild) {
325 // Ensure the string is strongly interned. b/32995596
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000326 if (object->IsString()) {
327 ObjPtr<mirror::String> str = reinterpret_cast<mirror::String*>(object.Ptr());
328 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
329 CHECK(class_linker->GetInternTable()->LookupStrong(Thread::Current(), str) != nullptr);
330 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000331 }
332 gc_roots[i] = GcRoot<mirror::Object>(object);
333 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000334}
335
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100336static uint8_t* GetRootTable(const void* code_ptr, uint32_t* number_of_roots = nullptr) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000337 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
338 uint8_t* data = method_header->GetOptimizedCodeInfoPtr();
339 uint32_t roots = GetNumberOfRoots(data);
340 if (number_of_roots != nullptr) {
341 *number_of_roots = roots;
342 }
343 return data - ComputeRootTableSize(roots);
344}
345
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100346// Use a sentinel for marking entries in the JIT table that have been cleared.
347// This helps diagnosing in case the compiled code tries to wrongly access such
348// entries.
Andreas Gampe5629d2d2017-05-15 16:28:13 -0700349static mirror::Class* const weak_sentinel =
350 reinterpret_cast<mirror::Class*>(Context::kBadGprBase + 0xff);
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100351
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000352// Helper for the GC to process a weak class in a JIT root table.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100353static inline void ProcessWeakClass(GcRoot<mirror::Class>* root_ptr,
354 IsMarkedVisitor* visitor,
355 mirror::Class* update)
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000356 REQUIRES_SHARED(Locks::mutator_lock_) {
357 // This does not need a read barrier because this is called by GC.
358 mirror::Class* cls = root_ptr->Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100359 if (cls != nullptr && cls != weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000360 DCHECK((cls->IsClass<kDefaultVerifyFlags, kWithoutReadBarrier>()));
361 // Look at the classloader of the class to know if it has been unloaded.
362 // This does not need a read barrier because this is called by GC.
363 mirror::Object* class_loader =
364 cls->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>();
365 if (class_loader == nullptr || visitor->IsMarked(class_loader) != nullptr) {
366 // The class loader is live, update the entry if the class has moved.
367 mirror::Class* new_cls = down_cast<mirror::Class*>(visitor->IsMarked(cls));
368 // Note that new_object can be null for CMS and newly allocated objects.
369 if (new_cls != nullptr && new_cls != cls) {
370 *root_ptr = GcRoot<mirror::Class>(new_cls);
371 }
372 } else {
373 // The class loader is not live, clear the entry.
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100374 *root_ptr = GcRoot<mirror::Class>(update);
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000375 }
376 }
377}
378
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000379void JitCodeCache::SweepRootTables(IsMarkedVisitor* visitor) {
380 MutexLock mu(Thread::Current(), lock_);
381 for (const auto& entry : method_code_map_) {
382 uint32_t number_of_roots = 0;
383 uint8_t* roots_data = GetRootTable(entry.first, &number_of_roots);
384 GcRoot<mirror::Object>* roots = reinterpret_cast<GcRoot<mirror::Object>*>(roots_data);
385 for (uint32_t i = 0; i < number_of_roots; ++i) {
386 // This does not need a read barrier because this is called by GC.
387 mirror::Object* object = roots[i].Read<kWithoutReadBarrier>();
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100388 if (object == nullptr || object == weak_sentinel) {
Nicolas Geoffray22384ae2016-12-12 22:33:36 +0000389 // entry got deleted in a previous sweep.
390 } else if (object->IsString<kDefaultVerifyFlags, kWithoutReadBarrier>()) {
391 mirror::Object* new_object = visitor->IsMarked(object);
392 // We know the string is marked because it's a strongly-interned string that
393 // is always alive. The IsMarked implementation of the CMS collector returns
394 // null for newly allocated objects, but we know those haven't moved. Therefore,
395 // only update the entry if we get a different non-null string.
396 // TODO: Do not use IsMarked for j.l.Class, and adjust once we move this method
397 // out of the weak access/creation pause. b/32167580
398 if (new_object != nullptr && new_object != object) {
399 DCHECK(new_object->IsString());
400 roots[i] = GcRoot<mirror::Object>(new_object);
401 }
402 } else {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100403 ProcessWeakClass(
404 reinterpret_cast<GcRoot<mirror::Class>*>(&roots[i]), visitor, weak_sentinel);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000405 }
406 }
407 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000408 // Walk over inline caches to clear entries containing unloaded classes.
409 for (ProfilingInfo* info : profiling_infos_) {
410 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
411 InlineCache* cache = &info->cache_[i];
412 for (size_t j = 0; j < InlineCache::kIndividualCacheSize; ++j) {
Nicolas Geoffray6ca115b2017-05-10 15:09:35 +0100413 ProcessWeakClass(&cache->classes_[j], visitor, nullptr);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000414 }
415 }
416 }
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000417}
418
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100419void JitCodeCache::FreeCode(const void* code_ptr) {
420 uintptr_t allocation = FromCodeToAllocation(code_ptr);
David Srbecky5cc349f2015-12-18 15:04:48 +0000421 // Notify native debugger that we are about to remove the code.
422 // It does nothing if we are not using native debugger.
423 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000424 FreeData(GetRootTable(code_ptr));
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100425 FreeCode(reinterpret_cast<uint8_t*>(allocation));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100426}
427
Mingyao Yang063fc772016-08-02 11:02:54 -0700428void JitCodeCache::FreeAllMethodHeaders(
429 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
430 {
431 MutexLock mu(Thread::Current(), *Locks::cha_lock_);
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700432 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()
Mingyao Yang063fc772016-08-02 11:02:54 -0700433 ->RemoveDependentsWithMethodHeaders(method_headers);
434 }
435
436 // We need to remove entries in method_headers from CHA dependencies
437 // first since once we do FreeCode() below, the memory can be reused
438 // so it's possible for the same method_header to start representing
439 // different compile code.
440 MutexLock mu(Thread::Current(), lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100441 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700442 for (const OatQuickMethodHeader* method_header : method_headers) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100443 FreeCode(method_header->GetCode());
Mingyao Yang063fc772016-08-02 11:02:54 -0700444 }
445}
446
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100447void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800448 ScopedTrace trace(__PRETTY_FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -0700449 // We use a set to first collect all method_headers whose code need to be
450 // removed. We need to free the underlying code after we remove CHA dependencies
451 // for entries in this set. And it's more efficient to iterate through
452 // the CHA dependency map just once with an unordered_set.
453 std::unordered_set<OatQuickMethodHeader*> method_headers;
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000454 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700455 MutexLock mu(self, lock_);
456 // We do not check if a code cache GC is in progress, as this method comes
457 // with the classlinker_classes_lock_ held, and suspending ourselves could
458 // lead to a deadlock.
459 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100460 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -0700461 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
462 if (alloc.ContainsUnsafe(it->second)) {
463 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
464 it = method_code_map_.erase(it);
465 } else {
466 ++it;
467 }
468 }
469 }
470 for (auto it = osr_code_map_.begin(); it != osr_code_map_.end();) {
471 if (alloc.ContainsUnsafe(it->first)) {
472 // Note that the code has already been pushed to method_headers in the loop
473 // above and is going to be removed in FreeCode() below.
474 it = osr_code_map_.erase(it);
475 } else {
476 ++it;
477 }
478 }
479 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
480 ProfilingInfo* info = *it;
481 if (alloc.ContainsUnsafe(info->GetMethod())) {
482 info->GetMethod()->SetProfilingInfo(nullptr);
483 FreeData(reinterpret_cast<uint8_t*>(info));
484 it = profiling_infos_.erase(it);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000485 } else {
486 ++it;
487 }
488 }
489 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700490 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100491}
492
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000493bool JitCodeCache::IsWeakAccessEnabled(Thread* self) const {
494 return kUseReadBarrier
495 ? self->GetWeakRefAccessEnabled()
496 : is_weak_access_enabled_.LoadSequentiallyConsistent();
497}
498
499void JitCodeCache::WaitUntilInlineCacheAccessible(Thread* self) {
500 if (IsWeakAccessEnabled(self)) {
501 return;
502 }
503 ScopedThreadSuspension sts(self, kWaitingWeakGcRootRead);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000504 MutexLock mu(self, lock_);
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000505 while (!IsWeakAccessEnabled(self)) {
506 inline_cache_cond_.Wait(self);
507 }
508}
509
510void JitCodeCache::BroadcastForInlineCacheAccess() {
511 Thread* self = Thread::Current();
512 MutexLock mu(self, lock_);
513 inline_cache_cond_.Broadcast(self);
514}
515
516void JitCodeCache::AllowInlineCacheAccess() {
517 DCHECK(!kUseReadBarrier);
518 is_weak_access_enabled_.StoreSequentiallyConsistent(true);
519 BroadcastForInlineCacheAccess();
520}
521
522void JitCodeCache::DisallowInlineCacheAccess() {
523 DCHECK(!kUseReadBarrier);
524 is_weak_access_enabled_.StoreSequentiallyConsistent(false);
525}
526
527void JitCodeCache::CopyInlineCacheInto(const InlineCache& ic,
528 Handle<mirror::ObjectArray<mirror::Class>> array) {
529 WaitUntilInlineCacheAccessible(Thread::Current());
530 // Note that we don't need to lock `lock_` here, the compiler calling
531 // this method has already ensured the inline cache will not be deleted.
532 for (size_t in_cache = 0, in_array = 0;
533 in_cache < InlineCache::kIndividualCacheSize;
534 ++in_cache) {
535 mirror::Class* object = ic.classes_[in_cache].Read();
536 if (object != nullptr) {
537 array->Set(in_array++, object);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000538 }
539 }
540}
541
Mathieu Chartierf044c222017-05-31 15:27:54 -0700542static void ClearMethodCounter(ArtMethod* method, bool was_warm) {
543 if (was_warm) {
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +0100544 method->SetPreviouslyWarm();
Mathieu Chartierf044c222017-05-31 15:27:54 -0700545 }
546 // We reset the counter to 1 so that the profile knows that the method was executed at least once.
547 // This is required for layout purposes.
Nicolas Geoffray88f50b12017-06-09 16:08:47 +0100548 // We also need to make sure we'll pass the warmup threshold again, so we set to 0 if
549 // the warmup threshold is 1.
550 uint16_t jit_warmup_threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
551 method->SetCounter(std::min(jit_warmup_threshold - 1, 1));
Mathieu Chartierf044c222017-05-31 15:27:54 -0700552}
553
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100554uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
555 ArtMethod* method,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000556 uint8_t* stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700557 uint8_t* method_info,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000558 uint8_t* roots_data,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100559 size_t frame_size_in_bytes,
560 size_t core_spill_mask,
561 size_t fp_spill_mask,
562 const uint8_t* code,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000563 size_t code_size,
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100564 size_t data_size,
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000565 bool osr,
Mingyao Yang063fc772016-08-02 11:02:54 -0700566 Handle<mirror::ObjectArray<mirror::Object>> roots,
567 bool has_should_deoptimize_flag,
568 const ArenaSet<ArtMethod*>&
569 cha_single_implementation_list) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000570 DCHECK(stack_map != nullptr);
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100571 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
572 // Ensure the header ends up at expected instruction alignment.
573 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
574 size_t total_size = header_size + code_size;
575
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100576 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100577 uint8_t* code_ptr = nullptr;
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000578 uint8_t* memory = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100579 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000580 ScopedThreadSuspension sts(self, kSuspended);
581 MutexLock mu(self, lock_);
582 WaitForPotentialCollectionToComplete(self);
583 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100584 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000585 memory = AllocateCode(total_size);
586 if (memory == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000587 return nullptr;
588 }
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100589 code_ptr = memory + header_size;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000590
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100591 std::copy(code, code + code_size, code_ptr);
592 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
593 new (method_header) OatQuickMethodHeader(
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000594 code_ptr - stack_map,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700595 code_ptr - method_info,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000596 frame_size_in_bytes,
597 core_spill_mask,
598 fp_spill_mask,
599 code_size);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100600 // Flush caches before we remove write permission because some ARMv8 Qualcomm kernels may
601 // trigger a segfault if a page fault occurs when requesting a cache maintenance operation.
602 // This is a kernel bug that we need to work around until affected devices (e.g. Nexus 5X and
603 // 6P) stop being supported or their kernels are fixed.
604 //
605 // For reference, this behavior is caused by this commit:
606 // https://android.googlesource.com/kernel/msm/+/3fbe6bc28a6b9939d0650f2f17eb5216c719950c
607 FlushInstructionCache(reinterpret_cast<char*>(code_ptr),
608 reinterpret_cast<char*>(code_ptr + code_size));
Mingyao Yang063fc772016-08-02 11:02:54 -0700609 DCHECK(!Runtime::Current()->IsAotCompiler());
610 if (has_should_deoptimize_flag) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100611 method_header->SetHasShouldDeoptimizeFlag();
Mingyao Yang063fc772016-08-02 11:02:54 -0700612 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100613 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100614
Nicolas Geoffray0a522232016-01-19 09:34:58 +0000615 number_of_compilations_++;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100616 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000617 // We need to update the entry point in the runnable state for the instrumentation.
618 {
Mingyao Yang063fc772016-08-02 11:02:54 -0700619 // Need cha_lock_ for checking all single-implementation flags and register
620 // dependencies.
621 MutexLock cha_mu(self, *Locks::cha_lock_);
622 bool single_impl_still_valid = true;
623 for (ArtMethod* single_impl : cha_single_implementation_list) {
624 if (!single_impl->HasSingleImplementation()) {
Jeff Hao00286db2017-05-30 16:53:07 -0700625 // Simply discard the compiled code. Clear the counter so that it may be recompiled later.
626 // Hopefully the class hierarchy will be more stable when compilation is retried.
Mingyao Yang063fc772016-08-02 11:02:54 -0700627 single_impl_still_valid = false;
Mathieu Chartierf044c222017-05-31 15:27:54 -0700628 ClearMethodCounter(method, /*was_warm*/ false);
Mingyao Yang063fc772016-08-02 11:02:54 -0700629 break;
630 }
631 }
632
633 // Discard the code if any single-implementation assumptions are now invalid.
634 if (!single_impl_still_valid) {
635 VLOG(jit) << "JIT discarded jitted code due to invalid single-implementation assumptions.";
636 return nullptr;
637 }
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000638 DCHECK(cha_single_implementation_list.empty() || !Runtime::Current()->IsJavaDebuggable())
Alex Lightdba61482016-12-21 08:20:29 -0800639 << "Should not be using cha on debuggable apps/runs!";
640
Mingyao Yang063fc772016-08-02 11:02:54 -0700641 for (ArtMethod* single_impl : cha_single_implementation_list) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700642 Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()->AddDependency(
Mingyao Yang063fc772016-08-02 11:02:54 -0700643 single_impl, method, method_header);
644 }
645
646 // The following needs to be guarded by cha_lock_ also. Otherwise it's
647 // possible that the compiled code is considered invalidated by some class linking,
648 // but below we still make the compiled code valid for the method.
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000649 MutexLock mu(self, lock_);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000650 // Fill the root table before updating the entry point.
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000651 DCHECK_EQ(FromStackMapToRoots(stack_map), roots_data);
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100652 DCHECK_LE(roots_data, stack_map);
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000653 FillRootTable(roots_data, roots);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100654 {
655 // Flush data cache, as compiled code references literals in it.
656 // We also need a TLB shootdown to act as memory barrier across cores.
657 ScopedCodeCacheWrite ccw(code_map_.get(), /* only_for_tlb_shootdown */ true);
658 FlushDataCache(reinterpret_cast<char*>(roots_data),
659 reinterpret_cast<char*>(roots_data + data_size));
660 }
Nicolas Geoffray352b17a2017-05-25 12:54:31 +0100661 method_code_map_.Put(code_ptr, method);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000662 if (osr) {
Nicolas Geoffrayfcdd7292016-02-25 13:27:47 +0000663 number_of_osr_compilations_++;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000664 osr_code_map_.Put(method, code_ptr);
Nicolas Geoffray480d5102016-04-18 12:09:30 +0100665 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000666 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
667 method, method_header->GetEntryPoint());
668 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000669 if (collection_in_progress_) {
670 // We need to update the live bitmap if there is a GC to ensure it sees this new
671 // code.
672 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
673 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000674 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000675 VLOG(jit)
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +0100676 << "JIT added (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
David Sehr709b0702016-10-13 09:12:37 -0700677 << ArtMethod::PrettyMethod(method) << "@" << method
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000678 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
679 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
680 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
Mingyao Yang063fc772016-08-02 11:02:54 -0700681 << reinterpret_cast<const void*>(method_header->GetEntryPoint() +
682 method_header->GetCodeSize());
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000683 histogram_code_memory_use_.AddValue(code_size);
684 if (code_size > kCodeSizeLogThreshold) {
685 LOG(INFO) << "JIT allocated "
686 << PrettySize(code_size)
687 << " for compiled code of "
David Sehr709b0702016-10-13 09:12:37 -0700688 << ArtMethod::PrettyMethod(method);
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000689 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000690 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100691
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100692 return reinterpret_cast<uint8_t*>(method_header);
693}
694
695size_t JitCodeCache::CodeCacheSize() {
696 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000697 return CodeCacheSizeLocked();
698}
699
Orion Hodsoneced6922017-06-01 10:54:28 +0100700bool JitCodeCache::RemoveMethod(ArtMethod* method, bool release_memory) {
701 MutexLock mu(Thread::Current(), lock_);
702 if (method->IsNative()) {
703 return false;
704 }
705
706 bool in_cache = false;
707 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100708 ScopedCodeCacheWrite ccw(code_map_.get());
Orion Hodsoneced6922017-06-01 10:54:28 +0100709 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
710 if (code_iter->second == method) {
711 if (release_memory) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100712 FreeCode(code_iter->first);
Orion Hodsoneced6922017-06-01 10:54:28 +0100713 }
714 code_iter = method_code_map_.erase(code_iter);
715 in_cache = true;
716 continue;
717 }
718 ++code_iter;
719 }
720 }
721
722 bool osr = false;
723 auto code_map = osr_code_map_.find(method);
724 if (code_map != osr_code_map_.end()) {
725 osr_code_map_.erase(code_map);
726 osr = true;
727 }
728
729 if (!in_cache) {
730 return false;
731 }
732
733 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
734 if (info != nullptr) {
735 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
736 DCHECK(profile != profiling_infos_.end());
737 profiling_infos_.erase(profile);
738 }
739 method->SetProfilingInfo(nullptr);
740 method->ClearCounter();
741 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
742 method, GetQuickToInterpreterBridge());
743 VLOG(jit)
744 << "JIT removed (osr=" << std::boolalpha << osr << std::noboolalpha << ") "
745 << ArtMethod::PrettyMethod(method) << "@" << method
746 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
747 << " dcache_size=" << PrettySize(DataCacheSizeLocked());
748 return true;
749}
750
Alex Lightdba61482016-12-21 08:20:29 -0800751// This notifies the code cache that the given method has been redefined and that it should remove
752// any cached information it has on the method. All threads must be suspended before calling this
753// method. The compiled code for the method (if there is any) must not be in any threads call stack.
754void JitCodeCache::NotifyMethodRedefined(ArtMethod* method) {
755 MutexLock mu(Thread::Current(), lock_);
756 if (method->IsNative()) {
757 return;
758 }
759 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
760 if (info != nullptr) {
761 auto profile = std::find(profiling_infos_.begin(), profiling_infos_.end(), info);
762 DCHECK(profile != profiling_infos_.end());
763 profiling_infos_.erase(profile);
764 }
765 method->SetProfilingInfo(nullptr);
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100766 ScopedCodeCacheWrite ccw(code_map_.get());
Andreas Gampe39e67382017-05-15 19:26:38 -0700767 for (auto code_iter = method_code_map_.begin(); code_iter != method_code_map_.end();) {
Alex Lightdba61482016-12-21 08:20:29 -0800768 if (code_iter->second == method) {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100769 FreeCode(code_iter->first);
Andreas Gampe39e67382017-05-15 19:26:38 -0700770 code_iter = method_code_map_.erase(code_iter);
771 continue;
Alex Lightdba61482016-12-21 08:20:29 -0800772 }
Andreas Gampe39e67382017-05-15 19:26:38 -0700773 ++code_iter;
Alex Lightdba61482016-12-21 08:20:29 -0800774 }
775 auto code_map = osr_code_map_.find(method);
776 if (code_map != osr_code_map_.end()) {
777 osr_code_map_.erase(code_map);
778 }
779}
780
781// This invalidates old_method. Once this function returns one can no longer use old_method to
782// execute code unless it is fixed up. This fixup will happen later in the process of installing a
783// class redefinition.
784// TODO We should add some info to ArtMethod to note that 'old_method' has been invalidated and
785// shouldn't be used since it is no longer logically in the jit code cache.
786// TODO We should add DCHECKS that validate that the JIT is paused when this method is entered.
787void JitCodeCache::MoveObsoleteMethod(ArtMethod* old_method, ArtMethod* new_method) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000788 // Native methods have no profiling info and need no special handling from the JIT code cache.
789 if (old_method->IsNative()) {
790 return;
791 }
Alex Lightdba61482016-12-21 08:20:29 -0800792 MutexLock mu(Thread::Current(), lock_);
793 // Update ProfilingInfo to the new one and remove it from the old_method.
794 if (old_method->GetProfilingInfo(kRuntimePointerSize) != nullptr) {
795 DCHECK_EQ(old_method->GetProfilingInfo(kRuntimePointerSize)->GetMethod(), old_method);
796 ProfilingInfo* info = old_method->GetProfilingInfo(kRuntimePointerSize);
797 old_method->SetProfilingInfo(nullptr);
798 // Since the JIT should be paused and all threads suspended by the time this is called these
799 // checks should always pass.
800 DCHECK(!info->IsInUseByCompiler());
801 new_method->SetProfilingInfo(info);
802 info->method_ = new_method;
803 }
804 // Update method_code_map_ to point to the new method.
805 for (auto& it : method_code_map_) {
806 if (it.second == old_method) {
807 it.second = new_method;
808 }
809 }
810 // Update osr_code_map_ to point to the new method.
811 auto code_map = osr_code_map_.find(old_method);
812 if (code_map != osr_code_map_.end()) {
813 osr_code_map_.Put(new_method, code_map->second);
814 osr_code_map_.erase(old_method);
815 }
816}
817
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000818size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000819 return used_memory_for_code_;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100820}
821
822size_t JitCodeCache::DataCacheSize() {
823 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000824 return DataCacheSizeLocked();
825}
826
827size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000828 return used_memory_for_data_;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800829}
830
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000831void JitCodeCache::ClearData(Thread* self,
832 uint8_t* stack_map_data,
833 uint8_t* roots_data) {
834 DCHECK_EQ(FromStackMapToRoots(stack_map_data), roots_data);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000835 MutexLock mu(self, lock_);
Nicolas Geoffrayf46501c2016-11-22 13:45:36 +0000836 FreeData(reinterpret_cast<uint8_t*>(roots_data));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000837}
838
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000839size_t JitCodeCache::ReserveData(Thread* self,
840 size_t stack_map_size,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700841 size_t method_info_size,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000842 size_t number_of_roots,
843 ArtMethod* method,
844 uint8_t** stack_map_data,
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700845 uint8_t** method_info_data,
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000846 uint8_t** roots_data) {
Nicolas Geoffray132d8362016-11-16 09:19:42 +0000847 size_t table_size = ComputeRootTableSize(number_of_roots);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700848 size_t size = RoundUp(stack_map_size + method_info_size + table_size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100849 uint8_t* result = nullptr;
850
851 {
852 ScopedThreadSuspension sts(self, kSuspended);
853 MutexLock mu(self, lock_);
854 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000855 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100856 }
857
858 if (result == nullptr) {
859 // Retry.
860 GarbageCollectCache(self);
861 ScopedThreadSuspension sts(self, kSuspended);
862 MutexLock mu(self, lock_);
863 WaitForPotentialCollectionToComplete(self);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +0000864 result = AllocateData(size);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100865 }
866
Nicolas Geoffray933330a2016-03-16 14:20:06 +0000867 MutexLock mu(self, lock_);
868 histogram_stack_map_memory_use_.AddValue(size);
869 if (size > kStackMapSizeLogThreshold) {
870 LOG(INFO) << "JIT allocated "
871 << PrettySize(size)
872 << " for stack maps of "
David Sehr709b0702016-10-13 09:12:37 -0700873 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800874 }
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000875 if (result != nullptr) {
876 *roots_data = result;
877 *stack_map_data = result + table_size;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700878 *method_info_data = *stack_map_data + stack_map_size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000879 FillRootTableLength(*roots_data, number_of_roots);
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000880 return size;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000881 } else {
882 *roots_data = nullptr;
883 *stack_map_data = nullptr;
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700884 *method_info_data = nullptr;
Nicolas Geoffrayed015ac2016-12-15 17:58:48 +0000885 return 0;
Nicolas Geoffrayf4b94422016-12-05 00:10:09 +0000886 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800887}
888
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100889class MarkCodeVisitor FINAL : public StackVisitor {
890 public:
891 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
892 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
893 code_cache_(code_cache_in),
894 bitmap_(code_cache_->GetLiveBitmap()) {}
895
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700896 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100897 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
898 if (method_header == nullptr) {
899 return true;
900 }
901 const void* code = method_header->GetCode();
902 if (code_cache_->ContainsPc(code)) {
903 // Use the atomic set version, as multiple threads are executing this code.
904 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
905 }
906 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800907 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100908
909 private:
910 JitCodeCache* const code_cache_;
911 CodeCacheBitmap* const bitmap_;
912};
913
914class MarkCodeClosure FINAL : public Closure {
915 public:
916 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
917 : code_cache_(code_cache), barrier_(barrier) {}
918
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700919 void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800920 ScopedTrace trace(__PRETTY_FUNCTION__);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100921 DCHECK(thread == Thread::Current() || thread->IsSuspended());
922 MarkCodeVisitor visitor(thread, code_cache_);
923 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000924 if (kIsDebugBuild) {
925 // The stack walking code queries the side instrumentation stack if it
926 // sees an instrumentation exit pc, so the JIT code of methods in that stack
927 // must have been seen. We sanity check this below.
928 for (const instrumentation::InstrumentationStackFrame& frame
929 : *thread->GetInstrumentationStack()) {
930 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
931 // its stack frame, it is not the method owning return_pc_. We just pass null to
932 // LookupMethodHeader: the method is only checked against in debug builds.
933 OatQuickMethodHeader* method_header =
934 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
935 if (method_header != nullptr) {
936 const void* code = method_header->GetCode();
937 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
938 }
939 }
940 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700941 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800942 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100943
944 private:
945 JitCodeCache* const code_cache_;
946 Barrier* const barrier_;
947};
948
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000949void JitCodeCache::NotifyCollectionDone(Thread* self) {
950 collection_in_progress_ = false;
951 lock_cond_.Broadcast(self);
952}
953
954void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
955 size_t per_space_footprint = new_footprint / 2;
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100956 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000957 DCHECK_EQ(per_space_footprint * 2, new_footprint);
958 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
959 {
Orion Hodsondbd05fe2017-08-10 11:41:35 +0100960 ScopedCodeCacheWrite scc(code_map_.get());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000961 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
962 }
963}
964
965bool JitCodeCache::IncreaseCodeCacheCapacity() {
966 if (current_capacity_ == max_capacity_) {
967 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100968 }
969
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000970 // Double the capacity if we're below 1MB, or increase it by 1MB if
971 // we're above.
972 if (current_capacity_ < 1 * MB) {
973 current_capacity_ *= 2;
974 } else {
975 current_capacity_ += 1 * MB;
976 }
977 if (current_capacity_ > max_capacity_) {
978 current_capacity_ = max_capacity_;
979 }
980
Nicolas Geoffray646d6382017-08-09 10:50:00 +0100981 VLOG(jit) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000982
983 SetFootprintLimit(current_capacity_);
984
985 return true;
986}
987
Nicolas Geoffray8d372502016-02-23 13:56:43 +0000988void JitCodeCache::MarkCompiledCodeOnThreadStacks(Thread* self) {
989 Barrier barrier(0);
990 size_t threads_running_checkpoint = 0;
991 MarkCodeClosure closure(this, &barrier);
992 threads_running_checkpoint = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
993 // Now that we have run our checkpoint, move to a suspended state and wait
994 // for other threads to run the checkpoint.
995 ScopedThreadSuspension sts(self, kSuspended);
996 if (threads_running_checkpoint != 0) {
997 barrier.Increment(self, threads_running_checkpoint);
998 }
999}
1000
Nicolas Geoffray35122442016-03-02 12:05:30 +00001001bool JitCodeCache::ShouldDoFullCollection() {
1002 if (current_capacity_ == max_capacity_) {
1003 // Always do a full collection when the code cache is full.
1004 return true;
1005 } else if (current_capacity_ < kReservedCapacity) {
1006 // Always do partial collection when the code cache size is below the reserved
1007 // capacity.
1008 return false;
1009 } else if (last_collection_increased_code_cache_) {
1010 // This time do a full collection.
1011 return true;
1012 } else {
1013 // This time do a partial collection.
1014 return false;
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001015 }
1016}
1017
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001018void JitCodeCache::GarbageCollectCache(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001019 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001020 if (!garbage_collect_code_) {
1021 MutexLock mu(self, lock_);
1022 IncreaseCodeCacheCapacity();
1023 return;
1024 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001025
Nicolas Geoffraya5891e82015-11-06 14:18:27 +00001026 // Wait for an existing collection, or let everyone know we are starting one.
1027 {
1028 ScopedThreadSuspension sts(self, kSuspended);
1029 MutexLock mu(self, lock_);
1030 if (WaitForPotentialCollectionToComplete(self)) {
1031 return;
1032 } else {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001033 number_of_collections_++;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001034 live_bitmap_.reset(CodeCacheBitmap::Create(
1035 "code-cache-bitmap",
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001036 reinterpret_cast<uintptr_t>(code_map_->Begin()),
1037 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001038 collection_in_progress_ = true;
1039 }
1040 }
1041
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001042 TimingLogger logger("JIT code cache timing logger", true, VLOG_IS_ON(jit));
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001043 {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001044 TimingLogger::ScopedTiming st("Code cache collection", &logger);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001045
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001046 bool do_full_collection = false;
1047 {
1048 MutexLock mu(self, lock_);
1049 do_full_collection = ShouldDoFullCollection();
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001050 }
1051
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001052 VLOG(jit) << "Do "
1053 << (do_full_collection ? "full" : "partial")
1054 << " code cache collection, code="
1055 << PrettySize(CodeCacheSize())
1056 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001057
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001058 DoCollection(self, /* collect_profiling_info */ do_full_collection);
1059
Nicolas Geoffray646d6382017-08-09 10:50:00 +01001060 VLOG(jit) << "After code cache collection, code="
1061 << PrettySize(CodeCacheSize())
1062 << ", data=" << PrettySize(DataCacheSize());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001063
1064 {
1065 MutexLock mu(self, lock_);
1066
1067 // Increase the code cache only when we do partial collections.
1068 // TODO: base this strategy on how full the code cache is?
1069 if (do_full_collection) {
1070 last_collection_increased_code_cache_ = false;
1071 } else {
1072 last_collection_increased_code_cache_ = true;
1073 IncreaseCodeCacheCapacity();
Nicolas Geoffray35122442016-03-02 12:05:30 +00001074 }
1075
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001076 bool next_collection_will_be_full = ShouldDoFullCollection();
1077
1078 // Start polling the liveness of compiled code to prepare for the next full collection.
Nicolas Geoffray480d5102016-04-18 12:09:30 +01001079 if (next_collection_will_be_full) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001080 // Save the entry point of methods we have compiled, and update the entry
1081 // point of those methods to the interpreter. If the method is invoked, the
1082 // interpreter will update its entry point to the compiled code and call it.
1083 for (ProfilingInfo* info : profiling_infos_) {
1084 const void* entry_point = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
1085 if (ContainsPc(entry_point)) {
1086 info->SetSavedEntryPoint(entry_point);
Nicolas Geoffray3b1a7f42017-02-22 10:21:00 +00001087 // Don't call Instrumentation::UpdateMethods, as it can check the declaring
1088 // class of the method. We may be concurrently running a GC which makes accessing
1089 // the class unsafe. We know it is OK to bypass the instrumentation as we've just
1090 // checked that the current entry point is JIT compiled code.
1091 info->GetMethod()->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001092 }
1093 }
1094
1095 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
1096 }
1097 live_bitmap_.reset(nullptr);
1098 NotifyCollectionDone(self);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001099 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001100 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001101 Runtime::Current()->GetJit()->AddTimingLogger(logger);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001102}
1103
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001104void JitCodeCache::RemoveUnmarkedCode(Thread* self) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001105 ScopedTrace trace(__FUNCTION__);
Mingyao Yang063fc772016-08-02 11:02:54 -07001106 std::unordered_set<OatQuickMethodHeader*> method_headers;
1107 {
1108 MutexLock mu(self, lock_);
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001109 ScopedCodeCacheWrite scc(code_map_.get());
Mingyao Yang063fc772016-08-02 11:02:54 -07001110 // Iterate over all compiled code and remove entries that are not marked.
1111 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
1112 const void* code_ptr = it->first;
1113 uintptr_t allocation = FromCodeToAllocation(code_ptr);
1114 if (GetLiveBitmap()->Test(allocation)) {
1115 ++it;
1116 } else {
1117 method_headers.insert(OatQuickMethodHeader::FromCodePointer(it->first));
1118 it = method_code_map_.erase(it);
1119 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001120 }
1121 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001122 FreeAllMethodHeaders(method_headers);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001123}
1124
1125void JitCodeCache::DoCollection(Thread* self, bool collect_profiling_info) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001126 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001127 {
1128 MutexLock mu(self, lock_);
1129 if (collect_profiling_info) {
1130 // Clear the profiling info of methods that do not have compiled code as entrypoint.
1131 // Also remove the saved entry point from the ProfilingInfo objects.
1132 for (ProfilingInfo* info : profiling_infos_) {
1133 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001134 if (!ContainsPc(ptr) && !info->IsInUseByCompiler()) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001135 info->GetMethod()->SetProfilingInfo(nullptr);
1136 }
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001137
1138 if (info->GetSavedEntryPoint() != nullptr) {
1139 info->SetSavedEntryPoint(nullptr);
1140 // We are going to move this method back to interpreter. Clear the counter now to
Mathieu Chartierf044c222017-05-31 15:27:54 -07001141 // give it a chance to be hot again.
1142 ClearMethodCounter(info->GetMethod(), /*was_warm*/ true);
Nicolas Geoffrayb9a639d2016-03-22 11:25:20 +00001143 }
Nicolas Geoffray35122442016-03-02 12:05:30 +00001144 }
1145 } else if (kIsDebugBuild) {
1146 // Sanity check that the profiling infos do not have a dangling entry point.
1147 for (ProfilingInfo* info : profiling_infos_) {
1148 DCHECK(info->GetSavedEntryPoint() == nullptr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001149 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001150 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001151
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001152 // Mark compiled code that are entrypoints of ArtMethods. Compiled code that is not
1153 // an entry point is either:
1154 // - an osr compiled code, that will be removed if not in a thread call stack.
1155 // - discarded compiled code, that will be removed if not in a thread call stack.
1156 for (const auto& it : method_code_map_) {
1157 ArtMethod* method = it.second;
1158 const void* code_ptr = it.first;
1159 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1160 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1161 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
1162 }
1163 }
1164
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001165 // Empty osr method map, as osr compiled code will be deleted (except the ones
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001166 // on thread stacks).
1167 osr_code_map_.clear();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001168 }
1169
1170 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
Nicolas Geoffray8d372502016-02-23 13:56:43 +00001171 MarkCompiledCodeOnThreadStacks(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001172
Nicolas Geoffray9abb2972016-03-04 14:32:59 +00001173 // At this point, mutator threads are still running, and entrypoints of methods can
1174 // change. We do know they cannot change to a code cache entry that is not marked,
1175 // therefore we can safely remove those entries.
1176 RemoveUnmarkedCode(self);
Nicolas Geoffraya96917a2016-03-01 22:18:02 +00001177
Nicolas Geoffray35122442016-03-02 12:05:30 +00001178 if (collect_profiling_info) {
1179 MutexLock mu(self, lock_);
1180 // Free all profiling infos of methods not compiled nor being compiled.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001181 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001182 [this] (ProfilingInfo* info) NO_THREAD_SAFETY_ANALYSIS {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001183 const void* ptr = info->GetMethod()->GetEntryPointFromQuickCompiledCode();
Nicolas Geoffray511e41b2016-03-02 17:09:35 +00001184 // We have previously cleared the ProfilingInfo pointer in the ArtMethod in the hope
1185 // that the compiled code would not get revived. As mutator threads run concurrently,
1186 // they may have revived the compiled code, and now we are in the situation where
1187 // a method has compiled code but no ProfilingInfo.
1188 // We make sure compiled methods have a ProfilingInfo object. It is needed for
1189 // code cache collection.
Andreas Gampe542451c2016-07-26 09:02:02 -07001190 if (ContainsPc(ptr) &&
1191 info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001192 info->GetMethod()->SetProfilingInfo(info);
Andreas Gampe542451c2016-07-26 09:02:02 -07001193 } else if (info->GetMethod()->GetProfilingInfo(kRuntimePointerSize) != info) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001194 // No need for this ProfilingInfo object anymore.
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001195 FreeData(reinterpret_cast<uint8_t*>(info));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001196 return true;
1197 }
1198 return false;
1199 });
1200 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray35122442016-03-02 12:05:30 +00001201 DCHECK(CheckLiveCompiledCodeHasProfilingInfo());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001202 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001203}
1204
Nicolas Geoffray35122442016-03-02 12:05:30 +00001205bool JitCodeCache::CheckLiveCompiledCodeHasProfilingInfo() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001206 ScopedTrace trace(__FUNCTION__);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001207 // Check that methods we have compiled do have a ProfilingInfo object. We would
1208 // have memory leaks of compiled code otherwise.
1209 for (const auto& it : method_code_map_) {
1210 ArtMethod* method = it.second;
Andreas Gampe542451c2016-07-26 09:02:02 -07001211 if (method->GetProfilingInfo(kRuntimePointerSize) == nullptr) {
Nicolas Geoffray35122442016-03-02 12:05:30 +00001212 const void* code_ptr = it.first;
1213 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1214 if (method_header->GetEntryPoint() == method->GetEntryPointFromQuickCompiledCode()) {
1215 // If the code is not dead, then we have a problem. Note that this can even
1216 // happen just after a collection, as mutator threads are running in parallel
1217 // and could deoptimize an existing compiled code.
1218 return false;
1219 }
1220 }
1221 }
1222 return true;
1223}
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001224
1225OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001226 static_assert(kRuntimeISA != InstructionSet::kThumb2, "kThumb2 cannot be a runtime ISA");
1227 if (kRuntimeISA == InstructionSet::kArm) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001228 // On Thumb-2, the pc is offset by one.
1229 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001230 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001231 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
1232 return nullptr;
1233 }
1234
1235 MutexLock mu(Thread::Current(), lock_);
1236 if (method_code_map_.empty()) {
1237 return nullptr;
1238 }
1239 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
1240 --it;
1241
1242 const void* code_ptr = it->first;
1243 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
1244 if (!method_header->Contains(pc)) {
1245 return nullptr;
1246 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001247 if (kIsDebugBuild && method != nullptr) {
Alex Light1ebe4fe2017-01-30 14:57:11 -08001248 // When we are walking the stack to redefine classes and creating obsolete methods it is
1249 // possible that we might have updated the method_code_map by making this method obsolete in a
1250 // previous frame. Therefore we should just check that the non-obsolete version of this method
1251 // is the one we expect. We change to the non-obsolete versions in the error message since the
1252 // obsolete version of the method might not be fully initialized yet. This situation can only
1253 // occur when we are in the process of allocating and setting up obsolete methods. Otherwise
Andreas Gampe06c42a52017-07-26 14:17:14 -07001254 // method and it->second should be identical. (See openjdkjvmti/ti_redefine.cc for more
Alex Light1ebe4fe2017-01-30 14:57:11 -08001255 // information.)
1256 DCHECK_EQ(it->second->GetNonObsoleteMethod(), method->GetNonObsoleteMethod())
1257 << ArtMethod::PrettyMethod(method->GetNonObsoleteMethod()) << " "
1258 << ArtMethod::PrettyMethod(it->second->GetNonObsoleteMethod()) << " "
David Sehr709b0702016-10-13 09:12:37 -07001259 << std::hex << pc;
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +00001260 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01001261 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001262}
1263
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001264OatQuickMethodHeader* JitCodeCache::LookupOsrMethodHeader(ArtMethod* method) {
1265 MutexLock mu(Thread::Current(), lock_);
1266 auto it = osr_code_map_.find(method);
1267 if (it == osr_code_map_.end()) {
1268 return nullptr;
1269 }
1270 return OatQuickMethodHeader::FromCodePointer(it->second);
1271}
1272
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001273ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
1274 ArtMethod* method,
1275 const std::vector<uint32_t>& entries,
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001276 bool retry_allocation)
1277 // No thread safety analysis as we are using TryLock/Unlock explicitly.
1278 NO_THREAD_SAFETY_ANALYSIS {
1279 ProfilingInfo* info = nullptr;
1280 if (!retry_allocation) {
1281 // If we are allocating for the interpreter, just try to lock, to avoid
1282 // lock contention with the JIT.
1283 if (lock_.ExclusiveTryLock(self)) {
1284 info = AddProfilingInfoInternal(self, method, entries);
1285 lock_.ExclusiveUnlock(self);
1286 }
1287 } else {
1288 {
1289 MutexLock mu(self, lock_);
1290 info = AddProfilingInfoInternal(self, method, entries);
1291 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001292
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001293 if (info == nullptr) {
1294 GarbageCollectCache(self);
1295 MutexLock mu(self, lock_);
1296 info = AddProfilingInfoInternal(self, method, entries);
1297 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001298 }
1299 return info;
1300}
1301
Nicolas Geoffray1e7da9b2016-03-01 14:11:40 +00001302ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self ATTRIBUTE_UNUSED,
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001303 ArtMethod* method,
1304 const std::vector<uint32_t>& entries) {
1305 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001306 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001307 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001308
1309 // Check whether some other thread has concurrently created it.
Andreas Gampe542451c2016-07-26 09:02:02 -07001310 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001311 if (info != nullptr) {
1312 return info;
1313 }
1314
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001315 uint8_t* data = AllocateData(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001316 if (data == nullptr) {
1317 return nullptr;
1318 }
1319 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +00001320
1321 // Make sure other threads see the data in the profiling info object before the
1322 // store in the ArtMethod's ProfilingInfo pointer.
1323 QuasiAtomic::ThreadFenceRelease();
1324
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001325 method->SetProfilingInfo(info);
1326 profiling_infos_.push_back(info);
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001327 histogram_profiling_info_memory_use_.AddValue(profile_info_size);
Nicolas Geoffray26705e22015-10-28 12:50:11 +00001328 return info;
1329}
1330
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001331// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
1332// is already held.
1333void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
1334 if (code_mspace_ == mspace) {
1335 size_t result = code_end_;
1336 code_end_ += increment;
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001337 return reinterpret_cast<void*>(result + code_map_->Begin());
Nicolas Geoffray0a3be162015-11-18 11:15:22 +00001338 } else {
1339 DCHECK_EQ(data_mspace_, mspace);
1340 size_t result = data_end_;
1341 data_end_ += increment;
1342 return reinterpret_cast<void*>(result + data_map_->Begin());
1343 }
1344}
1345
Calin Juravle99629622016-04-19 16:33:46 +01001346void JitCodeCache::GetProfiledMethods(const std::set<std::string>& dex_base_locations,
Calin Juravle940eb0c2017-01-30 19:30:44 -08001347 std::vector<ProfileMethodInfo>& methods) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001348 ScopedTrace trace(__FUNCTION__);
Calin Juravle31f2c152015-10-23 17:56:15 +01001349 MutexLock mu(Thread::Current(), lock_);
Calin Juravlea39fd982017-05-18 10:15:52 -07001350 uint16_t jit_compile_threshold = Runtime::Current()->GetJITOptions()->GetCompileThreshold();
Calin Juravle99629622016-04-19 16:33:46 +01001351 for (const ProfilingInfo* info : profiling_infos_) {
1352 ArtMethod* method = info->GetMethod();
1353 const DexFile* dex_file = method->GetDexFile();
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001354 const std::string base_location = DexFileLoader::GetBaseLocation(dex_file->GetLocation());
1355 if (!ContainsElement(dex_base_locations, base_location)) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001356 // Skip dex files which are not profiled.
1357 continue;
Calin Juravle31f2c152015-10-23 17:56:15 +01001358 }
Calin Juravle940eb0c2017-01-30 19:30:44 -08001359 std::vector<ProfileMethodInfo::ProfileInlineCache> inline_caches;
Calin Juravlea39fd982017-05-18 10:15:52 -07001360
1361 // If the method didn't reach the compilation threshold don't save the inline caches.
1362 // They might be incomplete and cause unnecessary deoptimizations.
1363 // If the inline cache is empty the compiler will generate a regular invoke virtual/interface.
1364 if (method->GetCounter() < jit_compile_threshold) {
1365 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001366 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravlea39fd982017-05-18 10:15:52 -07001367 continue;
1368 }
1369
Calin Juravle940eb0c2017-01-30 19:30:44 -08001370 for (size_t i = 0; i < info->number_of_inline_caches_; ++i) {
Mathieu Chartierdbddc222017-05-24 12:04:13 -07001371 std::vector<TypeReference> profile_classes;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001372 const InlineCache& cache = info->cache_[i];
Calin Juravle13439f02017-02-21 01:17:21 -08001373 ArtMethod* caller = info->GetMethod();
Calin Juravle589e71e2017-03-03 16:05:05 -08001374 bool is_missing_types = false;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001375 for (size_t k = 0; k < InlineCache::kIndividualCacheSize; k++) {
1376 mirror::Class* cls = cache.classes_[k].Read();
1377 if (cls == nullptr) {
1378 break;
1379 }
Calin Juravle4ca70a32017-02-21 16:22:24 -08001380
Calin Juravle13439f02017-02-21 01:17:21 -08001381 // Check if the receiver is in the boot class path or if it's in the
1382 // same class loader as the caller. If not, skip it, as there is not
1383 // much we can do during AOT.
1384 if (!cls->IsBootStrapClassLoaded() &&
1385 caller->GetClassLoader() != cls->GetClassLoader()) {
1386 is_missing_types = true;
1387 continue;
1388 }
1389
Calin Juravle4ca70a32017-02-21 16:22:24 -08001390 const DexFile* class_dex_file = nullptr;
1391 dex::TypeIndex type_index;
1392
1393 if (cls->GetDexCache() == nullptr) {
1394 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Calin Juravlee21806f2017-02-22 11:49:43 -08001395 // Make a best effort to find the type index in the method's dex file.
1396 // We could search all open dex files but that might turn expensive
1397 // and probably not worth it.
Calin Juravle4ca70a32017-02-21 16:22:24 -08001398 class_dex_file = dex_file;
1399 type_index = cls->FindTypeIndexInOtherDexFile(*dex_file);
1400 } else {
1401 class_dex_file = &(cls->GetDexFile());
1402 type_index = cls->GetDexTypeIndex();
1403 }
1404 if (!type_index.IsValid()) {
1405 // Could be a proxy class or an array for which we couldn't find the type index.
Calin Juravle589e71e2017-03-03 16:05:05 -08001406 is_missing_types = true;
Calin Juravle4ca70a32017-02-21 16:22:24 -08001407 continue;
1408 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001409 if (ContainsElement(dex_base_locations,
1410 DexFileLoader::GetBaseLocation(class_dex_file->GetLocation()))) {
Calin Juravle940eb0c2017-01-30 19:30:44 -08001411 // Only consider classes from the same apk (including multidex).
1412 profile_classes.emplace_back(/*ProfileMethodInfo::ProfileClassReference*/
Calin Juravle4ca70a32017-02-21 16:22:24 -08001413 class_dex_file, type_index);
Calin Juravle589e71e2017-03-03 16:05:05 -08001414 } else {
1415 is_missing_types = true;
Calin Juravle940eb0c2017-01-30 19:30:44 -08001416 }
1417 }
1418 if (!profile_classes.empty()) {
1419 inline_caches.emplace_back(/*ProfileMethodInfo::ProfileInlineCache*/
Calin Juravle589e71e2017-03-03 16:05:05 -08001420 cache.dex_pc_, is_missing_types, profile_classes);
Calin Juravle940eb0c2017-01-30 19:30:44 -08001421 }
1422 }
1423 methods.emplace_back(/*ProfileMethodInfo*/
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -07001424 MethodReference(dex_file, method->GetDexMethodIndex()), inline_caches);
Calin Juravle31f2c152015-10-23 17:56:15 +01001425 }
1426}
1427
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001428uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
1429 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +01001430}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001431
Nicolas Geoffray71cd50f2016-04-14 15:00:33 +01001432bool JitCodeCache::IsOsrCompiled(ArtMethod* method) {
1433 MutexLock mu(Thread::Current(), lock_);
1434 return osr_code_map_.find(method) != osr_code_map_.end();
1435}
1436
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001437bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self, bool osr) {
1438 if (!osr && ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001439 return false;
1440 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001441
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001442 MutexLock mu(self, lock_);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001443 if (osr && (osr_code_map_.find(method) != osr_code_map_.end())) {
1444 return false;
1445 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001446
Andreas Gampe542451c2016-07-26 09:02:02 -07001447 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001448 if (info == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001449 VLOG(jit) << method->PrettyMethod() << " needs a ProfilingInfo to be compiled";
Jeff Hao00286db2017-05-30 16:53:07 -07001450 // Because the counter is not atomic, there are some rare cases where we may not hit the
1451 // threshold for creating the ProfilingInfo. Reset the counter now to "correct" this.
Mathieu Chartierf044c222017-05-31 15:27:54 -07001452 ClearMethodCounter(method, /*was_warm*/ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001453 return false;
1454 }
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001455
buzbee454b3b62016-04-07 14:42:47 -07001456 if (info->IsMethodBeingCompiled(osr)) {
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001457 return false;
1458 }
1459
buzbee454b3b62016-04-07 14:42:47 -07001460 info->SetIsMethodBeingCompiled(true, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001461 return true;
1462}
1463
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001464ProfilingInfo* JitCodeCache::NotifyCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001465 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001466 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001467 if (info != nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001468 if (!info->IncrementInlineUse()) {
1469 // Overflow of inlining uses, just bail.
1470 return nullptr;
1471 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001472 }
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001473 return info;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001474}
1475
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001476void JitCodeCache::DoneCompilerUse(ArtMethod* method, Thread* self) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001477 MutexLock mu(self, lock_);
Andreas Gampe542451c2016-07-26 09:02:02 -07001478 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +00001479 DCHECK(info != nullptr);
1480 info->DecrementInlineUse();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00001481}
1482
buzbee454b3b62016-04-07 14:42:47 -07001483void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED, bool osr) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001484 ProfilingInfo* info = method->GetProfilingInfo(kRuntimePointerSize);
buzbee454b3b62016-04-07 14:42:47 -07001485 DCHECK(info->IsMethodBeingCompiled(osr));
1486 info->SetIsMethodBeingCompiled(false, osr);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001487}
1488
Nicolas Geoffraya25dce92016-01-12 16:41:10 +00001489size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
1490 MutexLock mu(Thread::Current(), lock_);
1491 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
1492}
1493
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001494void JitCodeCache::InvalidateCompiledCodeFor(ArtMethod* method,
1495 const OatQuickMethodHeader* header) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001496 ProfilingInfo* profiling_info = method->GetProfilingInfo(kRuntimePointerSize);
Nicolas Geoffray35122442016-03-02 12:05:30 +00001497 if ((profiling_info != nullptr) &&
1498 (profiling_info->GetSavedEntryPoint() == header->GetEntryPoint())) {
1499 // Prevent future uses of the compiled code.
1500 profiling_info->SetSavedEntryPoint(nullptr);
1501 }
1502
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001503 if (method->GetEntryPointFromQuickCompiledCode() == header->GetEntryPoint()) {
Jeff Hao00286db2017-05-30 16:53:07 -07001504 // The entrypoint is the one to invalidate, so we just update it to the interpreter entry point
Mathieu Chartierf044c222017-05-31 15:27:54 -07001505 // and clear the counter to get the method Jitted again.
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001506 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
1507 method, GetQuickToInterpreterBridge());
Mathieu Chartierf044c222017-05-31 15:27:54 -07001508 ClearMethodCounter(method, /*was_warm*/ profiling_info != nullptr);
Nicolas Geoffrayb88d59e2016-02-17 11:31:49 +00001509 } else {
1510 MutexLock mu(Thread::Current(), lock_);
1511 auto it = osr_code_map_.find(method);
1512 if (it != osr_code_map_.end() && OatQuickMethodHeader::FromCodePointer(it->second) == header) {
1513 // Remove the OSR method, to avoid using it again.
1514 osr_code_map_.erase(it);
1515 }
1516 }
1517}
1518
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001519uint8_t* JitCodeCache::AllocateCode(size_t code_size) {
1520 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
1521 uint8_t* result = reinterpret_cast<uint8_t*>(
1522 mspace_memalign(code_mspace_, alignment, code_size));
1523 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
1524 // Ensure the header ends up at expected instruction alignment.
1525 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(result + header_size), alignment);
1526 used_memory_for_code_ += mspace_usable_size(result);
1527 return result;
1528}
1529
Orion Hodsondbd05fe2017-08-10 11:41:35 +01001530void JitCodeCache::FreeCode(uint8_t* code) {
1531 used_memory_for_code_ -= mspace_usable_size(code);
1532 mspace_free(code_mspace_, code);
Nicolas Geoffray38ea9bd2016-02-19 16:25:57 +00001533}
1534
1535uint8_t* JitCodeCache::AllocateData(size_t data_size) {
1536 void* result = mspace_malloc(data_mspace_, data_size);
1537 used_memory_for_data_ += mspace_usable_size(result);
1538 return reinterpret_cast<uint8_t*>(result);
1539}
1540
1541void JitCodeCache::FreeData(uint8_t* data) {
1542 used_memory_for_data_ -= mspace_usable_size(data);
1543 mspace_free(data_mspace_, data);
1544}
1545
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001546void JitCodeCache::Dump(std::ostream& os) {
1547 MutexLock mu(Thread::Current(), lock_);
1548 os << "Current JIT code cache size: " << PrettySize(used_memory_for_code_) << "\n"
1549 << "Current JIT data cache size: " << PrettySize(used_memory_for_data_) << "\n"
1550 << "Current JIT capacity: " << PrettySize(current_capacity_) << "\n"
1551 << "Current number of JIT code cache entries: " << method_code_map_.size() << "\n"
1552 << "Total number of JIT compilations: " << number_of_compilations_ << "\n"
1553 << "Total number of JIT compilations for on stack replacement: "
1554 << number_of_osr_compilations_ << "\n"
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001555 << "Total number of JIT code cache collections: " << number_of_collections_ << std::endl;
Nicolas Geoffray933330a2016-03-16 14:20:06 +00001556 histogram_stack_map_memory_use_.PrintMemoryUse(os);
1557 histogram_code_memory_use_.PrintMemoryUse(os);
1558 histogram_profiling_info_memory_use_.PrintMemoryUse(os);
Nicolas Geoffraybcd94c82016-03-03 13:23:33 +00001559}
1560
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001561} // namespace jit
1562} // namespace art