1 /*
2 * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/ciArrayKlass.hpp"
26 #include "ci/ciEnv.hpp"
27 #include "ci/ciKlass.hpp"
28 #include "ci/ciMethod.hpp"
29 #include "classfile/javaClasses.inline.hpp"
30 #include "classfile/vmClasses.hpp"
31 #include "code/dependencies.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "compiler/compileTask.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "oops/klass.hpp"
37 #include "oops/method.inline.hpp"
38 #include "oops/objArrayKlass.hpp"
39 #include "oops/oop.inline.hpp"
40 #include "runtime/flags/flagSetting.hpp"
41 #include "runtime/handles.inline.hpp"
42 #include "runtime/javaThread.inline.hpp"
43 #include "runtime/jniHandles.inline.hpp"
44 #include "runtime/mutexLocker.hpp"
45 #include "runtime/perfData.hpp"
46 #include "runtime/vmThread.hpp"
47 #include "utilities/copy.hpp"
48
49
50 #ifdef ASSERT
51 static bool must_be_in_vm() {
52 Thread* thread = Thread::current();
53 if (thread->is_Java_thread()) {
54 return JavaThread::cast(thread)->thread_state() == _thread_in_vm;
55 } else {
56 return true; // Could be VMThread or GC thread
57 }
58 }
59 #endif //ASSERT
60
61 bool Dependencies::_verify_in_progress = false; // don't -Xlog:dependencies
62
63 void Dependencies::initialize(ciEnv* env) {
64 Arena* arena = env->arena();
65 _oop_recorder = env->oop_recorder();
66 _log = env->log();
67 _dep_seen = new(arena) GrowableArray<int>(arena, 500, 0, 0);
68 #if INCLUDE_JVMCI
69 _using_dep_values = false;
70 #endif
71 DEBUG_ONLY(_deps[end_marker] = nullptr);
72 for (int i = (int)FIRST_TYPE; i < (int)TYPE_LIMIT; i++) {
73 _deps[i] = new(arena) GrowableArray<ciBaseObject*>(arena, 10, 0, nullptr);
74 }
75 _content_bytes = nullptr;
76 _size_in_bytes = (size_t)-1;
77
78 assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT), "sanity");
79 }
80
81 void Dependencies::assert_evol_method(ciMethod* m) {
82 assert_common_1(evol_method, m);
83 }
84
85 void Dependencies::assert_mismatch_calling_convention(ciMethod* m) {
86 assert_common_1(mismatch_calling_convention, m);
87 }
88
89 void Dependencies::assert_leaf_type(ciKlass* ctxk) {
90 if (ctxk->is_array_klass()) {
91 // As a special case, support this assertion on an array type,
92 // which reduces to an assertion on its element type.
93 // Note that this cannot be done with assertions that
94 // relate to concreteness or abstractness.
95 ciType* elemt = ctxk->as_array_klass()->base_element_type();
96 if (!elemt->is_instance_klass()) return; // Ex: int[][]
97 ctxk = elemt->as_instance_klass();
98 //if (ctxk->is_final()) return; // Ex: String[][]
99 }
100 check_ctxk(ctxk);
101 assert_common_1(leaf_type, ctxk);
102 }
103
104 void Dependencies::assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck) {
105 check_ctxk_abstract(ctxk);
106 assert_common_2(abstract_with_unique_concrete_subtype, ctxk, conck);
107 }
108
109 void Dependencies::assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm) {
110 check_ctxk(ctxk);
111 check_unique_method(ctxk, uniqm);
112 assert_common_2(unique_concrete_method_2, ctxk, uniqm);
113 }
114
115 void Dependencies::assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm, ciKlass* resolved_klass, ciMethod* resolved_method) {
116 check_ctxk(ctxk);
117 check_unique_method(ctxk, uniqm);
118 assert_common_4(unique_concrete_method_4, ctxk, uniqm, resolved_klass, resolved_method);
119 }
120
121 void Dependencies::assert_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk) {
122 check_ctxk(ctxk);
123 check_unique_implementor(ctxk, uniqk);
124 assert_common_2(unique_implementor, ctxk, uniqk);
125 }
126
127 void Dependencies::assert_has_no_finalizable_subclasses(ciKlass* ctxk) {
128 check_ctxk(ctxk);
129 assert_common_1(no_finalizable_subclasses, ctxk);
130 }
131
132 void Dependencies::assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle) {
133 assert_common_2(call_site_target_value, call_site, method_handle);
134 }
135
136 #if INCLUDE_JVMCI
137
138 Dependencies::Dependencies(Arena* arena, OopRecorder* oop_recorder, CompileLog* log) {
139 _oop_recorder = oop_recorder;
140 _log = log;
141 _dep_seen = new(arena) GrowableArray<int>(arena, 500, 0, 0);
142 _using_dep_values = true;
143 DEBUG_ONLY(_dep_values[end_marker] = nullptr);
144 for (int i = (int)FIRST_TYPE; i < (int)TYPE_LIMIT; i++) {
145 _dep_values[i] = new(arena) GrowableArray<DepValue>(arena, 10, 0, DepValue());
146 }
147 _content_bytes = nullptr;
148 _size_in_bytes = (size_t)-1;
149
150 assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT), "sanity");
151 }
152
153 void Dependencies::assert_evol_method(Method* m) {
154 assert_common_1(evol_method, DepValue(_oop_recorder, m));
155 }
156
157 void Dependencies::assert_has_no_finalizable_subclasses(Klass* ctxk) {
158 check_ctxk(ctxk);
159 assert_common_1(no_finalizable_subclasses, DepValue(_oop_recorder, ctxk));
160 }
161
162 void Dependencies::assert_leaf_type(Klass* ctxk) {
163 if (ctxk->is_array_klass()) {
164 // As a special case, support this assertion on an array type,
165 // which reduces to an assertion on its element type.
166 // Note that this cannot be done with assertions that
167 // relate to concreteness or abstractness.
168 BasicType elemt = ArrayKlass::cast(ctxk)->element_type();
169 if (is_java_primitive(elemt)) return; // Ex: int[][]
170 ctxk = ObjArrayKlass::cast(ctxk)->bottom_klass();
171 //if (ctxk->is_final()) return; // Ex: String[][]
172 }
173 check_ctxk(ctxk);
174 assert_common_1(leaf_type, DepValue(_oop_recorder, ctxk));
175 }
176
177 void Dependencies::assert_abstract_with_unique_concrete_subtype(Klass* ctxk, Klass* conck) {
178 check_ctxk_abstract(ctxk);
179 DepValue ctxk_dv(_oop_recorder, ctxk);
180 DepValue conck_dv(_oop_recorder, conck, &ctxk_dv);
181 assert_common_2(abstract_with_unique_concrete_subtype, ctxk_dv, conck_dv);
182 }
183
184 void Dependencies::assert_unique_implementor(InstanceKlass* ctxk, InstanceKlass* uniqk) {
185 check_ctxk(ctxk);
186 assert(ctxk->is_interface(), "not an interface");
187 assert(ctxk->implementor() == uniqk, "not a unique implementor");
188 assert_common_2(unique_implementor, DepValue(_oop_recorder, ctxk), DepValue(_oop_recorder, uniqk));
189 }
190
191 void Dependencies::assert_unique_concrete_method(Klass* ctxk, Method* uniqm) {
192 check_ctxk(ctxk);
193 check_unique_method(ctxk, uniqm);
194 assert_common_2(unique_concrete_method_2, DepValue(_oop_recorder, ctxk), DepValue(_oop_recorder, uniqm));
195 }
196
197 void Dependencies::assert_call_site_target_value(oop call_site, oop method_handle) {
198 assert_common_2(call_site_target_value, DepValue(_oop_recorder, JNIHandles::make_local(call_site)), DepValue(_oop_recorder, JNIHandles::make_local(method_handle)));
199 }
200
201 #endif // INCLUDE_JVMCI
202
203
204 // Helper function. If we are adding a new dep. under ctxk2,
205 // try to find an old dep. under a broader* ctxk1. If there is
206 //
207 bool Dependencies::maybe_merge_ctxk(GrowableArray<ciBaseObject*>* deps,
208 int ctxk_i, ciKlass* ctxk2) {
209 ciKlass* ctxk1 = deps->at(ctxk_i)->as_metadata()->as_klass();
210 if (ctxk2->is_subtype_of(ctxk1)) {
211 return true; // success, and no need to change
212 } else if (ctxk1->is_subtype_of(ctxk2)) {
213 // new context class fully subsumes previous one
214 deps->at_put(ctxk_i, ctxk2);
215 return true;
216 } else {
217 return false;
218 }
219 }
220
221 void Dependencies::assert_common_1(DepType dept, ciBaseObject* x) {
222 assert(dep_args(dept) == 1, "sanity");
223 log_dependency(dept, x);
224 GrowableArray<ciBaseObject*>* deps = _deps[dept];
225
226 // see if the same (or a similar) dep is already recorded
227 if (note_dep_seen(dept, x)) {
228 assert(deps->find(x) >= 0, "sanity");
229 } else {
230 deps->append(x);
231 }
232 }
233
234 void Dependencies::assert_common_2(DepType dept,
235 ciBaseObject* x0, ciBaseObject* x1) {
236 assert(dep_args(dept) == 2, "sanity");
237 log_dependency(dept, x0, x1);
238 GrowableArray<ciBaseObject*>* deps = _deps[dept];
239
240 // see if the same (or a similar) dep is already recorded
241 bool has_ctxk = has_explicit_context_arg(dept);
242 if (has_ctxk) {
243 assert(dep_context_arg(dept) == 0, "sanity");
244 if (note_dep_seen(dept, x1)) {
245 // look in this bucket for redundant assertions
246 const int stride = 2;
247 for (int i = deps->length(); (i -= stride) >= 0; ) {
248 ciBaseObject* y1 = deps->at(i+1);
249 if (x1 == y1) { // same subject; check the context
250 if (maybe_merge_ctxk(deps, i+0, x0->as_metadata()->as_klass())) {
251 return;
252 }
253 }
254 }
255 }
256 } else {
257 bool dep_seen_x0 = note_dep_seen(dept, x0); // records x0 for future queries
258 bool dep_seen_x1 = note_dep_seen(dept, x1); // records x1 for future queries
259 if (dep_seen_x0 && dep_seen_x1) {
260 // look in this bucket for redundant assertions
261 const int stride = 2;
262 for (int i = deps->length(); (i -= stride) >= 0; ) {
263 ciBaseObject* y0 = deps->at(i+0);
264 ciBaseObject* y1 = deps->at(i+1);
265 if (x0 == y0 && x1 == y1) {
266 return;
267 }
268 }
269 }
270 }
271
272 // append the assertion in the correct bucket:
273 deps->append(x0);
274 deps->append(x1);
275 }
276
277 void Dependencies::assert_common_4(DepType dept,
278 ciKlass* ctxk, ciBaseObject* x1, ciBaseObject* x2, ciBaseObject* x3) {
279 assert(has_explicit_context_arg(dept), "sanity");
280 assert(dep_context_arg(dept) == 0, "sanity");
281 assert(dep_args(dept) == 4, "sanity");
282 log_dependency(dept, ctxk, x1, x2, x3);
283 GrowableArray<ciBaseObject*>* deps = _deps[dept];
284
285 // see if the same (or a similar) dep is already recorded
286 bool dep_seen_x1 = note_dep_seen(dept, x1); // records x1 for future queries
287 bool dep_seen_x2 = note_dep_seen(dept, x2); // records x2 for future queries
288 bool dep_seen_x3 = note_dep_seen(dept, x3); // records x3 for future queries
289 if (dep_seen_x1 && dep_seen_x2 && dep_seen_x3) {
290 // look in this bucket for redundant assertions
291 const int stride = 4;
292 for (int i = deps->length(); (i -= stride) >= 0; ) {
293 ciBaseObject* y1 = deps->at(i+1);
294 ciBaseObject* y2 = deps->at(i+2);
295 ciBaseObject* y3 = deps->at(i+3);
296 if (x1 == y1 && x2 == y2 && x3 == y3) { // same subjects; check the context
297 if (maybe_merge_ctxk(deps, i+0, ctxk)) {
298 return;
299 }
300 }
301 }
302 }
303 // append the assertion in the correct bucket:
304 deps->append(ctxk);
305 deps->append(x1);
306 deps->append(x2);
307 deps->append(x3);
308 }
309
310 #if INCLUDE_JVMCI
311 bool Dependencies::maybe_merge_ctxk(GrowableArray<DepValue>* deps,
312 int ctxk_i, DepValue ctxk2_dv) {
313 Klass* ctxk1 = deps->at(ctxk_i).as_klass(_oop_recorder);
314 Klass* ctxk2 = ctxk2_dv.as_klass(_oop_recorder);
315 if (ctxk2->is_subtype_of(ctxk1)) {
316 return true; // success, and no need to change
317 } else if (ctxk1->is_subtype_of(ctxk2)) {
318 // new context class fully subsumes previous one
319 deps->at_put(ctxk_i, ctxk2_dv);
320 return true;
321 } else {
322 return false;
323 }
324 }
325
326 void Dependencies::assert_common_1(DepType dept, DepValue x) {
327 assert(dep_args(dept) == 1, "sanity");
328 //log_dependency(dept, x);
329 GrowableArray<DepValue>* deps = _dep_values[dept];
330
331 // see if the same (or a similar) dep is already recorded
332 if (note_dep_seen(dept, x)) {
333 assert(deps->find(x) >= 0, "sanity");
334 } else {
335 deps->append(x);
336 }
337 }
338
339 void Dependencies::assert_common_2(DepType dept,
340 DepValue x0, DepValue x1) {
341 assert(dep_args(dept) == 2, "sanity");
342 //log_dependency(dept, x0, x1);
343 GrowableArray<DepValue>* deps = _dep_values[dept];
344
345 // see if the same (or a similar) dep is already recorded
346 bool has_ctxk = has_explicit_context_arg(dept);
347 if (has_ctxk) {
348 assert(dep_context_arg(dept) == 0, "sanity");
349 if (note_dep_seen(dept, x1)) {
350 // look in this bucket for redundant assertions
351 const int stride = 2;
352 for (int i = deps->length(); (i -= stride) >= 0; ) {
353 DepValue y1 = deps->at(i+1);
354 if (x1 == y1) { // same subject; check the context
355 if (maybe_merge_ctxk(deps, i+0, x0)) {
356 return;
357 }
358 }
359 }
360 }
361 } else {
362 bool dep_seen_x0 = note_dep_seen(dept, x0); // records x0 for future queries
363 bool dep_seen_x1 = note_dep_seen(dept, x1); // records x1 for future queries
364 if (dep_seen_x0 && dep_seen_x1) {
365 // look in this bucket for redundant assertions
366 const int stride = 2;
367 for (int i = deps->length(); (i -= stride) >= 0; ) {
368 DepValue y0 = deps->at(i+0);
369 DepValue y1 = deps->at(i+1);
370 if (x0 == y0 && x1 == y1) {
371 return;
372 }
373 }
374 }
375 }
376
377 // append the assertion in the correct bucket:
378 deps->append(x0);
379 deps->append(x1);
380 }
381 #endif // INCLUDE_JVMCI
382
383 /// Support for encoding dependencies into an nmethod:
384
385 void Dependencies::copy_to(nmethod* nm) {
386 address beg = nm->dependencies_begin();
387 address end = nm->dependencies_end();
388 guarantee(end - beg >= (ptrdiff_t) size_in_bytes(), "bad sizing");
389 (void)memcpy(beg, content_bytes(), size_in_bytes());
390 assert(size_in_bytes() % sizeof(HeapWord) == 0, "copy by words");
391 }
392
393 static int sort_dep(ciBaseObject** p1, ciBaseObject** p2, int narg) {
394 for (int i = 0; i < narg; i++) {
395 int diff = p1[i]->ident() - p2[i]->ident();
396 if (diff != 0) return diff;
397 }
398 return 0;
399 }
400 static int sort_dep_arg_1(ciBaseObject** p1, ciBaseObject** p2)
401 { return sort_dep(p1, p2, 1); }
402 static int sort_dep_arg_2(ciBaseObject** p1, ciBaseObject** p2)
403 { return sort_dep(p1, p2, 2); }
404 static int sort_dep_arg_3(ciBaseObject** p1, ciBaseObject** p2)
405 { return sort_dep(p1, p2, 3); }
406 static int sort_dep_arg_4(ciBaseObject** p1, ciBaseObject** p2)
407 { return sort_dep(p1, p2, 4); }
408
409 #if INCLUDE_JVMCI
410 // metadata deps are sorted before object deps
411 static int sort_dep_value(Dependencies::DepValue* p1, Dependencies::DepValue* p2, int narg) {
412 for (int i = 0; i < narg; i++) {
413 int diff = p1[i].sort_key() - p2[i].sort_key();
414 if (diff != 0) return diff;
415 }
416 return 0;
417 }
418 static int sort_dep_value_arg_1(Dependencies::DepValue* p1, Dependencies::DepValue* p2)
419 { return sort_dep_value(p1, p2, 1); }
420 static int sort_dep_value_arg_2(Dependencies::DepValue* p1, Dependencies::DepValue* p2)
421 { return sort_dep_value(p1, p2, 2); }
422 static int sort_dep_value_arg_3(Dependencies::DepValue* p1, Dependencies::DepValue* p2)
423 { return sort_dep_value(p1, p2, 3); }
424 #endif // INCLUDE_JVMCI
425
426 void Dependencies::sort_all_deps() {
427 #if INCLUDE_JVMCI
428 if (_using_dep_values) {
429 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
430 DepType dept = (DepType)deptv;
431 GrowableArray<DepValue>* deps = _dep_values[dept];
432 if (deps->length() <= 1) continue;
433 switch (dep_args(dept)) {
434 case 1: deps->sort(sort_dep_value_arg_1, 1); break;
435 case 2: deps->sort(sort_dep_value_arg_2, 2); break;
436 case 3: deps->sort(sort_dep_value_arg_3, 3); break;
437 default: ShouldNotReachHere(); break;
438 }
439 }
440 return;
441 }
442 #endif // INCLUDE_JVMCI
443 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
444 DepType dept = (DepType)deptv;
445 GrowableArray<ciBaseObject*>* deps = _deps[dept];
446 if (deps->length() <= 1) continue;
447 switch (dep_args(dept)) {
448 case 1: deps->sort(sort_dep_arg_1, 1); break;
449 case 2: deps->sort(sort_dep_arg_2, 2); break;
450 case 3: deps->sort(sort_dep_arg_3, 3); break;
451 case 4: deps->sort(sort_dep_arg_4, 4); break;
452 default: ShouldNotReachHere(); break;
453 }
454 }
455 }
456
457 size_t Dependencies::estimate_size_in_bytes() {
458 size_t est_size = 100;
459 #if INCLUDE_JVMCI
460 if (_using_dep_values) {
461 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
462 DepType dept = (DepType)deptv;
463 GrowableArray<DepValue>* deps = _dep_values[dept];
464 est_size += deps->length() * 2; // tags and argument(s)
465 }
466 return est_size;
467 }
468 #endif // INCLUDE_JVMCI
469 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
470 DepType dept = (DepType)deptv;
471 GrowableArray<ciBaseObject*>* deps = _deps[dept];
472 est_size += deps->length()*2; // tags and argument(s)
473 }
474 return est_size;
475 }
476
477 ciKlass* Dependencies::ctxk_encoded_as_null(DepType dept, ciBaseObject* x) {
478 switch (dept) {
479 case unique_concrete_method_2:
480 case unique_concrete_method_4:
481 return x->as_metadata()->as_method()->holder();
482 default:
483 return nullptr; // let nullptr be nullptr
484 }
485 }
486
487 Klass* Dependencies::ctxk_encoded_as_null(DepType dept, Metadata* x) {
488 assert(must_be_in_vm(), "raw oops here");
489 switch (dept) {
490 case unique_concrete_method_2:
491 case unique_concrete_method_4:
492 assert(x->is_method(), "sanity");
493 return ((Method*)x)->method_holder();
494 default:
495 return nullptr; // let nullptr be nullptr
496 }
497 }
498
499 void Dependencies::encode_content_bytes() {
500 sort_all_deps();
501
502 // cast is safe, no deps can overflow INT_MAX
503 CompressedWriteStream bytes((int)estimate_size_in_bytes());
504
505 #if INCLUDE_JVMCI
506 if (_using_dep_values) {
507 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
508 DepType dept = (DepType)deptv;
509 GrowableArray<DepValue>* deps = _dep_values[dept];
510 if (deps->length() == 0) continue;
511 int stride = dep_args(dept);
512 int ctxkj = dep_context_arg(dept); // -1 if no context arg
513 assert(stride > 0, "sanity");
514 for (int i = 0; i < deps->length(); i += stride) {
515 jbyte code_byte = (jbyte)dept;
516 int skipj = -1;
517 if (ctxkj >= 0 && ctxkj+1 < stride) {
518 Klass* ctxk = deps->at(i+ctxkj+0).as_klass(_oop_recorder);
519 DepValue x = deps->at(i+ctxkj+1); // following argument
520 if (ctxk == ctxk_encoded_as_null(dept, x.as_metadata(_oop_recorder))) {
521 skipj = ctxkj; // we win: maybe one less oop to keep track of
522 code_byte |= default_context_type_bit;
523 }
524 }
525 bytes.write_byte(code_byte);
526 for (int j = 0; j < stride; j++) {
527 if (j == skipj) continue;
528 DepValue v = deps->at(i+j);
529 int idx = v.index();
530 bytes.write_int(idx);
531 }
532 }
533 }
534 } else {
535 #endif // INCLUDE_JVMCI
536 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
537 DepType dept = (DepType)deptv;
538 GrowableArray<ciBaseObject*>* deps = _deps[dept];
539 if (deps->length() == 0) continue;
540 int stride = dep_args(dept);
541 int ctxkj = dep_context_arg(dept); // -1 if no context arg
542 assert(stride > 0, "sanity");
543 for (int i = 0; i < deps->length(); i += stride) {
544 jbyte code_byte = (jbyte)dept;
545 int skipj = -1;
546 if (ctxkj >= 0 && ctxkj+1 < stride) {
547 ciKlass* ctxk = deps->at(i+ctxkj+0)->as_metadata()->as_klass();
548 ciBaseObject* x = deps->at(i+ctxkj+1); // following argument
549 if (ctxk == ctxk_encoded_as_null(dept, x)) {
550 skipj = ctxkj; // we win: maybe one less oop to keep track of
551 code_byte |= default_context_type_bit;
552 }
553 }
554 bytes.write_byte(code_byte);
555 for (int j = 0; j < stride; j++) {
556 if (j == skipj) continue;
557 ciBaseObject* v = deps->at(i+j);
558 int idx;
559 if (v->is_object()) {
560 idx = _oop_recorder->find_index(v->as_object()->constant_encoding());
561 } else {
562 ciMetadata* meta = v->as_metadata();
563 idx = _oop_recorder->find_index(meta->constant_encoding());
564 }
565 bytes.write_int(idx);
566 }
567 }
568 }
569 #if INCLUDE_JVMCI
570 }
571 #endif
572
573 // write a sentinel byte to mark the end
574 bytes.write_byte(end_marker);
575
576 // round it out to a word boundary
577 while (bytes.position() % sizeof(HeapWord) != 0) {
578 bytes.write_byte(end_marker);
579 }
580
581 // check whether the dept byte encoding really works
582 assert((jbyte)default_context_type_bit != 0, "byte overflow");
583
584 _content_bytes = bytes.buffer();
585 _size_in_bytes = bytes.position();
586 }
587
588
589 const char* Dependencies::_dep_name[TYPE_LIMIT] = {
590 "end_marker",
591 "evol_method",
592 "mismatch_calling_convention",
593 "leaf_type",
594 "abstract_with_unique_concrete_subtype",
595 "unique_concrete_method_2",
596 "unique_concrete_method_4",
597 "unique_implementor",
598 "no_finalizable_subclasses",
599 "call_site_target_value"
600 };
601
602 int Dependencies::_dep_args[TYPE_LIMIT] = {
603 -1,// end_marker
604 1, // evol_method m
605 1, // mismatch_calling_convention m
606 1, // leaf_type ctxk
607 2, // abstract_with_unique_concrete_subtype ctxk, k
608 2, // unique_concrete_method_2 ctxk, m
609 4, // unique_concrete_method_4 ctxk, m, resolved_klass, resolved_method
610 2, // unique_implementor ctxk, implementor
611 1, // no_finalizable_subclasses ctxk
612 2 // call_site_target_value call_site, method_handle
613 };
614
615 const char* Dependencies::dep_name(Dependencies::DepType dept) {
616 if (!dept_in_mask(dept, all_types)) return "?bad-dep?";
617 return _dep_name[dept];
618 }
619
620 int Dependencies::dep_args(Dependencies::DepType dept) {
621 if (!dept_in_mask(dept, all_types)) return -1;
622 return _dep_args[dept];
623 }
624
625 void Dependencies::check_valid_dependency_type(DepType dept) {
626 guarantee(FIRST_TYPE <= dept && dept < TYPE_LIMIT, "invalid dependency type: %d", (int) dept);
627 }
628
629 Dependencies::DepType Dependencies::validate_dependencies(CompileTask* task, char** failure_detail) {
630 int klass_violations = 0;
631 DepType result = end_marker;
632 for (Dependencies::DepStream deps(this); deps.next(); ) {
633 Klass* witness = deps.check_dependency();
634 if (witness != nullptr) {
635 if (klass_violations == 0) {
636 result = deps.type();
637 if (failure_detail != nullptr && klass_violations == 0) {
638 // Use a fixed size buffer to prevent the string stream from
639 // resizing in the context of an inner resource mark.
640 char* buffer = NEW_RESOURCE_ARRAY(char, O_BUFLEN);
641 stringStream st(buffer, O_BUFLEN);
642 deps.print_dependency(&st, witness, true);
643 *failure_detail = st.as_string();
644 }
645 }
646 klass_violations++;
647 if (xtty == nullptr) {
648 // If we're not logging then a single violation is sufficient,
649 // otherwise we want to log all the dependences which were
650 // violated.
651 break;
652 }
653 }
654 }
655
656 return result;
657 }
658
659 // for the sake of the compiler log, print out current dependencies:
660 void Dependencies::log_all_dependencies() {
661 if (log() == nullptr) return;
662 ResourceMark rm;
663 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
664 DepType dept = (DepType)deptv;
665 GrowableArray<ciBaseObject*>* deps = _deps[dept];
666 int deplen = deps->length();
667 if (deplen == 0) {
668 continue;
669 }
670 int stride = dep_args(dept);
671 GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(stride);
672 for (int i = 0; i < deps->length(); i += stride) {
673 for (int j = 0; j < stride; j++) {
674 // flush out the identities before printing
675 ciargs->push(deps->at(i+j));
676 }
677 write_dependency_to(log(), dept, ciargs);
678 ciargs->clear();
679 }
680 guarantee(deplen == deps->length(), "deps array cannot grow inside nested ResoureMark scope");
681 }
682 }
683
684 void Dependencies::write_dependency_to(CompileLog* log,
685 DepType dept,
686 GrowableArray<DepArgument>* args,
687 Klass* witness) {
688 if (log == nullptr) {
689 return;
690 }
691 ResourceMark rm;
692 ciEnv* env = ciEnv::current();
693 GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(args->length());
694 for (GrowableArrayIterator<DepArgument> it = args->begin(); it != args->end(); ++it) {
695 DepArgument arg = *it;
696 if (arg.is_oop()) {
697 ciargs->push(env->get_object(arg.oop_value()));
698 } else {
699 ciargs->push(env->get_metadata(arg.metadata_value()));
700 }
701 }
702 int argslen = ciargs->length();
703 Dependencies::write_dependency_to(log, dept, ciargs, witness);
704 guarantee(argslen == ciargs->length(), "ciargs array cannot grow inside nested ResoureMark scope");
705 }
706
707 void Dependencies::write_dependency_to(CompileLog* log,
708 DepType dept,
709 GrowableArray<ciBaseObject*>* args,
710 Klass* witness) {
711 if (log == nullptr) {
712 return;
713 }
714 ResourceMark rm;
715 GrowableArray<int>* argids = new GrowableArray<int>(args->length());
716 for (GrowableArrayIterator<ciBaseObject*> it = args->begin(); it != args->end(); ++it) {
717 ciBaseObject* obj = *it;
718 if (obj->is_object()) {
719 argids->push(log->identify(obj->as_object()));
720 } else {
721 argids->push(log->identify(obj->as_metadata()));
722 }
723 }
724 if (witness != nullptr) {
725 log->begin_elem("dependency_failed");
726 } else {
727 log->begin_elem("dependency");
728 }
729 log->print(" type='%s'", dep_name(dept));
730 const int ctxkj = dep_context_arg(dept); // -1 if no context arg
731 if (ctxkj >= 0 && ctxkj < argids->length()) {
732 log->print(" ctxk='%d'", argids->at(ctxkj));
733 }
734 // write remaining arguments, if any.
735 for (int j = 0; j < argids->length(); j++) {
736 if (j == ctxkj) continue; // already logged
737 if (j == 1) {
738 log->print( " x='%d'", argids->at(j));
739 } else {
740 log->print(" x%d='%d'", j, argids->at(j));
741 }
742 }
743 if (witness != nullptr) {
744 log->object("witness", witness);
745 log->stamp();
746 }
747 log->end_elem();
748 }
749
750 void Dependencies::write_dependency_to(xmlStream* xtty,
751 DepType dept,
752 GrowableArray<DepArgument>* args,
753 Klass* witness) {
754 if (xtty == nullptr) {
755 return;
756 }
757 Thread* thread = Thread::current();
758 HandleMark rm(thread);
759 ttyLocker ttyl;
760 int ctxkj = dep_context_arg(dept); // -1 if no context arg
761 if (witness != nullptr) {
762 xtty->begin_elem("dependency_failed");
763 } else {
764 xtty->begin_elem("dependency");
765 }
766 xtty->print(" type='%s'", dep_name(dept));
767 if (ctxkj >= 0) {
768 xtty->object("ctxk", args->at(ctxkj).metadata_value());
769 }
770 // write remaining arguments, if any.
771 for (int j = 0; j < args->length(); j++) {
772 if (j == ctxkj) continue; // already logged
773 DepArgument arg = args->at(j);
774 if (j == 1) {
775 if (arg.is_oop()) {
776 xtty->object("x", Handle(thread, arg.oop_value()));
777 } else {
778 xtty->object("x", arg.metadata_value());
779 }
780 } else {
781 char xn[12];
782 os::snprintf_checked(xn, sizeof(xn), "x%d", j);
783 if (arg.is_oop()) {
784 xtty->object(xn, Handle(thread, arg.oop_value()));
785 } else {
786 xtty->object(xn, arg.metadata_value());
787 }
788 }
789 }
790 if (witness != nullptr) {
791 xtty->object("witness", witness);
792 xtty->stamp();
793 }
794 xtty->end_elem();
795 }
796
797 void Dependencies::print_dependency(DepType dept, GrowableArray<DepArgument>* args,
798 Klass* witness, outputStream* st) {
799 ResourceMark rm;
800 ttyLocker ttyl; // keep the following output all in one block
801 st->print_cr("%s of type %s",
802 (witness == nullptr)? "Dependency": "Failed dependency",
803 dep_name(dept));
804 // print arguments
805 int ctxkj = dep_context_arg(dept); // -1 if no context arg
806 for (int j = 0; j < args->length(); j++) {
807 DepArgument arg = args->at(j);
808 bool put_star = false;
809 if (arg.is_null()) continue;
810 const char* what;
811 if (j == ctxkj) {
812 assert(arg.is_metadata(), "must be");
813 what = "context";
814 put_star = !Dependencies::is_concrete_klass((Klass*)arg.metadata_value());
815 } else if (arg.is_method()) {
816 what = "method ";
817 put_star = !Dependencies::is_concrete_method((Method*)arg.metadata_value(), nullptr);
818 } else if (arg.is_klass()) {
819 what = "class ";
820 } else {
821 what = "object ";
822 }
823 st->print(" %s = %s", what, (put_star? "*": ""));
824 if (arg.is_klass()) {
825 st->print("%s", ((Klass*)arg.metadata_value())->external_name());
826 } else if (arg.is_method()) {
827 ((Method*)arg.metadata_value())->print_value_on(st);
828 } else if (arg.is_oop()) {
829 arg.oop_value()->print_value_on(st);
830 } else {
831 ShouldNotReachHere(); // Provide impl for this type.
832 }
833
834 st->cr();
835 }
836 if (witness != nullptr) {
837 bool put_star = !Dependencies::is_concrete_klass(witness);
838 st->print_cr(" witness = %s%s",
839 (put_star? "*": ""),
840 witness->external_name());
841 }
842 }
843
844 void Dependencies::DepStream::log_dependency(Klass* witness) {
845 if (_deps == nullptr && xtty == nullptr) return; // fast cutout for runtime
846 ResourceMark rm;
847 const int nargs = argument_count();
848 GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
849 for (int j = 0; j < nargs; j++) {
850 if (is_oop_argument(j)) {
851 args->push(argument_oop(j));
852 } else {
853 args->push(argument(j));
854 }
855 }
856 int argslen = args->length();
857 if (_deps != nullptr && _deps->log() != nullptr) {
858 if (ciEnv::current() != nullptr) {
859 Dependencies::write_dependency_to(_deps->log(), type(), args, witness);
860 } else {
861 // Treat the CompileLog as an xmlstream instead
862 Dependencies::write_dependency_to((xmlStream*)_deps->log(), type(), args, witness);
863 }
864 } else {
865 Dependencies::write_dependency_to(xtty, type(), args, witness);
866 }
867 guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
868 }
869
870 void Dependencies::DepStream::print_dependency(outputStream* st, Klass* witness, bool verbose) {
871 ResourceMark rm;
872 int nargs = argument_count();
873 GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
874 for (int j = 0; j < nargs; j++) {
875 if (is_oop_argument(j)) {
876 args->push(argument_oop(j));
877 } else {
878 args->push(argument(j));
879 }
880 }
881 int argslen = args->length();
882 Dependencies::print_dependency(type(), args, witness, st);
883 if (verbose) {
884 if (_code != nullptr) {
885 st->print(" code: ");
886 _code->print_value_on(st);
887 st->cr();
888 }
889 }
890 guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
891 }
892
893
894 /// Dependency stream support (decodes dependencies from an nmethod):
895
896 #ifdef ASSERT
897 void Dependencies::DepStream::initial_asserts(size_t byte_limit) {
898 assert(must_be_in_vm(), "raw oops here");
899 _byte_limit = byte_limit;
900 _type = undefined_dependency; // defeat "already at end" assert
901 assert((_code!=nullptr) + (_deps!=nullptr) == 1, "one or t'other");
902 }
903 #endif //ASSERT
904
905 bool Dependencies::DepStream::next() {
906 assert(_type != end_marker, "already at end");
907 if (_bytes.position() == 0 && _code != nullptr
908 && _code->dependencies_size() == 0) {
909 // Method has no dependencies at all.
910 return false;
911 }
912 int code_byte = (_bytes.read_byte() & 0xFF);
913 if (code_byte == end_marker) {
914 DEBUG_ONLY(_type = end_marker);
915 return false;
916 } else {
917 int ctxk_bit = (code_byte & Dependencies::default_context_type_bit);
918 code_byte -= ctxk_bit;
919 DepType dept = (DepType)code_byte;
920 _type = dept;
921 Dependencies::check_valid_dependency_type(dept);
922 int stride = _dep_args[dept];
923 assert(stride == dep_args(dept), "sanity");
924 int skipj = -1;
925 if (ctxk_bit != 0) {
926 skipj = 0; // currently the only context argument is at zero
927 assert(skipj == dep_context_arg(dept), "zero arg always ctxk");
928 }
929 for (int j = 0; j < stride; j++) {
930 _xi[j] = (j == skipj)? 0: _bytes.read_int();
931 }
932 DEBUG_ONLY(_xi[stride] = -1); // help detect overruns
933 return true;
934 }
935 }
936
937 inline Metadata* Dependencies::DepStream::recorded_metadata_at(int i) {
938 Metadata* o = nullptr;
939 if (_code != nullptr) {
940 o = _code->metadata_at(i);
941 } else {
942 o = _deps->oop_recorder()->metadata_at(i);
943 }
944 return o;
945 }
946
947 inline oop Dependencies::DepStream::recorded_oop_at(int i) {
948 return (_code != nullptr)
949 ? _code->oop_at(i)
950 : JNIHandles::resolve(_deps->oop_recorder()->oop_at(i));
951 }
952
953 Metadata* Dependencies::DepStream::argument(int i) {
954 Metadata* result = recorded_metadata_at(argument_index(i));
955
956 if (result == nullptr) { // Explicit context argument can be compressed
957 int ctxkj = dep_context_arg(type()); // -1 if no explicit context arg
958 if (ctxkj >= 0 && i == ctxkj && ctxkj+1 < argument_count()) {
959 result = ctxk_encoded_as_null(type(), argument(ctxkj+1));
960 }
961 }
962
963 assert(result == nullptr || result->is_klass() || result->is_method(), "must be");
964 return result;
965 }
966
967 /**
968 * Returns a unique identifier for each dependency argument.
969 */
970 uintptr_t Dependencies::DepStream::get_identifier(int i) {
971 if (is_oop_argument(i)) {
972 return (uintptr_t)(oopDesc*)argument_oop(i);
973 } else {
974 return (uintptr_t)argument(i);
975 }
976 }
977
978 oop Dependencies::DepStream::argument_oop(int i) {
979 oop result = recorded_oop_at(argument_index(i));
980 assert(oopDesc::is_oop_or_null(result), "must be");
981 return result;
982 }
983
984 InstanceKlass* Dependencies::DepStream::context_type() {
985 assert(must_be_in_vm(), "raw oops here");
986
987 // Most dependencies have an explicit context type argument.
988 {
989 int ctxkj = dep_context_arg(type()); // -1 if no explicit context arg
990 if (ctxkj >= 0) {
991 Metadata* k = argument(ctxkj);
992 assert(k != nullptr && k->is_klass(), "type check");
993 return InstanceKlass::cast((Klass*)k);
994 }
995 }
996
997 // Some dependencies are using the klass of the first object
998 // argument as implicit context type.
999 {
1000 int ctxkj = dep_implicit_context_arg(type());
1001 if (ctxkj >= 0) {
1002 Klass* k = argument_oop(ctxkj)->klass();
1003 assert(k != nullptr, "type check");
1004 return InstanceKlass::cast(k);
1005 }
1006 }
1007
1008 // And some dependencies don't have a context type at all,
1009 // e.g. evol_method.
1010 return nullptr;
1011 }
1012
1013 // ----------------- DependencySignature --------------------------------------
1014 bool DependencySignature::equals(DependencySignature const& s1, DependencySignature const& s2) {
1015 if ((s1.type() != s2.type()) || (s1.args_count() != s2.args_count())) {
1016 return false;
1017 }
1018
1019 for (int i = 0; i < s1.args_count(); i++) {
1020 if (s1.arg(i) != s2.arg(i)) {
1021 return false;
1022 }
1023 }
1024 return true;
1025 }
1026
1027 /// Checking dependencies
1028
1029 // This hierarchy walker inspects subtypes of a given type, trying to find a "bad" class which breaks a dependency.
1030 // Such a class is called a "witness" to the broken dependency.
1031 // While searching around, we ignore "participants", which are already known to the dependency.
1032 class AbstractClassHierarchyWalker {
1033 public:
1034 enum { PARTICIPANT_LIMIT = 3 };
1035
1036 private:
1037 // if non-zero, tells how many witnesses to convert to participants
1038 uint _record_witnesses;
1039
1040 // special classes which are not allowed to be witnesses:
1041 Klass* _participants[PARTICIPANT_LIMIT+1];
1042 uint _num_participants;
1043
1044 #ifdef ASSERT
1045 uint _nof_requests; // one-shot walker
1046 #endif // ASSERT
1047
1048 static PerfCounter* _perf_find_witness_anywhere_calls_count;
1049 static PerfCounter* _perf_find_witness_anywhere_steps_count;
1050 static PerfCounter* _perf_find_witness_in_calls_count;
1051
1052 protected:
1053 virtual Klass* find_witness_in(KlassDepChange& changes) = 0;
1054 virtual Klass* find_witness_anywhere(InstanceKlass* context_type) = 0;
1055
1056 AbstractClassHierarchyWalker(Klass* participant) : _record_witnesses(0), _num_participants(0)
1057 #ifdef ASSERT
1058 , _nof_requests(0)
1059 #endif // ASSERT
1060 {
1061 for (uint i = 0; i < PARTICIPANT_LIMIT+1; i++) {
1062 _participants[i] = nullptr;
1063 }
1064 if (participant != nullptr) {
1065 add_participant(participant);
1066 }
1067 }
1068
1069 bool is_participant(Klass* k) {
1070 for (uint i = 0; i < _num_participants; i++) {
1071 if (_participants[i] == k) {
1072 return true;
1073 }
1074 }
1075 return false;
1076 }
1077
1078 bool record_witness(Klass* witness) {
1079 if (_record_witnesses > 0) {
1080 --_record_witnesses;
1081 add_participant(witness);
1082 return false; // not a witness
1083 } else {
1084 return true; // is a witness
1085 }
1086 }
1087
1088 class CountingClassHierarchyIterator : public ClassHierarchyIterator {
1089 private:
1090 jlong _nof_steps;
1091 public:
1092 CountingClassHierarchyIterator(InstanceKlass* root) : ClassHierarchyIterator(root), _nof_steps(0) {}
1093
1094 void next() {
1095 _nof_steps++;
1096 ClassHierarchyIterator::next();
1097 }
1098
1099 ~CountingClassHierarchyIterator() {
1100 if (UsePerfData) {
1101 _perf_find_witness_anywhere_steps_count->inc(_nof_steps);
1102 }
1103 }
1104 };
1105
1106 public:
1107 uint num_participants() { return _num_participants; }
1108 Klass* participant(uint n) {
1109 assert(n <= _num_participants, "oob");
1110 if (n < _num_participants) {
1111 return _participants[n];
1112 } else {
1113 return nullptr;
1114 }
1115 }
1116
1117 void add_participant(Klass* participant) {
1118 assert(!is_participant(participant), "sanity");
1119 assert(_num_participants + _record_witnesses < PARTICIPANT_LIMIT, "oob");
1120 uint np = _num_participants++;
1121 _participants[np] = participant;
1122 }
1123
1124 void record_witnesses(uint add) {
1125 if (add > PARTICIPANT_LIMIT) add = PARTICIPANT_LIMIT;
1126 assert(_num_participants + add < PARTICIPANT_LIMIT, "oob");
1127 _record_witnesses = add;
1128 }
1129
1130 Klass* find_witness(InstanceKlass* context_type, KlassDepChange* changes = nullptr);
1131
1132 static void init();
1133 static void print_statistics();
1134 };
1135
1136 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_anywhere_calls_count = nullptr;
1137 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_anywhere_steps_count = nullptr;
1138 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_in_calls_count = nullptr;
1139
1140 void AbstractClassHierarchyWalker::init() {
1141 if (UsePerfData) {
1142 EXCEPTION_MARK;
1143 _perf_find_witness_anywhere_calls_count =
1144 PerfDataManager::create_counter(SUN_CI, "findWitnessAnywhere", PerfData::U_Events, CHECK);
1145 _perf_find_witness_anywhere_steps_count =
1146 PerfDataManager::create_counter(SUN_CI, "findWitnessAnywhereSteps", PerfData::U_Events, CHECK);
1147 _perf_find_witness_in_calls_count =
1148 PerfDataManager::create_counter(SUN_CI, "findWitnessIn", PerfData::U_Events, CHECK);
1149 }
1150 }
1151
1152 Klass* AbstractClassHierarchyWalker::find_witness(InstanceKlass* context_type, KlassDepChange* changes) {
1153 // Current thread must be in VM (not native mode, as in CI):
1154 assert(must_be_in_vm(), "raw oops here");
1155 // Must not move the class hierarchy during this check:
1156 assert_locked_or_safepoint(Compile_lock);
1157 assert(_nof_requests++ == 0, "repeated requests are not supported");
1158
1159 assert(changes == nullptr || changes->involves_context(context_type), "irrelevant dependency");
1160
1161 // (Note: Interfaces do not have subclasses.)
1162 // If it is an interface, search its direct implementors.
1163 // (Their subclasses are additional indirect implementors. See InstanceKlass::add_implementor().)
1164 if (context_type->is_interface()) {
1165 int nof_impls = context_type->nof_implementors();
1166 if (nof_impls == 0) {
1167 return nullptr; // no implementors
1168 } else if (nof_impls == 1) { // unique implementor
1169 assert(context_type != context_type->implementor(), "not unique");
1170 context_type = context_type->implementor();
1171 } else { // nof_impls >= 2
1172 // Avoid this case: *I.m > { A.m, C }; B.m > C
1173 // Here, I.m has 2 concrete implementations, but m appears unique
1174 // as A.m, because the search misses B.m when checking C.
1175 // The inherited method B.m was getting missed by the walker
1176 // when interface 'I' was the starting point.
1177 // %%% Until this is fixed more systematically, bail out.
1178 return context_type;
1179 }
1180 }
1181 assert(!context_type->is_interface(), "no interfaces allowed");
1182
1183 if (changes != nullptr) {
1184 if (UsePerfData) {
1185 _perf_find_witness_in_calls_count->inc();
1186 }
1187 return find_witness_in(*changes);
1188 } else {
1189 if (UsePerfData) {
1190 _perf_find_witness_anywhere_calls_count->inc();
1191 }
1192 return find_witness_anywhere(context_type);
1193 }
1194 }
1195
1196 class ConcreteSubtypeFinder : public AbstractClassHierarchyWalker {
1197 private:
1198 bool is_witness(Klass* k);
1199
1200 protected:
1201 virtual Klass* find_witness_in(KlassDepChange& changes);
1202 virtual Klass* find_witness_anywhere(InstanceKlass* context_type);
1203
1204 public:
1205 ConcreteSubtypeFinder(Klass* participant = nullptr) : AbstractClassHierarchyWalker(participant) {}
1206 };
1207
1208 bool ConcreteSubtypeFinder::is_witness(Klass* k) {
1209 if (Dependencies::is_concrete_klass(k)) {
1210 return record_witness(k); // concrete subtype
1211 } else {
1212 return false; // not a concrete class
1213 }
1214 }
1215
1216 Klass* ConcreteSubtypeFinder::find_witness_in(KlassDepChange& changes) {
1217 // When looking for unexpected concrete types, do not look beneath expected ones:
1218 // * CX > CC > C' is OK, even if C' is new.
1219 // * CX > { CC, C' } is not OK if C' is new, and C' is the witness.
1220 Klass* new_type = changes.as_new_klass_change()->new_type();
1221 assert(!is_participant(new_type), "only old classes are participants");
1222 // If the new type is a subtype of a participant, we are done.
1223 for (uint i = 0; i < num_participants(); i++) {
1224 if (changes.involves_context(participant(i))) {
1225 // new guy is protected from this check by previous participant
1226 return nullptr;
1227 }
1228 }
1229 if (is_witness(new_type)) {
1230 return new_type;
1231 }
1232 // No witness found. The dependency remains unbroken.
1233 return nullptr;
1234 }
1235
1236 Klass* ConcreteSubtypeFinder::find_witness_anywhere(InstanceKlass* context_type) {
1237 for (CountingClassHierarchyIterator iter(context_type); !iter.done(); iter.next()) {
1238 Klass* sub = iter.klass();
1239 // Do not report participant types.
1240 if (is_participant(sub)) {
1241 // Don't walk beneath a participant since it hides witnesses.
1242 iter.skip_subclasses();
1243 } else if (is_witness(sub)) {
1244 return sub; // found a witness
1245 }
1246 }
1247 // No witness found. The dependency remains unbroken.
1248 return nullptr;
1249 }
1250
1251 class ConcreteMethodFinder : public AbstractClassHierarchyWalker {
1252 private:
1253 Symbol* _name;
1254 Symbol* _signature;
1255
1256 // cache of method lookups
1257 Method* _found_methods[PARTICIPANT_LIMIT+1];
1258
1259 bool is_witness(Klass* k);
1260
1261 protected:
1262 virtual Klass* find_witness_in(KlassDepChange& changes);
1263 virtual Klass* find_witness_anywhere(InstanceKlass* context_type);
1264
1265 public:
1266 bool witnessed_reabstraction_in_supers(Klass* k);
1267
1268 ConcreteMethodFinder(Method* m, Klass* participant = nullptr) : AbstractClassHierarchyWalker(participant) {
1269 assert(m != nullptr && m->is_method(), "sanity");
1270 _name = m->name();
1271 _signature = m->signature();
1272
1273 for (int i = 0; i < PARTICIPANT_LIMIT+1; i++) {
1274 _found_methods[i] = nullptr;
1275 }
1276 }
1277
1278 // Note: If n==num_participants, returns nullptr.
1279 Method* found_method(uint n) {
1280 assert(n <= num_participants(), "oob");
1281 Method* fm = _found_methods[n];
1282 assert(n == num_participants() || fm != nullptr, "proper usage");
1283 if (fm != nullptr && fm->method_holder() != participant(n)) {
1284 // Default methods from interfaces can be added to classes. In
1285 // that case the holder of the method is not the class but the
1286 // interface where it's defined.
1287 assert(fm->is_default_method(), "sanity");
1288 return nullptr;
1289 }
1290 return fm;
1291 }
1292
1293 void add_participant(Klass* participant) {
1294 AbstractClassHierarchyWalker::add_participant(participant);
1295 _found_methods[num_participants()] = nullptr;
1296 }
1297
1298 bool record_witness(Klass* witness, Method* m) {
1299 _found_methods[num_participants()] = m;
1300 return AbstractClassHierarchyWalker::record_witness(witness);
1301 }
1302
1303 private:
1304 static PerfCounter* _perf_find_witness_anywhere_calls_count;
1305 static PerfCounter* _perf_find_witness_anywhere_steps_count;
1306 static PerfCounter* _perf_find_witness_in_calls_count;
1307
1308 public:
1309 static void init();
1310 static void print_statistics();
1311 };
1312
1313 bool ConcreteMethodFinder::is_witness(Klass* k) {
1314 if (is_participant(k)) {
1315 return false; // do not report participant types
1316 }
1317 if (k->is_instance_klass()) {
1318 InstanceKlass* ik = InstanceKlass::cast(k);
1319 // Search class hierarchy first, skipping private implementations
1320 // as they never override any inherited methods
1321 Method* m = ik->find_instance_method(_name, _signature, Klass::PrivateLookupMode::skip);
1322 if (Dependencies::is_concrete_method(m, ik)) {
1323 return record_witness(k, m); // concrete method found
1324 } else {
1325 // Check for re-abstraction of method
1326 if (!ik->is_interface() && m != nullptr && m->is_abstract()) {
1327 // Found a matching abstract method 'm' in the class hierarchy.
1328 // This is fine iff 'k' is an abstract class and all concrete subtypes
1329 // of 'k' override 'm' and are participates of the current search.
1330 ConcreteSubtypeFinder wf;
1331 for (uint i = 0; i < num_participants(); i++) {
1332 Klass* p = participant(i);
1333 wf.add_participant(p);
1334 }
1335 Klass* w = wf.find_witness(ik);
1336 if (w != nullptr) {
1337 Method* wm = InstanceKlass::cast(w)->find_instance_method(_name, _signature, Klass::PrivateLookupMode::skip);
1338 if (!Dependencies::is_concrete_method(wm, w)) {
1339 // Found a concrete subtype 'w' which does not override abstract method 'm'.
1340 // Bail out because 'm' could be called with 'w' as receiver (leading to an
1341 // AbstractMethodError) and thus the method we are looking for is not unique.
1342 return record_witness(k, m);
1343 }
1344 }
1345 }
1346 // Check interface defaults also, if any exist.
1347 Array<Method*>* default_methods = ik->default_methods();
1348 if (default_methods != nullptr) {
1349 Method* dm = ik->find_method(default_methods, _name, _signature);
1350 if (Dependencies::is_concrete_method(dm, nullptr)) {
1351 return record_witness(k, dm); // default method found
1352 }
1353 }
1354 return false; // no concrete method found
1355 }
1356 } else {
1357 return false; // no methods to find in an array type
1358 }
1359 }
1360
1361 Klass* ConcreteMethodFinder::find_witness_in(KlassDepChange& changes) {
1362 // When looking for unexpected concrete methods, look beneath expected ones, to see if there are overrides.
1363 // * CX.m > CC.m > C'.m is not OK, if C'.m is new, and C' is the witness.
1364 Klass* new_type = changes.as_new_klass_change()->new_type();
1365 assert(!is_participant(new_type), "only old classes are participants");
1366 if (is_witness(new_type)) {
1367 return new_type;
1368 } else {
1369 // No witness found, but is_witness() doesn't detect method re-abstraction in case of spot-checking.
1370 if (witnessed_reabstraction_in_supers(new_type)) {
1371 return new_type;
1372 }
1373 }
1374 // No witness found. The dependency remains unbroken.
1375 return nullptr;
1376 }
1377
1378 bool ConcreteMethodFinder::witnessed_reabstraction_in_supers(Klass* k) {
1379 if (!k->is_instance_klass()) {
1380 return false; // no methods to find in an array type
1381 } else {
1382 // Looking for a case when an abstract method is inherited into a concrete class.
1383 if (Dependencies::is_concrete_klass(k) && !k->is_interface()) {
1384 Method* m = InstanceKlass::cast(k)->find_instance_method(_name, _signature, Klass::PrivateLookupMode::skip);
1385 if (m != nullptr) {
1386 return false; // no reabstraction possible: local method found
1387 }
1388 for (InstanceKlass* super = k->java_super(); super != nullptr; super = super->java_super()) {
1389 m = super->find_instance_method(_name, _signature, Klass::PrivateLookupMode::skip);
1390 if (m != nullptr) { // inherited method found
1391 if (m->is_abstract() || m->is_overpass()) {
1392 return record_witness(super, m); // abstract method found
1393 }
1394 return false;
1395 }
1396 }
1397 // Miranda.
1398 return true;
1399 }
1400 return false;
1401 }
1402 }
1403
1404
1405 Klass* ConcreteMethodFinder::find_witness_anywhere(InstanceKlass* context_type) {
1406 // Walk hierarchy under a context type, looking for unexpected types.
1407 for (CountingClassHierarchyIterator iter(context_type); !iter.done(); iter.next()) {
1408 Klass* sub = iter.klass();
1409 if (is_witness(sub)) {
1410 return sub; // found a witness
1411 }
1412 }
1413 // No witness found. The dependency remains unbroken.
1414 return nullptr;
1415 }
1416
1417 // For some method m and some class ctxk (subclass of method holder),
1418 // enumerate all distinct overrides of m in concrete subclasses of ctxk.
1419 // It relies on vtable/itable information to perform method selection on each linked subclass
1420 // and ignores all non yet linked ones (speculatively treat them as "effectively abstract").
1421 class LinkedConcreteMethodFinder : public AbstractClassHierarchyWalker {
1422 private:
1423 InstanceKlass* _resolved_klass; // resolved class (JVMS-5.4.3.1)
1424 InstanceKlass* _declaring_klass; // the holder of resolved method (JVMS-5.4.3.3)
1425 int _vtable_index; // vtable/itable index of the resolved method
1426 bool _do_itable_lookup; // choose between itable and vtable lookup logic
1427
1428 // cache of method lookups
1429 Method* _found_methods[PARTICIPANT_LIMIT+1];
1430
1431 bool is_witness(Klass* k);
1432 Method* select_method(InstanceKlass* recv_klass);
1433 static int compute_vtable_index(InstanceKlass* resolved_klass, Method* resolved_method, bool& is_itable_index);
1434 static bool is_concrete_klass(InstanceKlass* ik);
1435
1436 void add_participant(Method* m, Klass* participant) {
1437 uint np = num_participants();
1438 AbstractClassHierarchyWalker::add_participant(participant);
1439 assert(np + 1 == num_participants(), "sanity");
1440 _found_methods[np] = m; // record the method for the participant
1441 }
1442
1443 bool record_witness(Klass* witness, Method* m) {
1444 for (uint i = 0; i < num_participants(); i++) {
1445 if (found_method(i) == m) {
1446 return false; // already recorded
1447 }
1448 }
1449 // Record not yet seen method.
1450 _found_methods[num_participants()] = m;
1451 return AbstractClassHierarchyWalker::record_witness(witness);
1452 }
1453
1454 void initialize(Method* participant) {
1455 for (uint i = 0; i < PARTICIPANT_LIMIT+1; i++) {
1456 _found_methods[i] = nullptr;
1457 }
1458 if (participant != nullptr) {
1459 add_participant(participant, participant->method_holder());
1460 }
1461 }
1462
1463 protected:
1464 virtual Klass* find_witness_in(KlassDepChange& changes);
1465 virtual Klass* find_witness_anywhere(InstanceKlass* context_type);
1466
1467 public:
1468 // In order to perform method selection, the following info is needed:
1469 // (1) interface or virtual call;
1470 // (2) vtable/itable index;
1471 // (3) declaring class (in case of interface call).
1472 //
1473 // It is prepared based on the results of method resolution: resolved class and resolved method (as specified in JVMS-5.4.3.3).
1474 // Optionally, a method which was previously determined as a unique target (uniqm) is added as a participant
1475 // to enable dependency spot-checking and speed up the search.
1476 LinkedConcreteMethodFinder(InstanceKlass* resolved_klass, Method* resolved_method, Method* uniqm = nullptr) : AbstractClassHierarchyWalker(nullptr) {
1477 assert(resolved_klass->is_linked(), "required");
1478 assert(resolved_method->method_holder()->is_linked(), "required");
1479 assert(!resolved_method->can_be_statically_bound(), "no vtable index available");
1480
1481 _resolved_klass = resolved_klass;
1482 _declaring_klass = resolved_method->method_holder();
1483 _vtable_index = compute_vtable_index(resolved_klass, resolved_method,
1484 _do_itable_lookup); // out parameter
1485 assert(_vtable_index >= 0, "invalid vtable index");
1486
1487 initialize(uniqm);
1488 }
1489
1490 // Note: If n==num_participants, returns nullptr.
1491 Method* found_method(uint n) {
1492 assert(n <= num_participants(), "oob");
1493 assert(participant(n) != nullptr || n == num_participants(), "proper usage");
1494 return _found_methods[n];
1495 }
1496 };
1497
1498 Klass* LinkedConcreteMethodFinder::find_witness_in(KlassDepChange& changes) {
1499 Klass* type = changes.type();
1500
1501 assert(!is_participant(type), "only old classes are participants");
1502
1503 if (is_witness(type)) {
1504 return type;
1505 }
1506 return nullptr; // No witness found. The dependency remains unbroken.
1507 }
1508
1509 Klass* LinkedConcreteMethodFinder::find_witness_anywhere(InstanceKlass* context_type) {
1510 for (CountingClassHierarchyIterator iter(context_type); !iter.done(); iter.next()) {
1511 Klass* sub = iter.klass();
1512 if (is_witness(sub)) {
1513 return sub;
1514 }
1515 if (sub->is_instance_klass() && !InstanceKlass::cast(sub)->is_linked()) {
1516 iter.skip_subclasses(); // ignore not yet linked classes
1517 }
1518 }
1519 return nullptr; // No witness found. The dependency remains unbroken.
1520 }
1521
1522 bool LinkedConcreteMethodFinder::is_witness(Klass* k) {
1523 if (is_participant(k)) {
1524 return false; // do not report participant types
1525 } else if (k->is_instance_klass()) {
1526 InstanceKlass* ik = InstanceKlass::cast(k);
1527 if (is_concrete_klass(ik)) {
1528 Method* m = select_method(ik);
1529 return record_witness(ik, m);
1530 } else {
1531 return false; // ignore non-concrete holder class
1532 }
1533 } else {
1534 return false; // no methods to find in an array type
1535 }
1536 }
1537
1538 Method* LinkedConcreteMethodFinder::select_method(InstanceKlass* recv_klass) {
1539 Method* selected_method = nullptr;
1540 if (_do_itable_lookup) {
1541 assert(_declaring_klass->is_interface(), "sanity");
1542 bool implements_interface; // initialized by method_at_itable_or_null()
1543 selected_method = recv_klass->method_at_itable_or_null(_declaring_klass, _vtable_index,
1544 implements_interface); // out parameter
1545 assert(implements_interface, "not implemented");
1546 } else {
1547 selected_method = recv_klass->method_at_vtable(_vtable_index);
1548 }
1549 return selected_method; // nullptr when corresponding slot is empty (AbstractMethodError case)
1550 }
1551
1552 int LinkedConcreteMethodFinder::compute_vtable_index(InstanceKlass* resolved_klass, Method* resolved_method,
1553 // out parameter
1554 bool& is_itable_index) {
1555 if (resolved_klass->is_interface() && resolved_method->has_itable_index()) {
1556 is_itable_index = true;
1557 return resolved_method->itable_index();
1558 }
1559 // Check for default or miranda method first.
1560 InstanceKlass* declaring_klass = resolved_method->method_holder();
1561 if (!resolved_klass->is_interface() && declaring_klass->is_interface()) {
1562 is_itable_index = false;
1563 return resolved_klass->vtable_index_of_interface_method(resolved_method);
1564 }
1565 // At this point we are sure that resolved_method is virtual and not
1566 // a default or miranda method; therefore, it must have a valid vtable index.
1567 assert(resolved_method->has_vtable_index(), "");
1568 is_itable_index = false;
1569 return resolved_method->vtable_index();
1570 }
1571
1572 bool LinkedConcreteMethodFinder::is_concrete_klass(InstanceKlass* ik) {
1573 if (!Dependencies::is_concrete_klass(ik)) {
1574 return false; // not concrete
1575 }
1576 if (ik->is_interface()) {
1577 return false; // interfaces aren't concrete
1578 }
1579 if (!ik->is_linked()) {
1580 return false; // not yet linked classes don't have instances
1581 }
1582 return true;
1583 }
1584
1585 #ifdef ASSERT
1586 // Assert that m is inherited into ctxk, without intervening overrides.
1587 // (May return true even if this is not true, in corner cases where we punt.)
1588 bool Dependencies::verify_method_context(InstanceKlass* ctxk, Method* m) {
1589 if (m->is_private()) {
1590 return false; // Quick lose. Should not happen.
1591 }
1592 if (m->method_holder() == ctxk) {
1593 return true; // Quick win.
1594 }
1595 if (!(m->is_public() || m->is_protected())) {
1596 // The override story is complex when packages get involved.
1597 return true; // Must punt the assertion to true.
1598 }
1599 Method* lm = ctxk->lookup_method(m->name(), m->signature());
1600 if (lm == nullptr) {
1601 // It might be an interface method
1602 lm = ctxk->lookup_method_in_ordered_interfaces(m->name(), m->signature());
1603 }
1604 if (lm == m) {
1605 // Method m is inherited into ctxk.
1606 return true;
1607 }
1608 if (lm != nullptr) {
1609 if (!(lm->is_public() || lm->is_protected())) {
1610 // Method is [package-]private, so the override story is complex.
1611 return true; // Must punt the assertion to true.
1612 }
1613 if (lm->is_static()) {
1614 // Static methods don't override non-static so punt
1615 return true;
1616 }
1617 if (!Dependencies::is_concrete_method(lm, ctxk) &&
1618 !Dependencies::is_concrete_method(m, ctxk)) {
1619 // They are both non-concrete
1620 if (lm->method_holder()->is_subtype_of(m->method_holder())) {
1621 // Method m is overridden by lm, but both are non-concrete.
1622 return true;
1623 }
1624 if (lm->method_holder()->is_interface() && m->method_holder()->is_interface() &&
1625 ctxk->is_subtype_of(m->method_holder()) && ctxk->is_subtype_of(lm->method_holder())) {
1626 // Interface method defined in multiple super interfaces
1627 return true;
1628 }
1629 }
1630 }
1631 ResourceMark rm;
1632 tty->print_cr("Dependency method not found in the associated context:");
1633 tty->print_cr(" context = %s", ctxk->external_name());
1634 tty->print( " method = "); m->print_short_name(tty); tty->cr();
1635 if (lm != nullptr) {
1636 tty->print( " found = "); lm->print_short_name(tty); tty->cr();
1637 }
1638 return false;
1639 }
1640 #endif // ASSERT
1641
1642 bool Dependencies::is_concrete_klass(Klass* k) {
1643 if (k->is_abstract()) return false;
1644 // %%% We could treat classes which are concrete but
1645 // have not yet been instantiated as virtually abstract.
1646 // This would require a deoptimization barrier on first instantiation.
1647 //if (k->is_not_instantiated()) return false;
1648 return true;
1649 }
1650
1651 bool Dependencies::is_concrete_method(Method* m, Klass* k) {
1652 // nullptr is not a concrete method.
1653 if (m == nullptr) {
1654 return false;
1655 }
1656 // Statics are irrelevant to virtual call sites.
1657 if (m->is_static()) {
1658 return false;
1659 }
1660 // Abstract methods are not concrete.
1661 if (m->is_abstract()) {
1662 return false;
1663 }
1664 // Overpass (error) methods are not concrete if k is abstract.
1665 if (m->is_overpass() && k != nullptr) {
1666 return !k->is_abstract();
1667 }
1668 // Note "true" is conservative answer: overpass clause is false if k == nullptr,
1669 // implies return true if answer depends on overpass clause.
1670 return true;
1671 }
1672
1673 Klass* Dependencies::find_finalizable_subclass(InstanceKlass* ik) {
1674 for (ClassHierarchyIterator iter(ik); !iter.done(); iter.next()) {
1675 Klass* sub = iter.klass();
1676 if (sub->has_finalizer() && !sub->is_interface()) {
1677 return sub;
1678 }
1679 }
1680 return nullptr; // not found
1681 }
1682
1683 bool Dependencies::is_concrete_klass(ciInstanceKlass* k) {
1684 if (k->is_abstract()) return false;
1685 // We could also return false if k does not yet appear to be
1686 // instantiated, if the VM version supports this distinction also.
1687 //if (k->is_not_instantiated()) return false;
1688 return true;
1689 }
1690
1691 bool Dependencies::has_finalizable_subclass(ciInstanceKlass* k) {
1692 return k->has_finalizable_subclass();
1693 }
1694
1695 // Any use of the contents (bytecodes) of a method must be
1696 // marked by an "evol_method" dependency, if those contents
1697 // can change. (Note: A method is always dependent on itself.)
1698 Klass* Dependencies::check_evol_method(Method* m) {
1699 assert(must_be_in_vm(), "raw oops here");
1700 // Did somebody do a JVMTI RedefineClasses while our backs were turned?
1701 // Or is there a now a breakpoint?
1702 // (Assumes compiled code cannot handle bkpts; change if UseFastBreakpoints.)
1703 if (m->is_old() || m->number_of_breakpoints() > 0) {
1704 return m->method_holder();
1705 } else {
1706 return nullptr;
1707 }
1708 }
1709
1710 Klass* Dependencies::check_mismatch_calling_convention(Method* m) {
1711 assert(must_be_in_vm(), "raw oops here");
1712 if (m->mismatch()) {
1713 return m->method_holder();
1714 } else {
1715 return nullptr;
1716 }
1717 }
1718
1719 // This is a strong assertion: It is that the given type
1720 // has no subtypes whatever. It is most useful for
1721 // optimizing checks on reflected types or on array types.
1722 // (Checks on types which are derived from real instances
1723 // can be optimized more strongly than this, because we
1724 // know that the checked type comes from a concrete type,
1725 // and therefore we can disregard abstract types.)
1726 Klass* Dependencies::check_leaf_type(InstanceKlass* ctxk) {
1727 assert(must_be_in_vm(), "raw oops here");
1728 assert_locked_or_safepoint(Compile_lock);
1729 Klass* sub = ctxk->subklass();
1730 if (sub != nullptr) {
1731 return sub;
1732 } else if (ctxk->nof_implementors() != 0) {
1733 // if it is an interface, it must be unimplemented
1734 // (if it is not an interface, nof_implementors is always zero)
1735 InstanceKlass* impl = ctxk->implementor();
1736 assert(impl != nullptr, "must be set");
1737 return impl;
1738 } else {
1739 return nullptr;
1740 }
1741 }
1742
1743 // Test the assertion that conck is the only concrete subtype* of ctxk.
1744 // The type conck itself is allowed to have have further concrete subtypes.
1745 // This allows the compiler to narrow occurrences of ctxk by conck,
1746 // when dealing with the types of actual instances.
1747 Klass* Dependencies::check_abstract_with_unique_concrete_subtype(InstanceKlass* ctxk,
1748 Klass* conck,
1749 NewKlassDepChange* changes) {
1750 ConcreteSubtypeFinder wf(conck);
1751 Klass* k = wf.find_witness(ctxk, changes);
1752 return k;
1753 }
1754
1755
1756 // Find the unique concrete proper subtype of ctxk, or nullptr if there
1757 // is more than one concrete proper subtype. If there are no concrete
1758 // proper subtypes, return ctxk itself, whether it is concrete or not.
1759 // The returned subtype is allowed to have have further concrete subtypes.
1760 // That is, return CC1 for CX > CC1 > CC2, but nullptr for CX > { CC1, CC2 }.
1761 Klass* Dependencies::find_unique_concrete_subtype(InstanceKlass* ctxk) {
1762 ConcreteSubtypeFinder wf(ctxk); // Ignore ctxk when walking.
1763 wf.record_witnesses(1); // Record one other witness when walking.
1764 Klass* wit = wf.find_witness(ctxk);
1765 if (wit != nullptr) return nullptr; // Too many witnesses.
1766 Klass* conck = wf.participant(0);
1767 if (conck == nullptr) {
1768 return ctxk; // Return ctxk as a flag for "no subtypes".
1769 } else {
1770 #ifndef PRODUCT
1771 // Make sure the dependency mechanism will pass this discovery:
1772 if (VerifyDependencies) {
1773 // Turn off dependency tracing while actually testing deps.
1774 FlagSetting fs(_verify_in_progress, true);
1775 if (!Dependencies::is_concrete_klass(ctxk)) {
1776 guarantee(nullptr == (void *)
1777 check_abstract_with_unique_concrete_subtype(ctxk, conck),
1778 "verify dep.");
1779 }
1780 }
1781 #endif //PRODUCT
1782 return conck;
1783 }
1784 }
1785
1786 // Try to determine whether root method in some context is concrete or not based on the information about the unique method
1787 // in that context. It exploits the fact that concrete root method is always inherited into the context when there's a unique method.
1788 // Hence, unique method holder is always a supertype of the context class when root method is concrete.
1789 // Examples for concrete_root_method
1790 // C (C.m uniqm)
1791 // |
1792 // CX (ctxk) uniqm is inherited into context.
1793 //
1794 // CX (ctxk) (CX.m uniqm) here uniqm is defined in ctxk.
1795 // Examples for !concrete_root_method
1796 // CX (ctxk)
1797 // |
1798 // C (C.m uniqm) uniqm is in subtype of ctxk.
1799 bool Dependencies::is_concrete_root_method(Method* uniqm, InstanceKlass* ctxk) {
1800 if (uniqm == nullptr) {
1801 return false; // match Dependencies::is_concrete_method() behavior
1802 }
1803 // Theoretically, the "direction" of subtype check matters here.
1804 // On one hand, in case of interface context with a single implementor, uniqm can be in a superclass of the implementor which
1805 // is not related to context class.
1806 // On another hand, uniqm could come from an interface unrelated to the context class, but right now it is not possible:
1807 // it is required that uniqm->method_holder() is the participant (uniqm->method_holder() <: ctxk), hence a default method
1808 // can't be used as unique.
1809 if (ctxk->is_interface()) {
1810 InstanceKlass* implementor = ctxk->implementor();
1811 assert(implementor != ctxk, "single implementor only"); // should have been invalidated earlier
1812 ctxk = implementor;
1813 }
1814 InstanceKlass* holder = uniqm->method_holder();
1815 assert(!holder->is_interface(), "no default methods allowed");
1816 assert(ctxk->is_subclass_of(holder) || holder->is_subclass_of(ctxk), "not related");
1817 return ctxk->is_subclass_of(holder);
1818 }
1819
1820 // If a class (or interface) has a unique concrete method uniqm, return nullptr.
1821 // Otherwise, return a class that contains an interfering method.
1822 Klass* Dependencies::check_unique_concrete_method(InstanceKlass* ctxk,
1823 Method* uniqm,
1824 NewKlassDepChange* changes) {
1825 ConcreteMethodFinder wf(uniqm, uniqm->method_holder());
1826 Klass* k = wf.find_witness(ctxk, changes);
1827 if (k != nullptr) {
1828 return k;
1829 }
1830 if (!Dependencies::is_concrete_root_method(uniqm, ctxk) || changes != nullptr) {
1831 Klass* conck = find_witness_AME(ctxk, uniqm, changes);
1832 if (conck != nullptr) {
1833 // Found a concrete subtype 'conck' which does not override abstract root method.
1834 return conck;
1835 }
1836 }
1837 return nullptr;
1838 }
1839
1840 Klass* Dependencies::check_unique_implementor(InstanceKlass* ctxk, Klass* uniqk, NewKlassDepChange* changes) {
1841 assert(ctxk->is_interface(), "sanity");
1842 assert(ctxk->nof_implementors() > 0, "no implementors");
1843 if (ctxk->nof_implementors() == 1) {
1844 assert(ctxk->implementor() == uniqk, "sanity");
1845 return nullptr;
1846 }
1847 return ctxk; // no unique implementor
1848 }
1849
1850 // Search for AME.
1851 // There are two version of checks.
1852 // 1) Spot checking version(Classload time). Newly added class is checked for AME.
1853 // Checks whether abstract/overpass method is inherited into/declared in newly added concrete class.
1854 // 2) Compile time analysis for abstract/overpass(abstract klass) root_m. The non uniqm subtrees are checked for concrete classes.
1855 Klass* Dependencies::find_witness_AME(InstanceKlass* ctxk, Method* m, KlassDepChange* changes) {
1856 if (m != nullptr) {
1857 if (changes != nullptr) {
1858 // Spot checking version.
1859 ConcreteMethodFinder wf(m);
1860 Klass* new_type = changes->as_new_klass_change()->new_type();
1861 if (wf.witnessed_reabstraction_in_supers(new_type)) {
1862 return new_type;
1863 }
1864 } else {
1865 // Note: It is required that uniqm->method_holder() is the participant (see ClassHierarchyWalker::found_method()).
1866 ConcreteSubtypeFinder wf(m->method_holder());
1867 Klass* conck = wf.find_witness(ctxk);
1868 if (conck != nullptr) {
1869 Method* cm = InstanceKlass::cast(conck)->find_instance_method(m->name(), m->signature(), Klass::PrivateLookupMode::skip);
1870 if (!Dependencies::is_concrete_method(cm, conck)) {
1871 return conck;
1872 }
1873 }
1874 }
1875 }
1876 return nullptr;
1877 }
1878
1879 // This function is used by find_unique_concrete_method(non vtable based)
1880 // to check whether subtype method overrides the base method.
1881 static bool overrides(Method* sub_m, Method* base_m) {
1882 assert(base_m != nullptr, "base method should be non null");
1883 if (sub_m == nullptr) {
1884 return false;
1885 }
1886 /**
1887 * If base_m is public or protected then sub_m always overrides.
1888 * If base_m is !public, !protected and !private (i.e. base_m is package private)
1889 * then sub_m should be in the same package as that of base_m.
1890 * For package private base_m this is conservative approach as it allows only subset of all allowed cases in
1891 * the jvm specification.
1892 **/
1893 if (base_m->is_public() || base_m->is_protected() ||
1894 base_m->method_holder()->is_same_class_package(sub_m->method_holder())) {
1895 return true;
1896 }
1897 return false;
1898 }
1899
1900 // Find the set of all non-abstract methods under ctxk that match m.
1901 // (The method m must be defined or inherited in ctxk.)
1902 // Include m itself in the set, unless it is abstract.
1903 // If this set has exactly one element, return that element.
1904 Method* Dependencies::find_unique_concrete_method(InstanceKlass* ctxk, Method* m, Klass** participant) {
1905 // Return nullptr if m is marked old; must have been a redefined method.
1906 if (m->is_old()) {
1907 return nullptr;
1908 }
1909 if (m->is_default_method()) {
1910 return nullptr; // not supported
1911 }
1912 assert(verify_method_context(ctxk, m), "proper context");
1913 ConcreteMethodFinder wf(m);
1914 wf.record_witnesses(1);
1915 Klass* wit = wf.find_witness(ctxk);
1916 if (wit != nullptr) return nullptr; // Too many witnesses.
1917 Method* fm = wf.found_method(0); // Will be nullptr if num_parts == 0.
1918 if (participant != nullptr) {
1919 (*participant) = wf.participant(0);
1920 }
1921 if (!Dependencies::is_concrete_method(fm, nullptr)) {
1922 fm = nullptr; // ignore abstract methods
1923 }
1924 if (Dependencies::is_concrete_method(m, ctxk)) {
1925 if (fm == nullptr) {
1926 // It turns out that m was always the only implementation.
1927 fm = m;
1928 } else if (fm != m) {
1929 // Two conflicting implementations after all.
1930 // (This can happen if m is inherited into ctxk and fm overrides it.)
1931 return nullptr;
1932 }
1933 } else if (Dependencies::find_witness_AME(ctxk, fm) != nullptr) {
1934 // Found a concrete subtype which does not override abstract root method.
1935 return nullptr;
1936 } else if (!overrides(fm, m)) {
1937 // Found method doesn't override abstract root method.
1938 return nullptr;
1939 }
1940 assert(Dependencies::is_concrete_root_method(fm, ctxk) == Dependencies::is_concrete_method(m, ctxk), "mismatch");
1941 #ifndef PRODUCT
1942 // Make sure the dependency mechanism will pass this discovery:
1943 if (VerifyDependencies && fm != nullptr) {
1944 guarantee(nullptr == (void *)check_unique_concrete_method(ctxk, fm),
1945 "verify dep.");
1946 }
1947 #endif //PRODUCT
1948 return fm;
1949 }
1950
1951 // If a class (or interface) has a unique concrete method uniqm, return nullptr.
1952 // Otherwise, return a class that contains an interfering method.
1953 Klass* Dependencies::check_unique_concrete_method(InstanceKlass* ctxk,
1954 Method* uniqm,
1955 Klass* resolved_klass,
1956 Method* resolved_method,
1957 KlassDepChange* changes) {
1958 assert(!ctxk->is_interface() || ctxk == resolved_klass, "sanity");
1959 assert(!resolved_method->can_be_statically_bound() || resolved_method == uniqm, "sanity");
1960 assert(resolved_klass->is_subtype_of(resolved_method->method_holder()), "sanity");
1961
1962 if (!InstanceKlass::cast(resolved_klass)->is_linked() ||
1963 !resolved_method->method_holder()->is_linked() ||
1964 resolved_method->can_be_statically_bound()) {
1965 // Dependency is redundant, but benign. Just keep it to avoid unnecessary recompilation.
1966 return nullptr; // no vtable index available
1967 }
1968
1969 LinkedConcreteMethodFinder mf(InstanceKlass::cast(resolved_klass), resolved_method, uniqm);
1970 return mf.find_witness(ctxk, changes);
1971 }
1972
1973 // Find the set of all non-abstract methods under ctxk that match m.
1974 // (The method m must be defined or inherited in ctxk.)
1975 // Include m itself in the set, unless it is abstract.
1976 // If this set has exactly one element, return that element.
1977 // Not yet linked subclasses of ctxk are ignored since they don't have any instances yet.
1978 // Additionally, resolved_klass and resolved_method complete the description of the call site being analyzed.
1979 Method* Dependencies::find_unique_concrete_method(InstanceKlass* ctxk, Method* m, Klass* resolved_klass, Method* resolved_method) {
1980 // Return nullptr if m is marked old; must have been a redefined method.
1981 if (m->is_old()) {
1982 return nullptr;
1983 }
1984 if (!InstanceKlass::cast(resolved_klass)->is_linked() ||
1985 !resolved_method->method_holder()->is_linked() ||
1986 resolved_method->can_be_statically_bound()) {
1987 return m; // nothing to do: no witness under ctxk
1988 }
1989 LinkedConcreteMethodFinder wf(InstanceKlass::cast(resolved_klass), resolved_method);
1990 assert(Dependencies::verify_method_context(ctxk, m), "proper context");
1991 wf.record_witnesses(1);
1992 Klass* wit = wf.find_witness(ctxk);
1993 if (wit != nullptr) {
1994 return nullptr; // Too many witnesses.
1995 }
1996 // p == nullptr when no participants are found (wf.num_participants() == 0).
1997 // fm == nullptr case has 2 meanings:
1998 // * when p == nullptr: no method found;
1999 // * when p != nullptr: AbstractMethodError-throwing method found.
2000 // Also, found method should always be accompanied by a participant class.
2001 Klass* p = wf.participant(0);
2002 Method* fm = wf.found_method(0);
2003 assert(fm == nullptr || p != nullptr, "no participant");
2004 // Normalize all error-throwing cases to nullptr.
2005 if (fm == Universe::throw_illegal_access_error() ||
2006 fm == Universe::throw_no_such_method_error() ||
2007 !Dependencies::is_concrete_method(fm, p)) {
2008 fm = nullptr; // error-throwing method
2009 }
2010 if (Dependencies::is_concrete_method(m, ctxk)) {
2011 if (p == nullptr) {
2012 // It turns out that m was always the only implementation.
2013 assert(fm == nullptr, "sanity");
2014 fm = m;
2015 }
2016 }
2017 #ifndef PRODUCT
2018 // Make sure the dependency mechanism will pass this discovery:
2019 if (VerifyDependencies && fm != nullptr) {
2020 guarantee(nullptr == check_unique_concrete_method(ctxk, fm, resolved_klass, resolved_method),
2021 "verify dep.");
2022 }
2023 #endif // PRODUCT
2024 assert(fm == nullptr || !fm->is_abstract(), "sanity");
2025 // Old CHA conservatively reports concrete methods in abstract classes
2026 // irrespective of whether they have concrete subclasses or not.
2027 // Also, abstract root method case is not fully supported.
2028 #ifdef ASSERT
2029 Klass* uniqp = nullptr;
2030 Method* uniqm = Dependencies::find_unique_concrete_method(ctxk, m, &uniqp);
2031 assert(uniqm == nullptr || uniqm == fm ||
2032 m->is_abstract() ||
2033 uniqm->method_holder()->is_abstract() ||
2034 (fm == nullptr && uniqm != nullptr && uniqp != nullptr && !InstanceKlass::cast(uniqp)->is_linked()),
2035 "sanity");
2036 #endif // ASSERT
2037 return fm;
2038 }
2039
2040 Klass* Dependencies::check_has_no_finalizable_subclasses(InstanceKlass* ctxk, NewKlassDepChange* changes) {
2041 InstanceKlass* search_at = ctxk;
2042 if (changes != nullptr) {
2043 search_at = changes->new_type(); // just look at the new bit
2044 }
2045 return find_finalizable_subclass(search_at);
2046 }
2047
2048 Klass* Dependencies::check_call_site_target_value(oop call_site, oop method_handle, CallSiteDepChange* changes) {
2049 assert(call_site != nullptr, "sanity");
2050 assert(method_handle != nullptr, "sanity");
2051 assert(call_site->is_a(vmClasses::CallSite_klass()), "sanity");
2052
2053 if (changes == nullptr) {
2054 // Validate all CallSites
2055 if (java_lang_invoke_CallSite::target(call_site) != method_handle)
2056 return call_site->klass(); // assertion failed
2057 } else {
2058 // Validate the given CallSite
2059 if (call_site == changes->call_site() && java_lang_invoke_CallSite::target(call_site) != changes->method_handle()) {
2060 assert(method_handle != changes->method_handle(), "must be");
2061 return call_site->klass(); // assertion failed
2062 }
2063 }
2064 return nullptr; // assertion still valid
2065 }
2066
2067 void Dependencies::DepStream::trace_and_log_witness(Klass* witness) {
2068 if (_verify_in_progress) return; // don't log
2069 if (witness != nullptr) {
2070 LogTarget(Debug, dependencies) lt;
2071 if (lt.is_enabled()) {
2072 LogStream ls(<);
2073 print_dependency(&ls, witness, /*verbose=*/ true);
2074 }
2075 // The following is a no-op unless logging is enabled:
2076 log_dependency(witness);
2077 }
2078 }
2079
2080 Klass* Dependencies::DepStream::check_new_klass_dependency(NewKlassDepChange* changes) {
2081 assert_locked_or_safepoint(Compile_lock);
2082 Dependencies::check_valid_dependency_type(type());
2083
2084 Klass* witness = nullptr;
2085 switch (type()) {
2086 case evol_method:
2087 witness = check_evol_method(method_argument(0));
2088 break;
2089 case mismatch_calling_convention:
2090 witness = check_mismatch_calling_convention(method_argument(0));
2091 break;
2092 case leaf_type:
2093 witness = check_leaf_type(context_type());
2094 break;
2095 case abstract_with_unique_concrete_subtype:
2096 witness = check_abstract_with_unique_concrete_subtype(context_type(), type_argument(1), changes);
2097 break;
2098 case unique_concrete_method_2:
2099 witness = check_unique_concrete_method(context_type(), method_argument(1), changes);
2100 break;
2101 case unique_concrete_method_4:
2102 witness = check_unique_concrete_method(context_type(), method_argument(1), type_argument(2), method_argument(3), changes);
2103 break;
2104 case unique_implementor:
2105 witness = check_unique_implementor(context_type(), type_argument(1), changes);
2106 break;
2107 case no_finalizable_subclasses:
2108 witness = check_has_no_finalizable_subclasses(context_type(), changes);
2109 break;
2110 default:
2111 witness = nullptr;
2112 break;
2113 }
2114 trace_and_log_witness(witness);
2115 return witness;
2116 }
2117
2118 Klass* Dependencies::DepStream::check_klass_init_dependency(KlassInitDepChange* changes) {
2119 assert_locked_or_safepoint(Compile_lock);
2120 Dependencies::check_valid_dependency_type(type());
2121
2122 // No new types added. Only unique_concrete_method_4 is sensitive to class initialization changes.
2123 Klass* witness = nullptr;
2124 switch (type()) {
2125 case unique_concrete_method_4:
2126 witness = check_unique_concrete_method(context_type(), method_argument(1), type_argument(2), method_argument(3), changes);
2127 break;
2128 default:
2129 witness = nullptr;
2130 break;
2131 }
2132 trace_and_log_witness(witness);
2133 return witness;
2134 }
2135
2136 Klass* Dependencies::DepStream::check_klass_dependency(KlassDepChange* changes) {
2137 assert_locked_or_safepoint(Compile_lock);
2138 Dependencies::check_valid_dependency_type(type());
2139
2140 if (changes != nullptr) {
2141 if (changes->is_klass_init_change()) {
2142 return check_klass_init_dependency(changes->as_klass_init_change());
2143 } else {
2144 return check_new_klass_dependency(changes->as_new_klass_change());
2145 }
2146 } else {
2147 Klass* witness = check_new_klass_dependency(nullptr);
2148 // check_klass_init_dependency duplicates check_new_klass_dependency checks when class hierarchy change info is absent.
2149 assert(witness != nullptr || check_klass_init_dependency(nullptr) == nullptr, "missed dependency");
2150 return witness;
2151 }
2152 }
2153
2154 Klass* Dependencies::DepStream::check_call_site_dependency(CallSiteDepChange* changes) {
2155 assert_locked_or_safepoint(Compile_lock);
2156 Dependencies::check_valid_dependency_type(type());
2157
2158 Klass* witness = nullptr;
2159 switch (type()) {
2160 case call_site_target_value:
2161 witness = check_call_site_target_value(argument_oop(0), argument_oop(1), changes);
2162 break;
2163 default:
2164 witness = nullptr;
2165 break;
2166 }
2167 trace_and_log_witness(witness);
2168 return witness;
2169 }
2170
2171
2172 Klass* Dependencies::DepStream::spot_check_dependency_at(DepChange& changes) {
2173 // Handle klass dependency
2174 if (changes.is_klass_change() && changes.as_klass_change()->involves_context(context_type()))
2175 return check_klass_dependency(changes.as_klass_change());
2176
2177 // Handle CallSite dependency
2178 if (changes.is_call_site_change())
2179 return check_call_site_dependency(changes.as_call_site_change());
2180
2181 // irrelevant dependency; skip it
2182 return nullptr;
2183 }
2184
2185
2186 void DepChange::print() { print_on(tty); }
2187
2188 void DepChange::print_on(outputStream* st) {
2189 int nsup = 0, nint = 0;
2190 for (ContextStream str(*this); str.next(); ) {
2191 InstanceKlass* k = str.klass();
2192 switch (str.change_type()) {
2193 case Change_new_type:
2194 st->print_cr(" dependee = %s", k->external_name());
2195 break;
2196 case Change_new_sub:
2197 if (!WizardMode) {
2198 ++nsup;
2199 } else {
2200 st->print_cr(" context super = %s", k->external_name());
2201 }
2202 break;
2203 case Change_new_impl:
2204 if (!WizardMode) {
2205 ++nint;
2206 } else {
2207 st->print_cr(" context interface = %s", k->external_name());
2208 }
2209 break;
2210 default:
2211 break;
2212 }
2213 }
2214 if (nsup + nint != 0) {
2215 st->print_cr(" context supers = %d, interfaces = %d", nsup, nint);
2216 }
2217 }
2218
2219 void DepChange::ContextStream::start() {
2220 InstanceKlass* type = (_changes.is_klass_change() ? _changes.as_klass_change()->type() : (InstanceKlass*) nullptr);
2221 _change_type = (type == nullptr ? NO_CHANGE : Start_Klass);
2222 _klass = type;
2223 _ti_base = nullptr;
2224 _ti_index = 0;
2225 _ti_limit = 0;
2226 }
2227
2228 bool DepChange::ContextStream::next() {
2229 switch (_change_type) {
2230 case Start_Klass: // initial state; _klass is the new type
2231 _ti_base = _klass->transitive_interfaces();
2232 _ti_index = 0;
2233 _change_type = Change_new_type;
2234 return true;
2235 case Change_new_type:
2236 // fall through:
2237 _change_type = Change_new_sub;
2238 case Change_new_sub:
2239 // 6598190: brackets workaround Sun Studio C++ compiler bug 6629277
2240 {
2241 _klass = _klass->java_super();
2242 if (_klass != nullptr) {
2243 return true;
2244 }
2245 }
2246 // else set up _ti_limit and fall through:
2247 _ti_limit = (_ti_base == nullptr) ? 0 : _ti_base->length();
2248 _change_type = Change_new_impl;
2249 case Change_new_impl:
2250 if (_ti_index < _ti_limit) {
2251 _klass = _ti_base->at(_ti_index++);
2252 return true;
2253 }
2254 // fall through:
2255 _change_type = NO_CHANGE; // iterator is exhausted
2256 case NO_CHANGE:
2257 break;
2258 default:
2259 ShouldNotReachHere();
2260 }
2261 return false;
2262 }
2263
2264 void KlassDepChange::initialize() {
2265 // entire transaction must be under this lock:
2266 assert_lock_strong(Compile_lock);
2267
2268 // Mark all dependee and all its superclasses
2269 // Mark transitive interfaces
2270 for (ContextStream str(*this); str.next(); ) {
2271 InstanceKlass* d = str.klass();
2272 assert(!d->is_marked_dependent(), "checking");
2273 d->set_is_marked_dependent(true);
2274 }
2275 }
2276
2277 KlassDepChange::~KlassDepChange() {
2278 // Unmark all dependee and all its superclasses
2279 // Unmark transitive interfaces
2280 for (ContextStream str(*this); str.next(); ) {
2281 InstanceKlass* d = str.klass();
2282 d->set_is_marked_dependent(false);
2283 }
2284 }
2285
2286 bool KlassDepChange::involves_context(Klass* k) {
2287 if (k == nullptr || !k->is_instance_klass()) {
2288 return false;
2289 }
2290 InstanceKlass* ik = InstanceKlass::cast(k);
2291 bool is_contained = ik->is_marked_dependent();
2292 assert(is_contained == type()->is_subtype_of(k),
2293 "correct marking of potential context types");
2294 return is_contained;
2295 }
2296
2297 void Dependencies::print_statistics() {
2298 AbstractClassHierarchyWalker::print_statistics();
2299 }
2300
2301 void AbstractClassHierarchyWalker::print_statistics() {
2302 if (UsePerfData) {
2303 jlong deps_find_witness_calls = _perf_find_witness_anywhere_calls_count->get_value();
2304 jlong deps_find_witness_steps = _perf_find_witness_anywhere_steps_count->get_value();
2305 jlong deps_find_witness_singles = _perf_find_witness_in_calls_count->get_value();
2306
2307 ttyLocker ttyl;
2308 tty->print_cr("Dependency check (find_witness) "
2309 "calls=" JLONG_FORMAT ", steps=" JLONG_FORMAT " (avg=%.1f), singles=" JLONG_FORMAT,
2310 deps_find_witness_calls,
2311 deps_find_witness_steps,
2312 (double)deps_find_witness_steps / deps_find_witness_calls,
2313 deps_find_witness_singles);
2314 if (xtty != nullptr) {
2315 xtty->elem("deps_find_witness calls='" JLONG_FORMAT "' steps='" JLONG_FORMAT "' singles='" JLONG_FORMAT "'",
2316 deps_find_witness_calls,
2317 deps_find_witness_steps,
2318 deps_find_witness_singles);
2319 }
2320 }
2321 }
2322
2323 CallSiteDepChange::CallSiteDepChange(Handle call_site, Handle method_handle) :
2324 _call_site(call_site),
2325 _method_handle(method_handle) {
2326 assert(_call_site()->is_a(vmClasses::CallSite_klass()), "must be");
2327 assert(_method_handle.is_null() || _method_handle()->is_a(vmClasses::MethodHandle_klass()), "must be");
2328 }
2329
2330 void dependencies_init() {
2331 AbstractClassHierarchyWalker::init();
2332 }