blob: eaba01b2ced0b1b6afd4d920bbde9482a75dee9c [file] [log] [blame]
Mingyao Yang063fc772016-08-02 11:02:54 -07001/*
2 * Copyright (C) 2016 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 "cha.h"
18
Andreas Gampe90b936d2017-01-31 08:58:55 -080019#include "art_method-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070020#include "jit/jit.h"
21#include "jit/jit_code_cache.h"
22#include "runtime.h"
23#include "scoped_thread_state_change-inl.h"
24#include "stack.h"
25#include "thread.h"
26#include "thread_list.h"
27#include "thread_pool.h"
28
29namespace art {
30
31void ClassHierarchyAnalysis::AddDependency(ArtMethod* method,
32 ArtMethod* dependent_method,
33 OatQuickMethodHeader* dependent_header) {
34 auto it = cha_dependency_map_.find(method);
35 if (it == cha_dependency_map_.end()) {
36 cha_dependency_map_[method] =
37 new std::vector<std::pair<art::ArtMethod*, art::OatQuickMethodHeader*>>();
38 it = cha_dependency_map_.find(method);
39 } else {
40 DCHECK(it->second != nullptr);
41 }
42 it->second->push_back(std::make_pair(dependent_method, dependent_header));
43}
44
45std::vector<std::pair<ArtMethod*, OatQuickMethodHeader*>>*
46 ClassHierarchyAnalysis::GetDependents(ArtMethod* method) {
47 auto it = cha_dependency_map_.find(method);
48 if (it != cha_dependency_map_.end()) {
49 DCHECK(it->second != nullptr);
50 return it->second;
51 }
52 return nullptr;
53}
54
55void ClassHierarchyAnalysis::RemoveDependencyFor(ArtMethod* method) {
56 auto it = cha_dependency_map_.find(method);
57 if (it != cha_dependency_map_.end()) {
58 auto dependents = it->second;
59 cha_dependency_map_.erase(it);
60 delete dependents;
61 }
62}
63
64void ClassHierarchyAnalysis::RemoveDependentsWithMethodHeaders(
65 const std::unordered_set<OatQuickMethodHeader*>& method_headers) {
66 // Iterate through all entries in the dependency map and remove any entry that
67 // contains one of those in method_headers.
68 for (auto map_it = cha_dependency_map_.begin(); map_it != cha_dependency_map_.end(); ) {
69 auto dependents = map_it->second;
70 for (auto vec_it = dependents->begin(); vec_it != dependents->end(); ) {
71 OatQuickMethodHeader* method_header = vec_it->second;
72 auto it = std::find(method_headers.begin(), method_headers.end(), method_header);
73 if (it != method_headers.end()) {
74 vec_it = dependents->erase(vec_it);
75 } else {
76 vec_it++;
77 }
78 }
79 // Remove the map entry if there are no more dependents.
80 if (dependents->empty()) {
81 map_it = cha_dependency_map_.erase(map_it);
82 delete dependents;
83 } else {
84 map_it++;
85 }
86 }
87}
88
89// This stack visitor walks the stack and for compiled code with certain method
90// headers, sets the should_deoptimize flag on stack to 1.
91// TODO: also set the register value to 1 when should_deoptimize is allocated in
92// a register.
93class CHAStackVisitor FINAL : public StackVisitor {
94 public:
95 CHAStackVisitor(Thread* thread_in,
96 Context* context,
97 const std::unordered_set<OatQuickMethodHeader*>& method_headers)
98 : StackVisitor(thread_in, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
99 method_headers_(method_headers) {
100 }
101
102 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
103 ArtMethod* method = GetMethod();
Mingyao Yang7b9a83f2016-12-13 12:28:31 -0800104 // Avoid types of methods that do not have an oat quick method header.
105 if (method == nullptr ||
106 method->IsRuntimeMethod() ||
107 method->IsNative() ||
108 method->IsProxyMethod()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700109 return true;
110 }
111 if (GetCurrentQuickFrame() == nullptr) {
112 // Not compiled code.
113 return true;
114 }
115 // Method may have multiple versions of compiled code. Check
116 // the method header to see if it has should_deoptimize flag.
117 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
Mingyao Yang7b9a83f2016-12-13 12:28:31 -0800118 DCHECK(method_header != nullptr);
Mingyao Yang063fc772016-08-02 11:02:54 -0700119 if (!method_header->HasShouldDeoptimizeFlag()) {
120 // This compiled version doesn't have should_deoptimize flag. Skip.
121 return true;
122 }
123 auto it = std::find(method_headers_.begin(), method_headers_.end(), method_header);
124 if (it == method_headers_.end()) {
125 // Not in the list of method headers that should be deoptimized.
126 return true;
127 }
128
129 // The compiled code on stack is not valid anymore. Need to deoptimize.
130 SetShouldDeoptimizeFlag();
131
132 return true;
133 }
134
135 private:
136 void SetShouldDeoptimizeFlag() REQUIRES_SHARED(Locks::mutator_lock_) {
137 QuickMethodFrameInfo frame_info = GetCurrentQuickFrameInfo();
138 size_t frame_size = frame_info.FrameSizeInBytes();
139 uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
140 size_t core_spill_size = POPCOUNT(frame_info.CoreSpillMask()) *
141 GetBytesPerGprSpillLocation(kRuntimeISA);
142 size_t fpu_spill_size = POPCOUNT(frame_info.FpSpillMask()) *
143 GetBytesPerFprSpillLocation(kRuntimeISA);
144 size_t offset = frame_size - core_spill_size - fpu_spill_size - kShouldDeoptimizeFlagSize;
145 uint8_t* should_deoptimize_addr = sp + offset;
146 // Set deoptimization flag to 1.
147 DCHECK(*should_deoptimize_addr == 0 || *should_deoptimize_addr == 1);
148 *should_deoptimize_addr = 1;
149 }
150
151 // Set of method headers for compiled code that should be deoptimized.
152 const std::unordered_set<OatQuickMethodHeader*>& method_headers_;
153
154 DISALLOW_COPY_AND_ASSIGN(CHAStackVisitor);
155};
156
157class CHACheckpoint FINAL : public Closure {
158 public:
159 explicit CHACheckpoint(const std::unordered_set<OatQuickMethodHeader*>& method_headers)
160 : barrier_(0),
161 method_headers_(method_headers) {}
162
163 void Run(Thread* thread) OVERRIDE {
164 // Note thread and self may not be equal if thread was already suspended at
165 // the point of the request.
166 Thread* self = Thread::Current();
167 ScopedObjectAccess soa(self);
168 CHAStackVisitor visitor(thread, nullptr, method_headers_);
169 visitor.WalkStack();
170 barrier_.Pass(self);
171 }
172
173 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
174 Thread* self = Thread::Current();
175 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
176 barrier_.Increment(self, threads_running_checkpoint);
177 }
178
179 private:
180 // The barrier to be passed through and for the requestor to wait upon.
181 Barrier barrier_;
182 // List of method headers for invalidated compiled code.
183 const std::unordered_set<OatQuickMethodHeader*>& method_headers_;
184
185 DISALLOW_COPY_AND_ASSIGN(CHACheckpoint);
186};
187
188void ClassHierarchyAnalysis::VerifyNonSingleImplementation(mirror::Class* verify_class,
Mingyao Yange8fcd012017-01-20 10:43:30 -0800189 uint16_t verify_index,
190 ArtMethod* excluded_method) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700191 // Grab cha_lock_ to make sure all single-implementation updates are seen.
192 PointerSize image_pointer_size =
193 Runtime::Current()->GetClassLinker()->GetImagePointerSize();
194 MutexLock cha_mu(Thread::Current(), *Locks::cha_lock_);
195 while (verify_class != nullptr) {
196 if (verify_index >= verify_class->GetVTableLength()) {
197 return;
198 }
199 ArtMethod* verify_method = verify_class->GetVTableEntry(verify_index, image_pointer_size);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800200 if (verify_method != excluded_method) {
201 DCHECK(!verify_method->HasSingleImplementation())
202 << "class: " << verify_class->PrettyClass()
Mingyao Yang37c8e5c2017-02-10 11:25:05 -0800203 << " verify_method: " << verify_method->PrettyMethod(true)
204 << " excluded_method: " << excluded_method->PrettyMethod(true);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800205 if (verify_method->IsAbstract()) {
206 DCHECK(verify_method->GetSingleImplementation(image_pointer_size) == nullptr);
207 }
208 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700209 verify_class = verify_class->GetSuperClass();
210 }
211}
212
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000213void ClassHierarchyAnalysis::CheckSingleImplementationInfo(
Mingyao Yang063fc772016-08-02 11:02:54 -0700214 Handle<mirror::Class> klass,
215 ArtMethod* virtual_method,
216 ArtMethod* method_in_super,
Mingyao Yange8fcd012017-01-20 10:43:30 -0800217 std::unordered_set<ArtMethod*>& invalidated_single_impl_methods,
218 PointerSize pointer_size) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700219 // TODO: if klass is not instantiable, virtual_method isn't invocable yet so
220 // even if it overrides, it doesn't invalidate single-implementation
221 // assumption.
222
Mingyao Yange8fcd012017-01-20 10:43:30 -0800223 DCHECK((virtual_method != method_in_super) || virtual_method->IsAbstract());
Mingyao Yang063fc772016-08-02 11:02:54 -0700224 DCHECK(method_in_super->GetDeclaringClass()->IsResolved()) << "class isn't resolved";
225 // If virtual_method doesn't come from a default interface method, it should
226 // be supplied by klass.
Mingyao Yange8fcd012017-01-20 10:43:30 -0800227 DCHECK(virtual_method == method_in_super ||
228 virtual_method->IsCopied() ||
Mingyao Yang063fc772016-08-02 11:02:54 -0700229 virtual_method->GetDeclaringClass() == klass.Get());
230
Mingyao Yange8fcd012017-01-20 10:43:30 -0800231 // To make updating single-implementation flags simple, we always maintain the following
232 // invariant:
233 // Say all virtual methods in the same vtable slot, starting from the bottom child class
234 // to super classes, is a sequence of unique methods m3, m2, m1, ... (after removing duplicate
235 // methods for inherited methods).
236 // For example for the following class hierarchy,
237 // class A { void m() { ... } }
238 // class B extends A { void m() { ... } }
239 // class C extends B {}
240 // class D extends C { void m() { ... } }
241 // the sequence is D.m(), B.m(), A.m().
242 // The single-implementation status for that sequence of methods begin with one or two true's,
243 // then become all falses. The only case where two true's are possible is for one abstract
244 // method m and one non-abstract method mImpl that overrides method m.
245 // With the invariant, when linking in a new class, we only need to at most update one or
246 // two methods in the sequence for their single-implementation status, in order to maintain
247 // the invariant.
248
Mingyao Yang063fc772016-08-02 11:02:54 -0700249 if (!method_in_super->HasSingleImplementation()) {
250 // method_in_super already has multiple implementations. All methods in the
251 // same vtable slots in its super classes should have
252 // non-single-implementation already.
253 if (kIsDebugBuild) {
254 VerifyNonSingleImplementation(klass->GetSuperClass()->GetSuperClass(),
Mingyao Yange8fcd012017-01-20 10:43:30 -0800255 method_in_super->GetMethodIndex(),
256 nullptr /* excluded_method */);
Mingyao Yang063fc772016-08-02 11:02:54 -0700257 }
258 return;
259 }
260
Mingyao Yange8fcd012017-01-20 10:43:30 -0800261 uint16_t method_index = method_in_super->GetMethodIndex();
262 if (method_in_super->IsAbstract()) {
263 if (kIsDebugBuild) {
264 // An abstract method should have made all methods in the same vtable
265 // slot above it in the class hierarchy having non-single-implementation.
266 mirror::Class* super_super = klass->GetSuperClass()->GetSuperClass();
267 VerifyNonSingleImplementation(super_super,
268 method_index,
269 method_in_super);
270 }
271
272 if (virtual_method->IsAbstract()) {
273 // SUPER: abstract, VIRTUAL: abstract.
274 if (method_in_super == virtual_method) {
275 DCHECK(klass->IsInstantiable());
276 // An instantiable subclass hasn't provided a concrete implementation of
277 // the abstract method. Invoking method_in_super may throw AbstractMethodError.
278 // This is an uncommon case, so we simply treat method_in_super as not
279 // having single-implementation.
280 invalidated_single_impl_methods.insert(method_in_super);
281 return;
282 } else {
283 // One abstract method overrides another abstract method. This is an uncommon
284 // case. We simply treat method_in_super as not having single-implementation.
285 invalidated_single_impl_methods.insert(method_in_super);
286 return;
287 }
288 } else {
289 // SUPER: abstract, VIRTUAL: non-abstract.
290 // A non-abstract method overrides an abstract method.
291 if (method_in_super->GetSingleImplementation(pointer_size) == nullptr) {
292 // Abstract method_in_super has no implementation yet.
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000293 // We need to grab cha_lock_ for further checking/updating due to possible
294 // races.
Mingyao Yange8fcd012017-01-20 10:43:30 -0800295 MutexLock cha_mu(Thread::Current(), *Locks::cha_lock_);
296 if (!method_in_super->HasSingleImplementation()) {
297 return;
298 }
299 if (method_in_super->GetSingleImplementation(pointer_size) == nullptr) {
300 // virtual_method becomes the first implementation for method_in_super.
301 method_in_super->SetSingleImplementation(virtual_method, pointer_size);
302 // Keep method_in_super's single-implementation status.
303 return;
304 }
305 // Fall through to invalidate method_in_super's single-implementation status.
306 }
307 // Abstract method_in_super already got one implementation.
308 // Invalidate method_in_super's single-implementation status.
309 invalidated_single_impl_methods.insert(method_in_super);
310 return;
311 }
312 } else {
313 if (virtual_method->IsAbstract()) {
314 // SUPER: non-abstract, VIRTUAL: abstract.
315 // An abstract method overrides a non-abstract method. This is an uncommon
316 // case, we simply treat both methods as not having single-implementation.
317 invalidated_single_impl_methods.insert(virtual_method);
318 // Fall-through to handle invalidating method_in_super of its
319 // single-implementation status.
320 }
321
322 // SUPER: non-abstract, VIRTUAL: non-abstract/abstract(fall-through from previous if).
323 // Invalidate method_in_super's single-implementation status.
324 invalidated_single_impl_methods.insert(method_in_super);
325
326 // method_in_super might be the single-implementation of another abstract method,
327 // which should be also invalidated of its single-implementation status.
328 mirror::Class* super_super = klass->GetSuperClass()->GetSuperClass();
329 while (super_super != nullptr &&
330 method_index < super_super->GetVTableLength()) {
331 ArtMethod* method_in_super_super = super_super->GetVTableEntry(method_index, pointer_size);
332 if (method_in_super_super != method_in_super) {
333 if (method_in_super_super->IsAbstract()) {
334 if (method_in_super_super->HasSingleImplementation()) {
335 // Invalidate method_in_super's single-implementation status.
336 invalidated_single_impl_methods.insert(method_in_super_super);
337 // No need to further traverse up the class hierarchy since if there
338 // are cases that one abstract method overrides another method, we
339 // should have made that method having non-single-implementation already.
340 } else {
341 // method_in_super_super is already non-single-implementation.
342 // No need to further traverse up the class hierarchy.
343 }
344 } else {
345 DCHECK(!method_in_super_super->HasSingleImplementation());
346 // No need to further traverse up the class hierarchy since two non-abstract
347 // methods (method_in_super and method_in_super_super) should have set all
348 // other methods (abstract or not) in the vtable slot to be non-single-implementation.
349 }
350
351 if (kIsDebugBuild) {
352 VerifyNonSingleImplementation(super_super->GetSuperClass(),
353 method_index,
354 method_in_super_super);
355 }
356 // No need to go any further.
357 return;
358 } else {
359 super_super = super_super->GetSuperClass();
360 }
361 }
362 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700363}
364
365void ClassHierarchyAnalysis::InitSingleImplementationFlag(Handle<mirror::Class> klass,
Mingyao Yange8fcd012017-01-20 10:43:30 -0800366 ArtMethod* method,
367 PointerSize pointer_size) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700368 DCHECK(method->IsCopied() || method->GetDeclaringClass() == klass.Get());
369 if (klass->IsFinal() || method->IsFinal()) {
370 // Final classes or methods do not need CHA for devirtualization.
371 // This frees up modifier bits for intrinsics which currently are only
372 // used for static methods or methods of final classes.
373 return;
374 }
Mingyao Yang37c8e5c2017-02-10 11:25:05 -0800375 if (method->IsAbstract()) {
376 // single-implementation of abstract method shares the same field
377 // that's used for JNI function of native method. It's fine since a method
378 // cannot be both abstract and native.
379 DCHECK(!method->IsNative()) << "Abstract method cannot be native";
380
Mingyao Yange8fcd012017-01-20 10:43:30 -0800381 if (method->GetDeclaringClass()->IsInstantiable()) {
382 // Rare case, but we do accept it (such as 800-smali/smali/b_26143249.smali).
383 // Do not attempt to devirtualize it.
384 method->SetHasSingleImplementation(false);
385 } else {
386 // Abstract method starts with single-implementation flag set and null
387 // implementation method.
388 method->SetHasSingleImplementation(true);
389 DCHECK(method->GetSingleImplementation(pointer_size) == nullptr);
390 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700391 } else {
392 method->SetHasSingleImplementation(true);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800393 // Single implementation of non-abstract method is itself.
394 DCHECK_EQ(method->GetSingleImplementation(pointer_size), method);
Mingyao Yang063fc772016-08-02 11:02:54 -0700395 }
396}
397
398void ClassHierarchyAnalysis::UpdateAfterLoadingOf(Handle<mirror::Class> klass) {
399 if (klass->IsInterface()) {
400 return;
401 }
402 mirror::Class* super_class = klass->GetSuperClass();
403 if (super_class == nullptr) {
404 return;
405 }
406
407 // Keeps track of all methods whose single-implementation assumption
408 // is invalidated by linking `klass`.
409 std::unordered_set<ArtMethod*> invalidated_single_impl_methods;
410
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000411 PointerSize image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Mingyao Yang063fc772016-08-02 11:02:54 -0700412 // Do an entry-by-entry comparison of vtable contents with super's vtable.
413 for (int32_t i = 0; i < super_class->GetVTableLength(); ++i) {
414 ArtMethod* method = klass->GetVTableEntry(i, image_pointer_size);
415 ArtMethod* method_in_super = super_class->GetVTableEntry(i, image_pointer_size);
416 if (method == method_in_super) {
417 // vtable slot entry is inherited from super class.
Mingyao Yange8fcd012017-01-20 10:43:30 -0800418 if (method->IsAbstract() && klass->IsInstantiable()) {
419 // An instantiable class that inherits an abstract method is treated as
420 // supplying an implementation that throws AbstractMethodError.
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000421 CheckSingleImplementationInfo(klass,
422 method,
423 method_in_super,
424 invalidated_single_impl_methods,
425 image_pointer_size);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800426 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700427 continue;
428 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800429 InitSingleImplementationFlag(klass, method, image_pointer_size);
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000430 CheckSingleImplementationInfo(klass,
431 method,
432 method_in_super,
433 invalidated_single_impl_methods,
434 image_pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700435 }
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000436
Mingyao Yang063fc772016-08-02 11:02:54 -0700437 // For new virtual methods that don't override.
438 for (int32_t i = super_class->GetVTableLength(); i < klass->GetVTableLength(); ++i) {
439 ArtMethod* method = klass->GetVTableEntry(i, image_pointer_size);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800440 InitSingleImplementationFlag(klass, method, image_pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700441 }
442
Nicolas Geoffray43e99be2017-03-15 06:28:52 +0000443 Runtime* const runtime = Runtime::Current();
Mingyao Yang063fc772016-08-02 11:02:54 -0700444 if (!invalidated_single_impl_methods.empty()) {
445 Thread *self = Thread::Current();
446 // Method headers for compiled code to be invalidated.
447 std::unordered_set<OatQuickMethodHeader*> dependent_method_headers;
448
449 {
450 // We do this under cha_lock_. Committing code also grabs this lock to
451 // make sure the code is only committed when all single-implementation
452 // assumptions are still true.
453 MutexLock cha_mu(self, *Locks::cha_lock_);
454 // Invalidate compiled methods that assume some virtual calls have only
455 // single implementations.
456 for (ArtMethod* invalidated : invalidated_single_impl_methods) {
457 if (!invalidated->HasSingleImplementation()) {
458 // It might have been invalidated already when other class linking is
459 // going on.
460 continue;
461 }
462 invalidated->SetHasSingleImplementation(false);
Mingyao Yange8fcd012017-01-20 10:43:30 -0800463 if (invalidated->IsAbstract()) {
464 // Clear the single implementation method.
465 invalidated->SetSingleImplementation(nullptr, image_pointer_size);
466 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700467
468 if (runtime->IsAotCompiler()) {
469 // No need to invalidate any compiled code as the AotCompiler doesn't
470 // run any code.
471 continue;
472 }
473
474 // Invalidate all dependents.
475 auto dependents = GetDependents(invalidated);
476 if (dependents == nullptr) {
477 continue;
478 }
479 for (const auto& dependent : *dependents) {
480 ArtMethod* method = dependent.first;;
481 OatQuickMethodHeader* method_header = dependent.second;
482 VLOG(class_linker) << "CHA invalidated compiled code for " << method->PrettyMethod();
483 DCHECK(runtime->UseJitCompilation());
484 runtime->GetJit()->GetCodeCache()->InvalidateCompiledCodeFor(
485 method, method_header);
486 dependent_method_headers.insert(method_header);
487 }
488 RemoveDependencyFor(invalidated);
489 }
490 }
491
492 if (dependent_method_headers.empty()) {
493 return;
494 }
495 // Deoptimze compiled code on stack that should have been invalidated.
496 CHACheckpoint checkpoint(dependent_method_headers);
497 size_t threads_running_checkpoint = runtime->GetThreadList()->RunCheckpoint(&checkpoint);
498 if (threads_running_checkpoint != 0) {
499 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
500 }
501 }
502}
503
504} // namespace art