1 /*
2 * Copyright (c) 2005, 2026, 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 DEBUG_ONLY(_deps[end_marker] = nullptr);
69 for (int i = (int)FIRST_TYPE; i < (int)TYPE_LIMIT; i++) {
70 _deps[i] = new(arena) GrowableArray<ciBaseObject*>(arena, 10, 0, nullptr);
71 }
72 _content_bytes = nullptr;
73 _size_in_bytes = (size_t)-1;
74
75 assert(TYPE_LIMIT <= (1<<LG2_TYPE_LIMIT), "sanity");
76 }
77
78 void Dependencies::assert_evol_method(ciMethod* m) {
79 assert_common_1(evol_method, m);
80 }
81
82 void Dependencies::assert_mismatch_calling_convention(ciMethod* m) {
83 assert_common_1(mismatch_calling_convention, m);
84 }
85
86 void Dependencies::assert_leaf_type(ciKlass* ctxk) {
87 if (ctxk->is_array_klass()) {
88 // As a special case, support this assertion on an array type,
89 // which reduces to an assertion on its element type.
90 // Note that this cannot be done with assertions that
91 // relate to concreteness or abstractness.
92 ciType* elemt = ctxk->as_array_klass()->base_element_type();
93 if (!elemt->is_instance_klass()) return; // Ex: int[][]
94 ctxk = elemt->as_instance_klass();
95 //if (ctxk->is_final()) return; // Ex: String[][]
96 }
97 check_ctxk(ctxk);
98 assert_common_1(leaf_type, ctxk);
99 }
100
101 void Dependencies::assert_abstract_with_unique_concrete_subtype(ciKlass* ctxk, ciKlass* conck) {
102 check_ctxk_abstract(ctxk);
103 assert_common_2(abstract_with_unique_concrete_subtype, ctxk, conck);
104 }
105
106 void Dependencies::assert_unique_concrete_method(ciKlass* ctxk, ciMethod* uniqm, ciKlass* resolved_klass, ciMethod* resolved_method) {
107 check_ctxk(ctxk);
108 check_unique_method(ctxk, uniqm);
109 assert_common_4(unique_concrete_method, ctxk, uniqm, resolved_klass, resolved_method);
110 }
111
112 void Dependencies::assert_unique_implementor(ciInstanceKlass* ctxk, ciInstanceKlass* uniqk) {
113 check_ctxk(ctxk);
114 check_unique_implementor(ctxk, uniqk);
115 assert_common_2(unique_implementor, ctxk, uniqk);
116 }
117
118 void Dependencies::assert_has_no_finalizable_subclasses(ciKlass* ctxk) {
119 check_ctxk(ctxk);
120 assert_common_1(no_finalizable_subclasses, ctxk);
121 }
122
123 void Dependencies::assert_call_site_target_value(ciCallSite* call_site, ciMethodHandle* method_handle) {
124 assert_common_2(call_site_target_value, call_site, method_handle);
125 }
126
127 // Helper function. If we are adding a new dep. under ctxk2,
128 // try to find an old dep. under a broader* ctxk1. If there is
129 //
130 bool Dependencies::maybe_merge_ctxk(GrowableArray<ciBaseObject*>* deps,
131 int ctxk_i, ciKlass* ctxk2) {
132 ciKlass* ctxk1 = deps->at(ctxk_i)->as_metadata()->as_klass();
133 if (ctxk2->is_subtype_of(ctxk1)) {
134 return true; // success, and no need to change
135 } else if (ctxk1->is_subtype_of(ctxk2)) {
136 // new context class fully subsumes previous one
137 deps->at_put(ctxk_i, ctxk2);
138 return true;
139 } else {
140 return false;
141 }
142 }
143
144 void Dependencies::assert_common_1(DepType dept, ciBaseObject* x) {
145 assert(dep_args(dept) == 1, "sanity");
146 log_dependency(dept, x);
147 GrowableArray<ciBaseObject*>* deps = _deps[dept];
148
149 // see if the same (or a similar) dep is already recorded
150 if (note_dep_seen(dept, x)) {
151 assert(deps->find(x) >= 0, "sanity");
152 } else {
153 deps->append(x);
154 }
155 }
156
157 void Dependencies::assert_common_2(DepType dept,
158 ciBaseObject* x0, ciBaseObject* x1) {
159 assert(dep_args(dept) == 2, "sanity");
160 log_dependency(dept, x0, x1);
161 GrowableArray<ciBaseObject*>* deps = _deps[dept];
162
163 // see if the same (or a similar) dep is already recorded
164 bool has_ctxk = has_explicit_context_arg(dept);
165 if (has_ctxk) {
166 assert(dep_context_arg(dept) == 0, "sanity");
167 if (note_dep_seen(dept, x1)) {
168 // look in this bucket for redundant assertions
169 const int stride = 2;
170 for (int i = deps->length(); (i -= stride) >= 0; ) {
171 ciBaseObject* y1 = deps->at(i+1);
172 if (x1 == y1) { // same subject; check the context
173 if (maybe_merge_ctxk(deps, i+0, x0->as_metadata()->as_klass())) {
174 return;
175 }
176 }
177 }
178 }
179 } else {
180 bool dep_seen_x0 = note_dep_seen(dept, x0); // records x0 for future queries
181 bool dep_seen_x1 = note_dep_seen(dept, x1); // records x1 for future queries
182 if (dep_seen_x0 && dep_seen_x1) {
183 // look in this bucket for redundant assertions
184 const int stride = 2;
185 for (int i = deps->length(); (i -= stride) >= 0; ) {
186 ciBaseObject* y0 = deps->at(i+0);
187 ciBaseObject* y1 = deps->at(i+1);
188 if (x0 == y0 && x1 == y1) {
189 return;
190 }
191 }
192 }
193 }
194
195 // append the assertion in the correct bucket:
196 deps->append(x0);
197 deps->append(x1);
198 }
199
200 void Dependencies::assert_common_4(DepType dept,
201 ciKlass* ctxk, ciBaseObject* x1, ciBaseObject* x2, ciBaseObject* x3) {
202 assert(has_explicit_context_arg(dept), "sanity");
203 assert(dep_context_arg(dept) == 0, "sanity");
204 assert(dep_args(dept) == 4, "sanity");
205 log_dependency(dept, ctxk, x1, x2, x3);
206 GrowableArray<ciBaseObject*>* deps = _deps[dept];
207
208 // see if the same (or a similar) dep is already recorded
209 bool dep_seen_x1 = note_dep_seen(dept, x1); // records x1 for future queries
210 bool dep_seen_x2 = note_dep_seen(dept, x2); // records x2 for future queries
211 bool dep_seen_x3 = note_dep_seen(dept, x3); // records x3 for future queries
212 if (dep_seen_x1 && dep_seen_x2 && dep_seen_x3) {
213 // look in this bucket for redundant assertions
214 const int stride = 4;
215 for (int i = deps->length(); (i -= stride) >= 0; ) {
216 ciBaseObject* y1 = deps->at(i+1);
217 ciBaseObject* y2 = deps->at(i+2);
218 ciBaseObject* y3 = deps->at(i+3);
219 if (x1 == y1 && x2 == y2 && x3 == y3) { // same subjects; check the context
220 if (maybe_merge_ctxk(deps, i+0, ctxk)) {
221 return;
222 }
223 }
224 }
225 }
226 // append the assertion in the correct bucket:
227 deps->append(ctxk);
228 deps->append(x1);
229 deps->append(x2);
230 deps->append(x3);
231 }
232
233 /// Support for encoding dependencies into an nmethod:
234
235 void Dependencies::copy_to(nmethod* nm) {
236 address beg = nm->dependencies_begin();
237 address end = nm->dependencies_end();
238 guarantee(end - beg >= (ptrdiff_t) size_in_bytes(), "bad sizing");
239 (void)memcpy(beg, content_bytes(), size_in_bytes());
240 assert(size_in_bytes() % sizeof(HeapWord) == 0, "copy by words");
241 }
242
243 static int sort_dep(ciBaseObject** p1, ciBaseObject** p2, int narg) {
244 for (int i = 0; i < narg; i++) {
245 int diff = p1[i]->ident() - p2[i]->ident();
246 if (diff != 0) return diff;
247 }
248 return 0;
249 }
250 static int sort_dep_arg_1(ciBaseObject** p1, ciBaseObject** p2)
251 { return sort_dep(p1, p2, 1); }
252 static int sort_dep_arg_2(ciBaseObject** p1, ciBaseObject** p2)
253 { return sort_dep(p1, p2, 2); }
254 static int sort_dep_arg_3(ciBaseObject** p1, ciBaseObject** p2)
255 { return sort_dep(p1, p2, 3); }
256 static int sort_dep_arg_4(ciBaseObject** p1, ciBaseObject** p2)
257 { return sort_dep(p1, p2, 4); }
258
259 void Dependencies::sort_all_deps() {
260 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
261 DepType dept = (DepType)deptv;
262 GrowableArray<ciBaseObject*>* deps = _deps[dept];
263 if (deps->length() <= 1) continue;
264 switch (dep_args(dept)) {
265 case 1: deps->sort(sort_dep_arg_1, 1); break;
266 case 2: deps->sort(sort_dep_arg_2, 2); break;
267 case 3: deps->sort(sort_dep_arg_3, 3); break;
268 case 4: deps->sort(sort_dep_arg_4, 4); break;
269 default: ShouldNotReachHere(); break;
270 }
271 }
272 }
273
274 size_t Dependencies::estimate_size_in_bytes() {
275 size_t est_size = 100;
276 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
277 DepType dept = (DepType)deptv;
278 GrowableArray<ciBaseObject*>* deps = _deps[dept];
279 est_size += deps->length()*2; // tags and argument(s)
280 }
281 return est_size;
282 }
283
284 ciKlass* Dependencies::ctxk_encoded_as_null(DepType dept, ciBaseObject* x) {
285 switch (dept) {
286 case unique_concrete_method:
287 return x->as_metadata()->as_method()->holder();
288 default:
289 return nullptr; // let nullptr be nullptr
290 }
291 }
292
293 Klass* Dependencies::ctxk_encoded_as_null(DepType dept, Metadata* x) {
294 assert(must_be_in_vm(), "raw oops here");
295 switch (dept) {
296 case unique_concrete_method:
297 assert(x->is_method(), "sanity");
298 return ((Method*)x)->method_holder();
299 default:
300 return nullptr; // let nullptr be nullptr
301 }
302 }
303
304 void Dependencies::encode_content_bytes() {
305 sort_all_deps();
306
307 // cast is safe, no deps can overflow INT_MAX
308 CompressedWriteStream bytes((int)estimate_size_in_bytes());
309
310 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
311 DepType dept = (DepType)deptv;
312 GrowableArray<ciBaseObject*>* deps = _deps[dept];
313 if (deps->length() == 0) continue;
314 int stride = dep_args(dept);
315 int ctxkj = dep_context_arg(dept); // -1 if no context arg
316 assert(stride > 0, "sanity");
317 for (int i = 0; i < deps->length(); i += stride) {
318 jbyte code_byte = (jbyte)dept;
319 int skipj = -1;
320 if (ctxkj >= 0 && ctxkj+1 < stride) {
321 ciKlass* ctxk = deps->at(i+ctxkj+0)->as_metadata()->as_klass();
322 ciBaseObject* x = deps->at(i+ctxkj+1); // following argument
323 if (ctxk == ctxk_encoded_as_null(dept, x)) {
324 skipj = ctxkj; // we win: maybe one less oop to keep track of
325 code_byte |= default_context_type_bit;
326 }
327 }
328 bytes.write_byte(code_byte);
329 for (int j = 0; j < stride; j++) {
330 if (j == skipj) continue;
331 ciBaseObject* v = deps->at(i+j);
332 int idx;
333 if (v->is_object()) {
334 idx = _oop_recorder->find_index(v->as_object()->constant_encoding());
335 } else {
336 ciMetadata* meta = v->as_metadata();
337 idx = _oop_recorder->find_index(meta->constant_encoding());
338 }
339 bytes.write_int(idx);
340 }
341 }
342 }
343
344 // write a sentinel byte to mark the end
345 bytes.write_byte(end_marker);
346
347 // round it out to a word boundary
348 while (bytes.position() % sizeof(HeapWord) != 0) {
349 bytes.write_byte(end_marker);
350 }
351
352 // check whether the dept byte encoding really works
353 assert((jbyte)default_context_type_bit != 0, "byte overflow");
354
355 _content_bytes = bytes.buffer();
356 _size_in_bytes = bytes.position();
357 }
358
359
360 const char* Dependencies::_dep_name[TYPE_LIMIT] = {
361 "end_marker",
362 "evol_method",
363 "mismatch_calling_convention",
364 "leaf_type",
365 "abstract_with_unique_concrete_subtype",
366 "unique_concrete_method",
367 "unique_implementor",
368 "no_finalizable_subclasses",
369 "call_site_target_value"
370 };
371
372 int Dependencies::_dep_args[TYPE_LIMIT] = {
373 -1,// end_marker
374 1, // evol_method m
375 1, // mismatch_calling_convention m
376 1, // leaf_type ctxk
377 2, // abstract_with_unique_concrete_subtype ctxk, k
378 4, // unique_concrete_method ctxk, m, resolved_klass, resolved_method
379 2, // unique_implementor ctxk, implementor
380 1, // no_finalizable_subclasses ctxk
381 2 // call_site_target_value call_site, method_handle
382 };
383
384 const char* Dependencies::dep_name(Dependencies::DepType dept) {
385 if (!dept_in_mask(dept, all_types)) return "?bad-dep?";
386 return _dep_name[dept];
387 }
388
389 int Dependencies::dep_args(Dependencies::DepType dept) {
390 if (!dept_in_mask(dept, all_types)) return -1;
391 return _dep_args[dept];
392 }
393
394 void Dependencies::check_valid_dependency_type(DepType dept) {
395 guarantee(FIRST_TYPE <= dept && dept < TYPE_LIMIT, "invalid dependency type: %d", (int) dept);
396 }
397
398 Dependencies::DepType Dependencies::validate_dependencies(CompileTask* task, char** failure_detail) {
399 int klass_violations = 0;
400 DepType result = end_marker;
401 for (Dependencies::DepStream deps(this); deps.next(); ) {
402 Klass* witness = deps.check_dependency();
403 if (witness != nullptr) {
404 if (klass_violations == 0) {
405 result = deps.type();
406 if (failure_detail != nullptr && klass_violations == 0) {
407 // Use a fixed size buffer to prevent the string stream from
408 // resizing in the context of an inner resource mark.
409 char* buffer = NEW_RESOURCE_ARRAY(char, O_BUFLEN);
410 stringStream st(buffer, O_BUFLEN);
411 deps.print_dependency(&st, witness, true);
412 *failure_detail = st.as_string();
413 }
414 }
415 klass_violations++;
416 if (xtty == nullptr) {
417 // If we're not logging then a single violation is sufficient,
418 // otherwise we want to log all the dependences which were
419 // violated.
420 break;
421 }
422 }
423 }
424
425 return result;
426 }
427
428 // for the sake of the compiler log, print out current dependencies:
429 void Dependencies::log_all_dependencies() {
430 if (log() == nullptr) return;
431 ResourceMark rm;
432 for (int deptv = (int)FIRST_TYPE; deptv < (int)TYPE_LIMIT; deptv++) {
433 DepType dept = (DepType)deptv;
434 GrowableArray<ciBaseObject*>* deps = _deps[dept];
435 int deplen = deps->length();
436 if (deplen == 0) {
437 continue;
438 }
439 int stride = dep_args(dept);
440 GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(stride);
441 for (int i = 0; i < deps->length(); i += stride) {
442 for (int j = 0; j < stride; j++) {
443 // flush out the identities before printing
444 ciargs->push(deps->at(i+j));
445 }
446 write_dependency_to(log(), dept, ciargs);
447 ciargs->clear();
448 }
449 guarantee(deplen == deps->length(), "deps array cannot grow inside nested ResoureMark scope");
450 }
451 }
452
453 void Dependencies::write_dependency_to(CompileLog* log,
454 DepType dept,
455 GrowableArray<DepArgument>* args,
456 Klass* witness) {
457 if (log == nullptr) {
458 return;
459 }
460 ResourceMark rm;
461 ciEnv* env = ciEnv::current();
462 GrowableArray<ciBaseObject*>* ciargs = new GrowableArray<ciBaseObject*>(args->length());
463 for (GrowableArrayIterator<DepArgument> it = args->begin(); it != args->end(); ++it) {
464 DepArgument arg = *it;
465 if (arg.is_oop()) {
466 ciargs->push(env->get_object(arg.oop_value()));
467 } else {
468 ciargs->push(env->get_metadata(arg.metadata_value()));
469 }
470 }
471 int argslen = ciargs->length();
472 Dependencies::write_dependency_to(log, dept, ciargs, witness);
473 guarantee(argslen == ciargs->length(), "ciargs array cannot grow inside nested ResoureMark scope");
474 }
475
476 void Dependencies::write_dependency_to(CompileLog* log,
477 DepType dept,
478 GrowableArray<ciBaseObject*>* args,
479 Klass* witness) {
480 if (log == nullptr) {
481 return;
482 }
483 ResourceMark rm;
484 GrowableArray<int>* argids = new GrowableArray<int>(args->length());
485 for (GrowableArrayIterator<ciBaseObject*> it = args->begin(); it != args->end(); ++it) {
486 ciBaseObject* obj = *it;
487 if (obj->is_object()) {
488 argids->push(log->identify(obj->as_object()));
489 } else {
490 argids->push(log->identify(obj->as_metadata()));
491 }
492 }
493 if (witness != nullptr) {
494 log->begin_elem("dependency_failed");
495 } else {
496 log->begin_elem("dependency");
497 }
498 log->print(" type='%s'", dep_name(dept));
499 const int ctxkj = dep_context_arg(dept); // -1 if no context arg
500 if (ctxkj >= 0 && ctxkj < argids->length()) {
501 log->print(" ctxk='%d'", argids->at(ctxkj));
502 }
503 // write remaining arguments, if any.
504 for (int j = 0; j < argids->length(); j++) {
505 if (j == ctxkj) continue; // already logged
506 if (j == 1) {
507 log->print( " x='%d'", argids->at(j));
508 } else {
509 log->print(" x%d='%d'", j, argids->at(j));
510 }
511 }
512 if (witness != nullptr) {
513 log->object("witness", witness);
514 log->stamp();
515 }
516 log->end_elem();
517 }
518
519 void Dependencies::write_dependency_to(xmlStream* xtty,
520 DepType dept,
521 GrowableArray<DepArgument>* args,
522 Klass* witness) {
523 if (xtty == nullptr) {
524 return;
525 }
526 Thread* thread = Thread::current();
527 HandleMark rm(thread);
528 ttyLocker ttyl;
529 int ctxkj = dep_context_arg(dept); // -1 if no context arg
530 if (witness != nullptr) {
531 xtty->begin_elem("dependency_failed");
532 } else {
533 xtty->begin_elem("dependency");
534 }
535 xtty->print(" type='%s'", dep_name(dept));
536 if (ctxkj >= 0) {
537 xtty->object("ctxk", args->at(ctxkj).metadata_value());
538 }
539 // write remaining arguments, if any.
540 for (int j = 0; j < args->length(); j++) {
541 if (j == ctxkj) continue; // already logged
542 DepArgument arg = args->at(j);
543 if (j == 1) {
544 if (arg.is_oop()) {
545 xtty->object("x", Handle(thread, arg.oop_value()));
546 } else {
547 xtty->object("x", arg.metadata_value());
548 }
549 } else {
550 char xn[12];
551 os::snprintf_checked(xn, sizeof(xn), "x%d", j);
552 if (arg.is_oop()) {
553 xtty->object(xn, Handle(thread, arg.oop_value()));
554 } else {
555 xtty->object(xn, arg.metadata_value());
556 }
557 }
558 }
559 if (witness != nullptr) {
560 xtty->object("witness", witness);
561 xtty->stamp();
562 }
563 xtty->end_elem();
564 }
565
566 void Dependencies::print_dependency(DepType dept, GrowableArray<DepArgument>* args,
567 Klass* witness, outputStream* st) {
568 ResourceMark rm;
569 ttyLocker ttyl; // keep the following output all in one block
570 st->print_cr("%s of type %s",
571 (witness == nullptr)? "Dependency": "Failed dependency",
572 dep_name(dept));
573 // print arguments
574 int ctxkj = dep_context_arg(dept); // -1 if no context arg
575 for (int j = 0; j < args->length(); j++) {
576 DepArgument arg = args->at(j);
577 bool put_star = false;
578 if (arg.is_null()) continue;
579 const char* what;
580 if (j == ctxkj) {
581 assert(arg.is_metadata(), "must be");
582 what = "context";
583 put_star = !Dependencies::is_concrete_klass((Klass*)arg.metadata_value());
584 } else if (arg.is_method()) {
585 what = "method ";
586 put_star = !Dependencies::is_concrete_method((Method*)arg.metadata_value(), nullptr);
587 } else if (arg.is_klass()) {
588 what = "class ";
589 } else {
590 what = "object ";
591 }
592 st->print(" %s = %s", what, (put_star? "*": ""));
593 if (arg.is_klass()) {
594 st->print("%s", ((Klass*)arg.metadata_value())->external_name());
595 } else if (arg.is_method()) {
596 ((Method*)arg.metadata_value())->print_value_on(st);
597 } else if (arg.is_oop()) {
598 arg.oop_value()->print_value_on(st);
599 } else {
600 ShouldNotReachHere(); // Provide impl for this type.
601 }
602
603 st->cr();
604 }
605 if (witness != nullptr) {
606 bool put_star = !Dependencies::is_concrete_klass(witness);
607 st->print_cr(" witness = %s%s",
608 (put_star? "*": ""),
609 witness->external_name());
610 }
611 }
612
613 void Dependencies::DepStream::log_dependency(Klass* witness) {
614 if (_deps == nullptr && xtty == nullptr) return; // fast cutout for runtime
615 ResourceMark rm;
616 const int nargs = argument_count();
617 GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
618 for (int j = 0; j < nargs; j++) {
619 if (is_oop_argument(j)) {
620 args->push(argument_oop(j));
621 } else {
622 args->push(argument(j));
623 }
624 }
625 int argslen = args->length();
626 if (_deps != nullptr && _deps->log() != nullptr) {
627 if (ciEnv::current() != nullptr) {
628 Dependencies::write_dependency_to(_deps->log(), type(), args, witness);
629 } else {
630 // Treat the CompileLog as an xmlstream instead
631 Dependencies::write_dependency_to((xmlStream*)_deps->log(), type(), args, witness);
632 }
633 } else {
634 Dependencies::write_dependency_to(xtty, type(), args, witness);
635 }
636 guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
637 }
638
639 void Dependencies::DepStream::print_dependency(outputStream* st, Klass* witness, bool verbose) {
640 ResourceMark rm;
641 int nargs = argument_count();
642 GrowableArray<DepArgument>* args = new GrowableArray<DepArgument>(nargs);
643 for (int j = 0; j < nargs; j++) {
644 if (is_oop_argument(j)) {
645 args->push(argument_oop(j));
646 } else {
647 args->push(argument(j));
648 }
649 }
650 int argslen = args->length();
651 Dependencies::print_dependency(type(), args, witness, st);
652 if (verbose) {
653 if (_code != nullptr) {
654 st->print(" code: ");
655 _code->print_value_on(st);
656 st->cr();
657 }
658 }
659 guarantee(argslen == args->length(), "args array cannot grow inside nested ResoureMark scope");
660 }
661
662
663 /// Dependency stream support (decodes dependencies from an nmethod):
664
665 #ifdef ASSERT
666 void Dependencies::DepStream::initial_asserts(size_t byte_limit) {
667 assert(must_be_in_vm(), "raw oops here");
668 _byte_limit = byte_limit;
669 _type = undefined_dependency; // defeat "already at end" assert
670 assert((_code!=nullptr) + (_deps!=nullptr) == 1, "one or t'other");
671 }
672 #endif //ASSERT
673
674 bool Dependencies::DepStream::next() {
675 assert(_type != end_marker, "already at end");
676 if (_bytes.position() == 0 && _code != nullptr
677 && _code->dependencies_size() == 0) {
678 // Method has no dependencies at all.
679 return false;
680 }
681 int code_byte = (_bytes.read_byte() & 0xFF);
682 if (code_byte == end_marker) {
683 DEBUG_ONLY(_type = end_marker);
684 return false;
685 } else {
686 int ctxk_bit = (code_byte & Dependencies::default_context_type_bit);
687 code_byte -= ctxk_bit;
688 DepType dept = (DepType)code_byte;
689 _type = dept;
690 Dependencies::check_valid_dependency_type(dept);
691 int stride = _dep_args[dept];
692 assert(stride == dep_args(dept), "sanity");
693 int skipj = -1;
694 if (ctxk_bit != 0) {
695 skipj = 0; // currently the only context argument is at zero
696 assert(skipj == dep_context_arg(dept), "zero arg always ctxk");
697 }
698 for (int j = 0; j < stride; j++) {
699 _xi[j] = (j == skipj)? 0: _bytes.read_int();
700 }
701 DEBUG_ONLY(_xi[stride] = -1); // help detect overruns
702 return true;
703 }
704 }
705
706 inline Metadata* Dependencies::DepStream::recorded_metadata_at(int i) {
707 Metadata* o = nullptr;
708 if (_code != nullptr) {
709 o = _code->metadata_at(i);
710 } else {
711 o = _deps->oop_recorder()->metadata_at(i);
712 }
713 return o;
714 }
715
716 inline oop Dependencies::DepStream::recorded_oop_at(int i) {
717 return (_code != nullptr)
718 ? _code->oop_at(i)
719 : JNIHandles::resolve(_deps->oop_recorder()->oop_at(i));
720 }
721
722 Metadata* Dependencies::DepStream::argument(int i) {
723 Metadata* result = recorded_metadata_at(argument_index(i));
724
725 if (result == nullptr) { // Explicit context argument can be compressed
726 int ctxkj = dep_context_arg(type()); // -1 if no explicit context arg
727 if (ctxkj >= 0 && i == ctxkj && ctxkj+1 < argument_count()) {
728 result = ctxk_encoded_as_null(type(), argument(ctxkj+1));
729 }
730 }
731
732 assert(result == nullptr || result->is_klass() || result->is_method(), "must be");
733 return result;
734 }
735
736 /**
737 * Returns a unique identifier for each dependency argument.
738 */
739 uintptr_t Dependencies::DepStream::get_identifier(int i) {
740 if (is_oop_argument(i)) {
741 return (uintptr_t)(oopDesc*)argument_oop(i);
742 } else {
743 return (uintptr_t)argument(i);
744 }
745 }
746
747 oop Dependencies::DepStream::argument_oop(int i) {
748 oop result = recorded_oop_at(argument_index(i));
749 assert(oopDesc::is_oop_or_null(result), "must be");
750 return result;
751 }
752
753 InstanceKlass* Dependencies::DepStream::context_type() {
754 assert(must_be_in_vm(), "raw oops here");
755
756 // Most dependencies have an explicit context type argument.
757 {
758 int ctxkj = dep_context_arg(type()); // -1 if no explicit context arg
759 if (ctxkj >= 0) {
760 Metadata* k = argument(ctxkj);
761 assert(k != nullptr && k->is_klass(), "type check");
762 return InstanceKlass::cast((Klass*)k);
763 }
764 }
765
766 // Some dependencies are using the klass of the first object
767 // argument as implicit context type.
768 {
769 int ctxkj = dep_implicit_context_arg(type());
770 if (ctxkj >= 0) {
771 Klass* k = argument_oop(ctxkj)->klass();
772 assert(k != nullptr, "type check");
773 return InstanceKlass::cast(k);
774 }
775 }
776
777 // And some dependencies don't have a context type at all,
778 // e.g. evol_method.
779 return nullptr;
780 }
781
782 // ----------------- DependencySignature --------------------------------------
783 bool DependencySignature::equals(DependencySignature const& s1, DependencySignature const& s2) {
784 if ((s1.type() != s2.type()) || (s1.args_count() != s2.args_count())) {
785 return false;
786 }
787
788 for (int i = 0; i < s1.args_count(); i++) {
789 if (s1.arg(i) != s2.arg(i)) {
790 return false;
791 }
792 }
793 return true;
794 }
795
796 /// Checking dependencies
797
798 // This hierarchy walker inspects subtypes of a given type, trying to find a "bad" class which breaks a dependency.
799 // Such a class is called a "witness" to the broken dependency.
800 // While searching around, we ignore "participants", which are already known to the dependency.
801 class AbstractClassHierarchyWalker {
802 public:
803 enum { PARTICIPANT_LIMIT = 3 };
804
805 private:
806 // if non-zero, tells how many witnesses to convert to participants
807 uint _record_witnesses;
808
809 // special classes which are not allowed to be witnesses:
810 Klass* _participants[PARTICIPANT_LIMIT+1];
811 uint _num_participants;
812
813 #ifdef ASSERT
814 uint _nof_requests; // one-shot walker
815 #endif // ASSERT
816
817 static PerfCounter* _perf_find_witness_anywhere_calls_count;
818 static PerfCounter* _perf_find_witness_anywhere_steps_count;
819 static PerfCounter* _perf_find_witness_in_calls_count;
820
821 protected:
822 virtual Klass* find_witness_in(KlassDepChange& changes) = 0;
823 virtual Klass* find_witness_anywhere(InstanceKlass* context_type) = 0;
824
825 AbstractClassHierarchyWalker(Klass* participant) : _record_witnesses(0), _num_participants(0)
826 #ifdef ASSERT
827 , _nof_requests(0)
828 #endif // ASSERT
829 {
830 for (uint i = 0; i < PARTICIPANT_LIMIT+1; i++) {
831 _participants[i] = nullptr;
832 }
833 if (participant != nullptr) {
834 add_participant(participant);
835 }
836 }
837
838 bool is_participant(Klass* k) {
839 for (uint i = 0; i < _num_participants; i++) {
840 if (_participants[i] == k) {
841 return true;
842 }
843 }
844 return false;
845 }
846
847 bool record_witness(Klass* witness) {
848 if (_record_witnesses > 0) {
849 --_record_witnesses;
850 add_participant(witness);
851 return false; // not a witness
852 } else {
853 return true; // is a witness
854 }
855 }
856
857 class CountingClassHierarchyIterator : public ClassHierarchyIterator {
858 private:
859 jlong _nof_steps;
860 public:
861 CountingClassHierarchyIterator(InstanceKlass* root) : ClassHierarchyIterator(root), _nof_steps(0) {}
862
863 void next() {
864 _nof_steps++;
865 ClassHierarchyIterator::next();
866 }
867
868 ~CountingClassHierarchyIterator() {
869 if (UsePerfData) {
870 _perf_find_witness_anywhere_steps_count->inc(_nof_steps);
871 }
872 }
873 };
874
875 public:
876 uint num_participants() { return _num_participants; }
877 Klass* participant(uint n) {
878 assert(n <= _num_participants, "oob");
879 if (n < _num_participants) {
880 return _participants[n];
881 } else {
882 return nullptr;
883 }
884 }
885
886 void add_participant(Klass* participant) {
887 assert(!is_participant(participant), "sanity");
888 assert(_num_participants + _record_witnesses < PARTICIPANT_LIMIT, "oob");
889 uint np = _num_participants++;
890 _participants[np] = participant;
891 }
892
893 void record_witnesses(uint add) {
894 if (add > PARTICIPANT_LIMIT) add = PARTICIPANT_LIMIT;
895 assert(_num_participants + add < PARTICIPANT_LIMIT, "oob");
896 _record_witnesses = add;
897 }
898
899 Klass* find_witness(InstanceKlass* context_type, KlassDepChange* changes = nullptr);
900
901 static void init();
902 NOT_PRODUCT(static void print_statistics();)
903 };
904
905 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_anywhere_calls_count = nullptr;
906 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_anywhere_steps_count = nullptr;
907 PerfCounter* AbstractClassHierarchyWalker::_perf_find_witness_in_calls_count = nullptr;
908
909 void AbstractClassHierarchyWalker::init() {
910 if (UsePerfData) {
911 EXCEPTION_MARK;
912 _perf_find_witness_anywhere_calls_count =
913 PerfDataManager::create_counter(SUN_CI, "findWitnessAnywhere", PerfData::U_Events, CHECK);
914 _perf_find_witness_anywhere_steps_count =
915 PerfDataManager::create_counter(SUN_CI, "findWitnessAnywhereSteps", PerfData::U_Events, CHECK);
916 _perf_find_witness_in_calls_count =
917 PerfDataManager::create_counter(SUN_CI, "findWitnessIn", PerfData::U_Events, CHECK);
918 }
919 }
920
921 Klass* AbstractClassHierarchyWalker::find_witness(InstanceKlass* context_type, KlassDepChange* changes) {
922 // Current thread must be in VM (not native mode, as in CI):
923 assert(must_be_in_vm(), "raw oops here");
924 // Must not move the class hierarchy during this check:
925 assert_locked_or_safepoint(Compile_lock);
926 assert(_nof_requests++ == 0, "repeated requests are not supported");
927
928 assert(changes == nullptr || changes->involves_context(context_type), "irrelevant dependency");
929
930 // (Note: Interfaces do not have subclasses.)
931 // If it is an interface, search its direct implementors.
932 // (Their subclasses are additional indirect implementors. See InstanceKlass::add_implementor().)
933 if (context_type->is_interface()) {
934 int nof_impls = context_type->nof_implementors();
935 if (nof_impls == 0) {
936 return nullptr; // no implementors
937 } else if (nof_impls == 1) { // unique implementor
938 assert(context_type != context_type->implementor(), "not unique");
939 context_type = context_type->implementor();
940 } else { // nof_impls >= 2
941 // Avoid this case: *I.m > { A.m, C }; B.m > C
942 // Here, I.m has 2 concrete implementations, but m appears unique
943 // as A.m, because the search misses B.m when checking C.
944 // The inherited method B.m was getting missed by the walker
945 // when interface 'I' was the starting point.
946 // %%% Until this is fixed more systematically, bail out.
947 return context_type;
948 }
949 }
950 assert(!context_type->is_interface(), "no interfaces allowed");
951
952 if (changes != nullptr) {
953 if (UsePerfData) {
954 _perf_find_witness_in_calls_count->inc();
955 }
956 return find_witness_in(*changes);
957 } else {
958 if (UsePerfData) {
959 _perf_find_witness_anywhere_calls_count->inc();
960 }
961 return find_witness_anywhere(context_type);
962 }
963 }
964
965 class ConcreteSubtypeFinder : public AbstractClassHierarchyWalker {
966 private:
967 bool is_witness(Klass* k);
968
969 protected:
970 virtual Klass* find_witness_in(KlassDepChange& changes);
971 virtual Klass* find_witness_anywhere(InstanceKlass* context_type);
972
973 public:
974 ConcreteSubtypeFinder(Klass* participant = nullptr) : AbstractClassHierarchyWalker(participant) {}
975 };
976
977 bool ConcreteSubtypeFinder::is_witness(Klass* k) {
978 if (Dependencies::is_concrete_klass(k)) {
979 return record_witness(k); // concrete subtype
980 } else {
981 return false; // not a concrete class
982 }
983 }
984
985 Klass* ConcreteSubtypeFinder::find_witness_in(KlassDepChange& changes) {
986 // When looking for unexpected concrete types, do not look beneath expected ones:
987 // * CX > CC > C' is OK, even if C' is new.
988 // * CX > { CC, C' } is not OK if C' is new, and C' is the witness.
989 Klass* new_type = changes.as_new_klass_change()->new_type();
990 assert(!is_participant(new_type), "only old classes are participants");
991 // If the new type is a subtype of a participant, we are done.
992 for (uint i = 0; i < num_participants(); i++) {
993 if (changes.involves_context(participant(i))) {
994 // new guy is protected from this check by previous participant
995 return nullptr;
996 }
997 }
998 if (is_witness(new_type)) {
999 return new_type;
1000 }
1001 // No witness found. The dependency remains unbroken.
1002 return nullptr;
1003 }
1004
1005 Klass* ConcreteSubtypeFinder::find_witness_anywhere(InstanceKlass* context_type) {
1006 for (CountingClassHierarchyIterator iter(context_type); !iter.done(); iter.next()) {
1007 Klass* sub = iter.klass();
1008 // Do not report participant types.
1009 if (is_participant(sub)) {
1010 // Don't walk beneath a participant since it hides witnesses.
1011 iter.skip_subclasses();
1012 } else if (is_witness(sub)) {
1013 return sub; // found a witness
1014 }
1015 }
1016 // No witness found. The dependency remains unbroken.
1017 return nullptr;
1018 }
1019
1020 // For some method m and some class ctxk (subclass of method holder),
1021 // enumerate all distinct overrides of m in concrete subclasses of ctxk.
1022 // It relies on vtable/itable information to perform method selection on each linked subclass
1023 // and ignores all non yet linked ones (speculatively treat them as "effectively abstract").
1024 class LinkedConcreteMethodFinder : public AbstractClassHierarchyWalker {
1025 private:
1026 InstanceKlass* _resolved_klass; // resolved class (JVMS-5.4.3.1)
1027 InstanceKlass* _declaring_klass; // the holder of resolved method (JVMS-5.4.3.3)
1028 int _vtable_index; // vtable/itable index of the resolved method
1029 bool _do_itable_lookup; // choose between itable and vtable lookup logic
1030
1031 // cache of method lookups
1032 Method* _found_methods[PARTICIPANT_LIMIT+1];
1033
1034 bool is_witness(Klass* k);
1035 Method* select_method(InstanceKlass* recv_klass);
1036 static int compute_vtable_index(InstanceKlass* resolved_klass, Method* resolved_method, bool& is_itable_index);
1037 static bool is_concrete_klass(InstanceKlass* ik);
1038
1039 void add_participant(Method* m, Klass* participant) {
1040 uint np = num_participants();
1041 AbstractClassHierarchyWalker::add_participant(participant);
1042 assert(np + 1 == num_participants(), "sanity");
1043 _found_methods[np] = m; // record the method for the participant
1044 }
1045
1046 bool record_witness(Klass* witness, Method* m) {
1047 for (uint i = 0; i < num_participants(); i++) {
1048 if (found_method(i) == m) {
1049 return false; // already recorded
1050 }
1051 }
1052 // Record not yet seen method.
1053 _found_methods[num_participants()] = m;
1054 return AbstractClassHierarchyWalker::record_witness(witness);
1055 }
1056
1057 void initialize(Method* participant) {
1058 for (uint i = 0; i < PARTICIPANT_LIMIT+1; i++) {
1059 _found_methods[i] = nullptr;
1060 }
1061 if (participant != nullptr) {
1062 add_participant(participant, participant->method_holder());
1063 }
1064 }
1065
1066 protected:
1067 virtual Klass* find_witness_in(KlassDepChange& changes);
1068 virtual Klass* find_witness_anywhere(InstanceKlass* context_type);
1069
1070 public:
1071 // In order to perform method selection, the following info is needed:
1072 // (1) interface or virtual call;
1073 // (2) vtable/itable index;
1074 // (3) declaring class (in case of interface call).
1075 //
1076 // It is prepared based on the results of method resolution: resolved class and resolved method (as specified in JVMS-5.4.3.3).
1077 // Optionally, a method which was previously determined as a unique target (uniqm) is added as a participant
1078 // to enable dependency spot-checking and speed up the search.
1079 LinkedConcreteMethodFinder(InstanceKlass* resolved_klass, Method* resolved_method, Method* uniqm = nullptr) : AbstractClassHierarchyWalker(nullptr) {
1080 assert(resolved_klass->is_linked(), "required");
1081 assert(resolved_method->method_holder()->is_linked(), "required");
1082 assert(!resolved_method->can_be_statically_bound(), "no vtable index available");
1083
1084 _resolved_klass = resolved_klass;
1085 _declaring_klass = resolved_method->method_holder();
1086 _vtable_index = compute_vtable_index(resolved_klass, resolved_method,
1087 _do_itable_lookup); // out parameter
1088 assert(_vtable_index >= 0, "invalid vtable index");
1089
1090 initialize(uniqm);
1091 }
1092
1093 // Note: If n==num_participants, returns nullptr.
1094 Method* found_method(uint n) {
1095 assert(n <= num_participants(), "oob");
1096 assert(participant(n) != nullptr || n == num_participants(), "proper usage");
1097 return _found_methods[n];
1098 }
1099 };
1100
1101 Klass* LinkedConcreteMethodFinder::find_witness_in(KlassDepChange& changes) {
1102 Klass* type = changes.type();
1103
1104 assert(!is_participant(type), "only old classes are participants");
1105
1106 if (is_witness(type)) {
1107 return type;
1108 }
1109 return nullptr; // No witness found. The dependency remains unbroken.
1110 }
1111
1112 Klass* LinkedConcreteMethodFinder::find_witness_anywhere(InstanceKlass* context_type) {
1113 for (CountingClassHierarchyIterator iter(context_type); !iter.done(); iter.next()) {
1114 Klass* sub = iter.klass();
1115 if (is_witness(sub)) {
1116 return sub;
1117 }
1118 if (sub->is_instance_klass() && !InstanceKlass::cast(sub)->is_linked()) {
1119 iter.skip_subclasses(); // ignore not yet linked classes
1120 }
1121 }
1122 return nullptr; // No witness found. The dependency remains unbroken.
1123 }
1124
1125 bool LinkedConcreteMethodFinder::is_witness(Klass* k) {
1126 if (is_participant(k)) {
1127 return false; // do not report participant types
1128 } else if (k->is_instance_klass()) {
1129 InstanceKlass* ik = InstanceKlass::cast(k);
1130 if (is_concrete_klass(ik)) {
1131 Method* m = select_method(ik);
1132 return record_witness(ik, m);
1133 } else {
1134 return false; // ignore non-concrete holder class
1135 }
1136 } else {
1137 return false; // no methods to find in an array type
1138 }
1139 }
1140
1141 Method* LinkedConcreteMethodFinder::select_method(InstanceKlass* recv_klass) {
1142 Method* selected_method = nullptr;
1143 if (_do_itable_lookup) {
1144 assert(_declaring_klass->is_interface(), "sanity");
1145 bool implements_interface; // initialized by method_at_itable_or_null()
1146 selected_method = recv_klass->method_at_itable_or_null(_declaring_klass, _vtable_index,
1147 implements_interface); // out parameter
1148 assert(implements_interface, "not implemented");
1149 } else {
1150 selected_method = recv_klass->method_at_vtable(_vtable_index);
1151 }
1152 return selected_method; // nullptr when corresponding slot is empty (AbstractMethodError case)
1153 }
1154
1155 int LinkedConcreteMethodFinder::compute_vtable_index(InstanceKlass* resolved_klass, Method* resolved_method,
1156 // out parameter
1157 bool& is_itable_index) {
1158 if (resolved_klass->is_interface() && resolved_method->has_itable_index()) {
1159 is_itable_index = true;
1160 return resolved_method->itable_index();
1161 }
1162 // Check for default or miranda method first.
1163 InstanceKlass* declaring_klass = resolved_method->method_holder();
1164 if (!resolved_klass->is_interface() && declaring_klass->is_interface()) {
1165 is_itable_index = false;
1166 return resolved_klass->vtable_index_of_interface_method(resolved_method);
1167 }
1168 // At this point we are sure that resolved_method is virtual and not
1169 // a default or miranda method; therefore, it must have a valid vtable index.
1170 assert(resolved_method->has_vtable_index(), "");
1171 is_itable_index = false;
1172 return resolved_method->vtable_index();
1173 }
1174
1175 bool LinkedConcreteMethodFinder::is_concrete_klass(InstanceKlass* ik) {
1176 if (!Dependencies::is_concrete_klass(ik)) {
1177 return false; // not concrete
1178 }
1179 if (ik->is_interface()) {
1180 return false; // interfaces aren't concrete
1181 }
1182 if (!ik->is_linked()) {
1183 return false; // not yet linked classes don't have instances
1184 }
1185 return true;
1186 }
1187
1188 #ifdef ASSERT
1189 // Assert that m is inherited into ctxk, without intervening overrides.
1190 // (May return true even if this is not true, in corner cases where we punt.)
1191 bool Dependencies::verify_method_context(InstanceKlass* ctxk, Method* m) {
1192 if (m->is_private()) {
1193 return false; // Quick lose. Should not happen.
1194 }
1195 if (m->method_holder() == ctxk) {
1196 return true; // Quick win.
1197 }
1198 if (!(m->is_public() || m->is_protected())) {
1199 // The override story is complex when packages get involved.
1200 return true; // Must punt the assertion to true.
1201 }
1202 Method* lm = ctxk->lookup_method(m->name(), m->signature());
1203 if (lm == nullptr) {
1204 // It might be an interface method
1205 lm = ctxk->lookup_method_in_ordered_interfaces(m->name(), m->signature());
1206 }
1207 if (lm == m) {
1208 // Method m is inherited into ctxk.
1209 return true;
1210 }
1211 if (lm != nullptr) {
1212 if (!(lm->is_public() || lm->is_protected())) {
1213 // Method is [package-]private, so the override story is complex.
1214 return true; // Must punt the assertion to true.
1215 }
1216 if (lm->is_static()) {
1217 // Static methods don't override non-static so punt
1218 return true;
1219 }
1220 if (!Dependencies::is_concrete_method(lm, ctxk) &&
1221 !Dependencies::is_concrete_method(m, ctxk)) {
1222 // They are both non-concrete
1223 if (lm->method_holder()->is_subtype_of(m->method_holder())) {
1224 // Method m is overridden by lm, but both are non-concrete.
1225 return true;
1226 }
1227 if (lm->method_holder()->is_interface() && m->method_holder()->is_interface() &&
1228 ctxk->is_subtype_of(m->method_holder()) && ctxk->is_subtype_of(lm->method_holder())) {
1229 // Interface method defined in multiple super interfaces
1230 return true;
1231 }
1232 }
1233 }
1234 ResourceMark rm;
1235 tty->print_cr("Dependency method not found in the associated context:");
1236 tty->print_cr(" context = %s", ctxk->external_name());
1237 tty->print( " method = "); m->print_short_name(tty); tty->cr();
1238 if (lm != nullptr) {
1239 tty->print( " found = "); lm->print_short_name(tty); tty->cr();
1240 }
1241 return false;
1242 }
1243 #endif // ASSERT
1244
1245 bool Dependencies::is_concrete_klass(Klass* k) {
1246 if (k->is_abstract()) return false;
1247 // %%% We could treat classes which are concrete but
1248 // have not yet been instantiated as virtually abstract.
1249 // This would require a deoptimization barrier on first instantiation.
1250 //if (k->is_not_instantiated()) return false;
1251 return true;
1252 }
1253
1254 bool Dependencies::is_concrete_method(Method* m, Klass* k) {
1255 // nullptr is not a concrete method.
1256 if (m == nullptr) {
1257 return false;
1258 }
1259 // Statics are irrelevant to virtual call sites.
1260 if (m->is_static()) {
1261 return false;
1262 }
1263 // Abstract methods are not concrete.
1264 if (m->is_abstract()) {
1265 return false;
1266 }
1267 // Overpass (error) methods are not concrete if k is abstract.
1268 if (m->is_overpass() && k != nullptr) {
1269 return !k->is_abstract();
1270 }
1271 // Note "true" is conservative answer: overpass clause is false if k == nullptr,
1272 // implies return true if answer depends on overpass clause.
1273 return true;
1274 }
1275
1276 Klass* Dependencies::find_finalizable_subclass(InstanceKlass* ik) {
1277 for (ClassHierarchyIterator iter(ik); !iter.done(); iter.next()) {
1278 Klass* sub = iter.klass();
1279 if (sub->has_finalizer() && !sub->is_interface()) {
1280 return sub;
1281 }
1282 }
1283 return nullptr; // not found
1284 }
1285
1286 bool Dependencies::is_concrete_klass(ciInstanceKlass* k) {
1287 if (k->is_abstract()) return false;
1288 // We could also return false if k does not yet appear to be
1289 // instantiated, if the VM version supports this distinction also.
1290 //if (k->is_not_instantiated()) return false;
1291 return true;
1292 }
1293
1294 bool Dependencies::has_finalizable_subclass(ciInstanceKlass* k) {
1295 return k->has_finalizable_subclass();
1296 }
1297
1298 // Any use of the contents (bytecodes) of a method must be
1299 // marked by an "evol_method" dependency, if those contents
1300 // can change. (Note: A method is always dependent on itself.)
1301 Klass* Dependencies::check_evol_method(Method* m) {
1302 assert(must_be_in_vm(), "raw oops here");
1303 // Did somebody do a JVMTI RedefineClasses while our backs were turned?
1304 // Or is there a now a breakpoint?
1305 // (Assumes compiled code cannot handle bkpts; change if UseFastBreakpoints.)
1306 if (m->is_old() || m->number_of_breakpoints() > 0) {
1307 return m->method_holder();
1308 } else {
1309 return nullptr;
1310 }
1311 }
1312
1313 Klass* Dependencies::check_mismatch_calling_convention(Method* m) {
1314 assert(must_be_in_vm(), "raw oops here");
1315 if (m->mismatch()) {
1316 return m->method_holder();
1317 } else {
1318 return nullptr;
1319 }
1320 }
1321
1322 // This is a strong assertion: It is that the given type
1323 // has no subtypes whatever. It is most useful for
1324 // optimizing checks on reflected types or on array types.
1325 // (Checks on types which are derived from real instances
1326 // can be optimized more strongly than this, because we
1327 // know that the checked type comes from a concrete type,
1328 // and therefore we can disregard abstract types.)
1329 Klass* Dependencies::check_leaf_type(InstanceKlass* ctxk) {
1330 assert(must_be_in_vm(), "raw oops here");
1331 assert_locked_or_safepoint(Compile_lock);
1332 Klass* sub = ctxk->subklass();
1333 if (sub != nullptr) {
1334 return sub;
1335 } else if (ctxk->nof_implementors() != 0) {
1336 // if it is an interface, it must be unimplemented
1337 // (if it is not an interface, nof_implementors is always zero)
1338 InstanceKlass* impl = ctxk->implementor();
1339 assert(impl != nullptr, "must be set");
1340 return impl;
1341 } else {
1342 return nullptr;
1343 }
1344 }
1345
1346 // Test the assertion that conck is the only concrete subtype* of ctxk.
1347 // The type conck itself is allowed to have have further concrete subtypes.
1348 // This allows the compiler to narrow occurrences of ctxk by conck,
1349 // when dealing with the types of actual instances.
1350 Klass* Dependencies::check_abstract_with_unique_concrete_subtype(InstanceKlass* ctxk,
1351 Klass* conck,
1352 NewKlassDepChange* changes) {
1353 ConcreteSubtypeFinder wf(conck);
1354 Klass* k = wf.find_witness(ctxk, changes);
1355 return k;
1356 }
1357
1358
1359 // Find the unique concrete proper subtype of ctxk, or nullptr if there
1360 // is more than one concrete proper subtype. If there are no concrete
1361 // proper subtypes, return ctxk itself, whether it is concrete or not.
1362 // The returned subtype is allowed to have have further concrete subtypes.
1363 // That is, return CC1 for CX > CC1 > CC2, but nullptr for CX > { CC1, CC2 }.
1364 Klass* Dependencies::find_unique_concrete_subtype(InstanceKlass* ctxk) {
1365 ConcreteSubtypeFinder wf(ctxk); // Ignore ctxk when walking.
1366 wf.record_witnesses(1); // Record one other witness when walking.
1367 Klass* wit = wf.find_witness(ctxk);
1368 if (wit != nullptr) return nullptr; // Too many witnesses.
1369 Klass* conck = wf.participant(0);
1370 if (conck == nullptr) {
1371 return ctxk; // Return ctxk as a flag for "no subtypes".
1372 } else {
1373 #ifndef PRODUCT
1374 // Make sure the dependency mechanism will pass this discovery:
1375 if (VerifyDependencies) {
1376 // Turn off dependency tracing while actually testing deps.
1377 FlagSetting fs(_verify_in_progress, true);
1378 if (!Dependencies::is_concrete_klass(ctxk)) {
1379 guarantee(nullptr == (void *)
1380 check_abstract_with_unique_concrete_subtype(ctxk, conck),
1381 "verify dep.");
1382 }
1383 }
1384 #endif //PRODUCT
1385 return conck;
1386 }
1387 }
1388
1389 Klass* Dependencies::check_unique_implementor(InstanceKlass* ctxk, Klass* uniqk, NewKlassDepChange* changes) {
1390 assert(ctxk->is_interface(), "sanity");
1391 assert(ctxk->nof_implementors() > 0, "no implementors");
1392 if (ctxk->nof_implementors() == 1) {
1393 assert(ctxk->implementor() == uniqk, "sanity");
1394 return nullptr;
1395 }
1396 return ctxk; // no unique implementor
1397 }
1398
1399 // If a class (or interface) has a unique concrete method uniqm, return nullptr.
1400 // Otherwise, return a class that contains an interfering method.
1401 Klass* Dependencies::check_unique_concrete_method(InstanceKlass* ctxk,
1402 Method* uniqm,
1403 Klass* resolved_klass,
1404 Method* resolved_method,
1405 KlassDepChange* changes) {
1406 assert(!ctxk->is_interface() || ctxk == resolved_klass, "sanity");
1407 assert(!resolved_method->can_be_statically_bound() || resolved_method == uniqm, "sanity");
1408 assert(resolved_klass->is_subtype_of(resolved_method->method_holder()), "sanity");
1409
1410 if (!InstanceKlass::cast(resolved_klass)->is_linked() ||
1411 !resolved_method->method_holder()->is_linked() ||
1412 resolved_method->can_be_statically_bound()) {
1413 // Dependency is redundant, but benign. Just keep it to avoid unnecessary recompilation.
1414 return nullptr; // no vtable index available
1415 }
1416
1417 LinkedConcreteMethodFinder mf(InstanceKlass::cast(resolved_klass), resolved_method, uniqm);
1418 return mf.find_witness(ctxk, changes);
1419 }
1420
1421 // Find the set of all non-abstract methods under ctxk that match m.
1422 // (The method m must be defined or inherited in ctxk.)
1423 // Include m itself in the set, unless it is abstract.
1424 // If this set has exactly one element, return that element.
1425 // Not yet linked subclasses of ctxk are ignored since they don't have any instances yet.
1426 // Additionally, resolved_klass and resolved_method complete the description of the call site being analyzed.
1427 Method* Dependencies::find_unique_concrete_method(InstanceKlass* ctxk, Method* m, Klass* resolved_klass, Method* resolved_method) {
1428 // Return nullptr if m is marked old; must have been a redefined method.
1429 if (m->is_old()) {
1430 return nullptr;
1431 }
1432 if (!InstanceKlass::cast(resolved_klass)->is_linked() ||
1433 !resolved_method->method_holder()->is_linked() ||
1434 resolved_method->can_be_statically_bound()) {
1435 return m; // nothing to do: no witness under ctxk
1436 }
1437 LinkedConcreteMethodFinder wf(InstanceKlass::cast(resolved_klass), resolved_method);
1438 assert(Dependencies::verify_method_context(ctxk, m), "proper context");
1439 wf.record_witnesses(1);
1440 Klass* wit = wf.find_witness(ctxk);
1441 if (wit != nullptr) {
1442 return nullptr; // Too many witnesses.
1443 }
1444 // p == nullptr when no participants are found (wf.num_participants() == 0).
1445 // fm == nullptr case has 2 meanings:
1446 // * when p == nullptr: no method found;
1447 // * when p != nullptr: AbstractMethodError-throwing method found.
1448 // Also, found method should always be accompanied by a participant class.
1449 Klass* p = wf.participant(0);
1450 Method* fm = wf.found_method(0);
1451 assert(fm == nullptr || p != nullptr, "no participant");
1452 // Normalize all error-throwing cases to nullptr.
1453 if (fm == Universe::throw_illegal_access_error() ||
1454 fm == Universe::throw_no_such_method_error() ||
1455 !Dependencies::is_concrete_method(fm, p)) {
1456 fm = nullptr; // error-throwing method
1457 }
1458 if (Dependencies::is_concrete_method(m, ctxk)) {
1459 if (p == nullptr) {
1460 // It turns out that m was always the only implementation.
1461 assert(fm == nullptr, "sanity");
1462 fm = m;
1463 }
1464 }
1465 #ifndef PRODUCT
1466 // Make sure the dependency mechanism will pass this discovery:
1467 if (VerifyDependencies && fm != nullptr) {
1468 guarantee(nullptr == check_unique_concrete_method(ctxk, fm, resolved_klass, resolved_method),
1469 "verify dep.");
1470 }
1471 #endif // PRODUCT
1472 assert(fm == nullptr || !fm->is_abstract(), "sanity");
1473 return fm;
1474 }
1475
1476 Klass* Dependencies::check_has_no_finalizable_subclasses(InstanceKlass* ctxk, NewKlassDepChange* changes) {
1477 InstanceKlass* search_at = ctxk;
1478 if (changes != nullptr) {
1479 search_at = changes->new_type(); // just look at the new bit
1480 }
1481 return find_finalizable_subclass(search_at);
1482 }
1483
1484 Klass* Dependencies::check_call_site_target_value(oop call_site, oop method_handle, CallSiteDepChange* changes) {
1485 assert(call_site != nullptr, "sanity");
1486 assert(method_handle != nullptr, "sanity");
1487 assert(call_site->is_a(vmClasses::CallSite_klass()), "sanity");
1488
1489 if (changes == nullptr) {
1490 // Validate all CallSites
1491 if (java_lang_invoke_CallSite::target(call_site) != method_handle)
1492 return call_site->klass(); // assertion failed
1493 } else {
1494 // Validate the given CallSite
1495 if (call_site == changes->call_site() && java_lang_invoke_CallSite::target(call_site) != changes->method_handle()) {
1496 assert(method_handle != changes->method_handle(), "must be");
1497 return call_site->klass(); // assertion failed
1498 }
1499 }
1500 return nullptr; // assertion still valid
1501 }
1502
1503 void Dependencies::DepStream::trace_and_log_witness(Klass* witness) {
1504 if (_verify_in_progress) return; // don't log
1505 if (witness != nullptr) {
1506 LogTarget(Debug, dependencies) lt;
1507 if (lt.is_enabled()) {
1508 LogStream ls(<);
1509 print_dependency(&ls, witness, /*verbose=*/ true);
1510 }
1511 // The following is a no-op unless logging is enabled:
1512 log_dependency(witness);
1513 }
1514 }
1515
1516 Klass* Dependencies::DepStream::check_new_klass_dependency(NewKlassDepChange* changes) {
1517 assert_locked_or_safepoint(Compile_lock);
1518 Dependencies::check_valid_dependency_type(type());
1519
1520 Klass* witness = nullptr;
1521 switch (type()) {
1522 case evol_method:
1523 witness = check_evol_method(method_argument(0));
1524 break;
1525 case mismatch_calling_convention:
1526 witness = check_mismatch_calling_convention(method_argument(0));
1527 break;
1528 case leaf_type:
1529 witness = check_leaf_type(context_type());
1530 break;
1531 case abstract_with_unique_concrete_subtype:
1532 witness = check_abstract_with_unique_concrete_subtype(context_type(), type_argument(1), changes);
1533 break;
1534 case unique_concrete_method:
1535 witness = check_unique_concrete_method(context_type(), method_argument(1), type_argument(2), method_argument(3), changes);
1536 break;
1537 case unique_implementor:
1538 witness = check_unique_implementor(context_type(), type_argument(1), changes);
1539 break;
1540 case no_finalizable_subclasses:
1541 witness = check_has_no_finalizable_subclasses(context_type(), changes);
1542 break;
1543 default:
1544 witness = nullptr;
1545 break;
1546 }
1547 trace_and_log_witness(witness);
1548 return witness;
1549 }
1550
1551 Klass* Dependencies::DepStream::check_klass_init_dependency(KlassInitDepChange* changes) {
1552 assert_locked_or_safepoint(Compile_lock);
1553 Dependencies::check_valid_dependency_type(type());
1554
1555 // No new types added. Only unique_concrete_method is sensitive to class initialization changes.
1556 if (type() == unique_concrete_method) {
1557 Klass* witness = check_unique_concrete_method(context_type(), method_argument(1), type_argument(2), method_argument(3), changes);
1558 trace_and_log_witness(witness);
1559 return witness;
1560 }
1561 return nullptr;
1562 }
1563
1564 Klass* Dependencies::DepStream::check_klass_dependency(KlassDepChange* changes) {
1565 assert_locked_or_safepoint(Compile_lock);
1566 Dependencies::check_valid_dependency_type(type());
1567
1568 if (changes != nullptr) {
1569 if (changes->is_klass_init_change()) {
1570 return check_klass_init_dependency(changes->as_klass_init_change());
1571 } else {
1572 return check_new_klass_dependency(changes->as_new_klass_change());
1573 }
1574 } else {
1575 Klass* witness = check_new_klass_dependency(nullptr);
1576 // check_klass_init_dependency duplicates check_new_klass_dependency checks when class hierarchy change info is absent.
1577 assert(witness != nullptr || check_klass_init_dependency(nullptr) == nullptr, "missed dependency");
1578 return witness;
1579 }
1580 }
1581
1582 Klass* Dependencies::DepStream::check_call_site_dependency(CallSiteDepChange* changes) {
1583 assert_locked_or_safepoint(Compile_lock);
1584 Dependencies::check_valid_dependency_type(type());
1585
1586 Klass* witness = nullptr;
1587 switch (type()) {
1588 case call_site_target_value:
1589 witness = check_call_site_target_value(argument_oop(0), argument_oop(1), changes);
1590 break;
1591 default:
1592 witness = nullptr;
1593 break;
1594 }
1595 trace_and_log_witness(witness);
1596 return witness;
1597 }
1598
1599
1600 Klass* Dependencies::DepStream::spot_check_dependency_at(DepChange& changes) {
1601 // Handle klass dependency
1602 if (changes.is_klass_change() && changes.as_klass_change()->involves_context(context_type()))
1603 return check_klass_dependency(changes.as_klass_change());
1604
1605 // Handle CallSite dependency
1606 if (changes.is_call_site_change())
1607 return check_call_site_dependency(changes.as_call_site_change());
1608
1609 // irrelevant dependency; skip it
1610 return nullptr;
1611 }
1612
1613
1614 void DepChange::print() { print_on(tty); }
1615
1616 void DepChange::print_on(outputStream* st) {
1617 int nsup = 0, nint = 0;
1618 for (ContextStream str(*this); str.next(); ) {
1619 InstanceKlass* k = str.klass();
1620 switch (str.change_type()) {
1621 case Change_new_type:
1622 st->print_cr(" dependee = %s", k->external_name());
1623 break;
1624 case Change_new_sub:
1625 if (!WizardMode) {
1626 ++nsup;
1627 } else {
1628 st->print_cr(" context super = %s", k->external_name());
1629 }
1630 break;
1631 case Change_new_impl:
1632 if (!WizardMode) {
1633 ++nint;
1634 } else {
1635 st->print_cr(" context interface = %s", k->external_name());
1636 }
1637 break;
1638 default:
1639 break;
1640 }
1641 }
1642 if (nsup + nint != 0) {
1643 st->print_cr(" context supers = %d, interfaces = %d", nsup, nint);
1644 }
1645 }
1646
1647 void DepChange::ContextStream::start() {
1648 InstanceKlass* type = (_changes.is_klass_change() ? _changes.as_klass_change()->type() : (InstanceKlass*) nullptr);
1649 _change_type = (type == nullptr ? NO_CHANGE : Start_Klass);
1650 _klass = type;
1651 _ti_base = nullptr;
1652 _ti_index = 0;
1653 _ti_limit = 0;
1654 }
1655
1656 bool DepChange::ContextStream::next() {
1657 switch (_change_type) {
1658 case Start_Klass: // initial state; _klass is the new type
1659 _ti_base = _klass->transitive_interfaces();
1660 _ti_index = 0;
1661 _change_type = Change_new_type;
1662 return true;
1663 case Change_new_type:
1664 // fall through:
1665 _change_type = Change_new_sub;
1666 case Change_new_sub:
1667 // 6598190: brackets workaround Sun Studio C++ compiler bug 6629277
1668 {
1669 _klass = _klass->java_super();
1670 if (_klass != nullptr) {
1671 return true;
1672 }
1673 }
1674 // else set up _ti_limit and fall through:
1675 _ti_limit = (_ti_base == nullptr) ? 0 : _ti_base->length();
1676 _change_type = Change_new_impl;
1677 case Change_new_impl:
1678 if (_ti_index < _ti_limit) {
1679 _klass = _ti_base->at(_ti_index++);
1680 return true;
1681 }
1682 // fall through:
1683 _change_type = NO_CHANGE; // iterator is exhausted
1684 case NO_CHANGE:
1685 break;
1686 default:
1687 ShouldNotReachHere();
1688 }
1689 return false;
1690 }
1691
1692 void KlassDepChange::initialize() {
1693 // entire transaction must be under this lock:
1694 assert_lock_strong(Compile_lock);
1695
1696 // Mark all dependee and all its superclasses
1697 // Mark transitive interfaces
1698 for (ContextStream str(*this); str.next(); ) {
1699 InstanceKlass* d = str.klass();
1700 assert(!d->is_marked_dependent(), "checking");
1701 d->set_is_marked_dependent(true);
1702 }
1703 }
1704
1705 KlassDepChange::~KlassDepChange() {
1706 // Unmark all dependee and all its superclasses
1707 // Unmark transitive interfaces
1708 for (ContextStream str(*this); str.next(); ) {
1709 InstanceKlass* d = str.klass();
1710 d->set_is_marked_dependent(false);
1711 }
1712 }
1713
1714 bool KlassDepChange::involves_context(Klass* k) {
1715 if (k == nullptr || !k->is_instance_klass()) {
1716 return false;
1717 }
1718 InstanceKlass* ik = InstanceKlass::cast(k);
1719 bool is_contained = ik->is_marked_dependent();
1720 assert(is_contained == type()->is_subtype_of(k),
1721 "correct marking of potential context types");
1722 return is_contained;
1723 }
1724
1725 #ifndef PRODUCT
1726 void Dependencies::print_statistics() {
1727 AbstractClassHierarchyWalker::print_statistics();
1728 }
1729
1730 void AbstractClassHierarchyWalker::print_statistics() {
1731 if (UsePerfData) {
1732 jlong deps_find_witness_calls = _perf_find_witness_anywhere_calls_count->get_value();
1733 jlong deps_find_witness_steps = _perf_find_witness_anywhere_steps_count->get_value();
1734 jlong deps_find_witness_singles = _perf_find_witness_in_calls_count->get_value();
1735
1736 ttyLocker ttyl;
1737 tty->print_cr("Dependency check (find_witness) "
1738 "calls=" JLONG_FORMAT ", steps=" JLONG_FORMAT " (avg=%.1f), singles=" JLONG_FORMAT,
1739 deps_find_witness_calls,
1740 deps_find_witness_steps,
1741 (double)deps_find_witness_steps / deps_find_witness_calls,
1742 deps_find_witness_singles);
1743 if (xtty != nullptr) {
1744 xtty->elem("deps_find_witness calls='" JLONG_FORMAT "' steps='" JLONG_FORMAT "' singles='" JLONG_FORMAT "'",
1745 deps_find_witness_calls,
1746 deps_find_witness_steps,
1747 deps_find_witness_singles);
1748 }
1749 }
1750 }
1751 #endif
1752
1753 CallSiteDepChange::CallSiteDepChange(Handle call_site, Handle method_handle) :
1754 _call_site(call_site),
1755 _method_handle(method_handle) {
1756 assert(_call_site()->is_a(vmClasses::CallSite_klass()), "must be");
1757 assert(_method_handle.is_null() || _method_handle()->is_a(vmClasses::MethodHandle_klass()), "must be");
1758 }
1759
1760 void dependencies_init() {
1761 AbstractClassHierarchyWalker::init();
1762 }