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