1 /*
   2  * Copyright (c) 2000, 2024, 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 "precompiled.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "compiler/compilationPolicy.hpp"
  29 #include "compiler/compilerDefinitions.inline.hpp"
  30 #include "compiler/compilerOracle.hpp"
  31 #include "interpreter/bytecode.hpp"
  32 #include "interpreter/bytecodeStream.hpp"
  33 #include "interpreter/linkResolver.hpp"
  34 #include "memory/metaspaceClosure.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "oops/klass.inline.hpp"
  37 #include "oops/methodData.inline.hpp"
  38 #include "prims/jvmtiRedefineClasses.hpp"
  39 #include "runtime/atomic.hpp"
  40 #include "runtime/deoptimization.hpp"
  41 #include "runtime/handles.inline.hpp"
  42 #include "runtime/orderAccess.hpp"
  43 #include "runtime/safepointVerifiers.hpp"
  44 #include "runtime/signature.hpp"
  45 #include "utilities/align.hpp"
  46 #include "utilities/checkedCast.hpp"
  47 #include "utilities/copy.hpp"
  48 
  49 // ==================================================================
  50 // DataLayout
  51 //
  52 // Overlay for generic profiling data.
  53 
  54 // Some types of data layouts need a length field.
  55 bool DataLayout::needs_array_len(u1 tag) {
  56   return (tag == multi_branch_data_tag) || (tag == arg_info_data_tag) || (tag == parameters_type_data_tag);
  57 }
  58 
  59 // Perform generic initialization of the data.  More specific
  60 // initialization occurs in overrides of ProfileData::post_initialize.
  61 void DataLayout::initialize(u1 tag, u2 bci, int cell_count) {
  62   DataLayout temp;
  63   temp._header._bits = (intptr_t)0;
  64   temp._header._struct._tag = tag;
  65   temp._header._struct._bci = bci;
  66   // Write the header using a single intptr_t write.  This ensures that if the layout is
  67   // reinitialized readers will never see the transient state where the header is 0.
  68   _header = temp._header;
  69 
  70   for (int i = 0; i < cell_count; i++) {
  71     set_cell_at(i, (intptr_t)0);
  72   }
  73   if (needs_array_len(tag)) {
  74     set_cell_at(ArrayData::array_len_off_set, cell_count - 1); // -1 for header.
  75   }
  76   if (tag == call_type_data_tag) {
  77     CallTypeData::initialize(this, cell_count);
  78   } else if (tag == virtual_call_type_data_tag) {
  79     VirtualCallTypeData::initialize(this, cell_count);
  80   }
  81 }
  82 
  83 void DataLayout::clean_weak_klass_links(bool always_clean) {
  84   ResourceMark m;
  85   data_in()->clean_weak_klass_links(always_clean);
  86 }
  87 
  88 
  89 // ==================================================================
  90 // ProfileData
  91 //
  92 // A ProfileData object is created to refer to a section of profiling
  93 // data in a structured way.
  94 
  95 // Constructor for invalid ProfileData.
  96 ProfileData::ProfileData() {
  97   _data = nullptr;
  98 }
  99 
 100 char* ProfileData::print_data_on_helper(const MethodData* md) const {
 101   DataLayout* dp  = md->extra_data_base();
 102   DataLayout* end = md->args_data_limit();
 103   stringStream ss;
 104   for (;; dp = MethodData::next_extra(dp)) {
 105     assert(dp < end, "moved past end of extra data");
 106     switch(dp->tag()) {
 107     case DataLayout::speculative_trap_data_tag:
 108       if (dp->bci() == bci()) {
 109         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
 110         int trap = data->trap_state();
 111         char buf[100];
 112         ss.print("trap/");
 113         data->method()->print_short_name(&ss);
 114         ss.print("(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
 115       }
 116       break;
 117     case DataLayout::bit_data_tag:
 118       break;
 119     case DataLayout::no_tag:
 120     case DataLayout::arg_info_data_tag:
 121       return ss.as_string();
 122       break;
 123     default:
 124       fatal("unexpected tag %d", dp->tag());
 125     }
 126   }
 127   return nullptr;
 128 }
 129 
 130 void ProfileData::print_data_on(outputStream* st, const MethodData* md) const {
 131   print_data_on(st, print_data_on_helper(md));
 132 }
 133 
 134 void ProfileData::print_shared(outputStream* st, const char* name, const char* extra) const {
 135   st->print("bci: %d ", bci());
 136   st->fill_to(tab_width_one + 1);
 137   st->print("%s", name);
 138   tab(st);
 139   int trap = trap_state();
 140   if (trap != 0) {
 141     char buf[100];
 142     st->print("trap(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
 143   }
 144   if (extra != nullptr) {
 145     st->print("%s", extra);
 146   }
 147   int flags = data()->flags();
 148   if (flags != 0) {
 149     st->print("flags(%d) ", flags);
 150   }
 151 }
 152 
 153 void ProfileData::tab(outputStream* st, bool first) const {
 154   st->fill_to(first ? tab_width_one : tab_width_two);
 155 }
 156 
 157 // ==================================================================
 158 // BitData
 159 //
 160 // A BitData corresponds to a one-bit flag.  This is used to indicate
 161 // whether a checkcast bytecode has seen a null value.
 162 
 163 
 164 void BitData::print_data_on(outputStream* st, const char* extra) const {
 165   print_shared(st, "BitData", extra);
 166   st->cr();
 167 }
 168 
 169 // ==================================================================
 170 // CounterData
 171 //
 172 // A CounterData corresponds to a simple counter.
 173 
 174 void CounterData::print_data_on(outputStream* st, const char* extra) const {
 175   print_shared(st, "CounterData", extra);
 176   st->print_cr("count(%u)", count());
 177 }
 178 
 179 // ==================================================================
 180 // JumpData
 181 //
 182 // A JumpData is used to access profiling information for a direct
 183 // branch.  It is a counter, used for counting the number of branches,
 184 // plus a data displacement, used for realigning the data pointer to
 185 // the corresponding target bci.
 186 
 187 void JumpData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 188   assert(stream->bci() == bci(), "wrong pos");
 189   int target;
 190   Bytecodes::Code c = stream->code();
 191   if (c == Bytecodes::_goto_w || c == Bytecodes::_jsr_w) {
 192     target = stream->dest_w();
 193   } else {
 194     target = stream->dest();
 195   }
 196   int my_di = mdo->dp_to_di(dp());
 197   int target_di = mdo->bci_to_di(target);
 198   int offset = target_di - my_di;
 199   set_displacement(offset);
 200 }
 201 
 202 void JumpData::print_data_on(outputStream* st, const char* extra) const {
 203   print_shared(st, "JumpData", extra);
 204   st->print_cr("taken(%u) displacement(%d)", taken(), displacement());
 205 }
 206 
 207 int TypeStackSlotEntries::compute_cell_count(Symbol* signature, bool include_receiver, int max) {
 208   // Parameter profiling include the receiver
 209   int args_count = include_receiver ? 1 : 0;
 210   ResourceMark rm;
 211   ReferenceArgumentCount rac(signature);
 212   args_count += rac.count();
 213   args_count = MIN2(args_count, max);
 214   return args_count * per_arg_cell_count;
 215 }
 216 
 217 int TypeEntriesAtCall::compute_cell_count(BytecodeStream* stream) {
 218   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 219   assert(TypeStackSlotEntries::per_arg_count() > ReturnTypeEntry::static_cell_count(), "code to test for arguments/results broken");
 220   const methodHandle m = stream->method();
 221   int bci = stream->bci();
 222   Bytecode_invoke inv(m, bci);
 223   int args_cell = 0;
 224   if (MethodData::profile_arguments_for_invoke(m, bci)) {
 225     args_cell = TypeStackSlotEntries::compute_cell_count(inv.signature(), false, TypeProfileArgsLimit);
 226   }
 227   int ret_cell = 0;
 228   if (MethodData::profile_return_for_invoke(m, bci) && is_reference_type(inv.result_type())) {
 229     ret_cell = ReturnTypeEntry::static_cell_count();
 230   }
 231   int header_cell = 0;
 232   if (args_cell + ret_cell > 0) {
 233     header_cell = header_cell_count();
 234   }
 235 
 236   return header_cell + args_cell + ret_cell;
 237 }
 238 
 239 class ArgumentOffsetComputer : public SignatureIterator {
 240 private:
 241   int _max;
 242   int _offset;
 243   GrowableArray<int> _offsets;
 244 
 245   friend class SignatureIterator;  // so do_parameters_on can call do_type
 246   void do_type(BasicType type) {
 247     if (is_reference_type(type) && _offsets.length() < _max) {
 248       _offsets.push(_offset);
 249     }
 250     _offset += parameter_type_word_count(type);
 251   }
 252 
 253  public:
 254   ArgumentOffsetComputer(Symbol* signature, int max)
 255     : SignatureIterator(signature),
 256       _max(max), _offset(0),
 257       _offsets(max) {
 258     do_parameters_on(this);  // non-virtual template execution
 259   }
 260 
 261   int off_at(int i) const { return _offsets.at(i); }
 262 };
 263 
 264 void TypeStackSlotEntries::post_initialize(Symbol* signature, bool has_receiver, bool include_receiver) {
 265   ResourceMark rm;
 266   int start = 0;
 267   // Parameter profiling include the receiver
 268   if (include_receiver && has_receiver) {
 269     set_stack_slot(0, 0);
 270     set_type(0, type_none());
 271     start += 1;
 272   }
 273   ArgumentOffsetComputer aos(signature, _number_of_entries-start);
 274   for (int i = start; i < _number_of_entries; i++) {
 275     set_stack_slot(i, aos.off_at(i-start) + (has_receiver ? 1 : 0));
 276     set_type(i, type_none());
 277   }
 278 }
 279 
 280 void CallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 281   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 282   Bytecode_invoke inv(stream->method(), stream->bci());
 283 
 284   if (has_arguments()) {
 285 #ifdef ASSERT
 286     ResourceMark rm;
 287     ReferenceArgumentCount rac(inv.signature());
 288     int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
 289     assert(count > 0, "room for args type but none found?");
 290     check_number_of_arguments(count);
 291 #endif
 292     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
 293   }
 294 
 295   if (has_return()) {
 296     assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
 297     _ret.post_initialize();
 298   }
 299 }
 300 
 301 void VirtualCallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 302   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
 303   Bytecode_invoke inv(stream->method(), stream->bci());
 304 
 305   if (has_arguments()) {
 306 #ifdef ASSERT
 307     ResourceMark rm;
 308     ReferenceArgumentCount rac(inv.signature());
 309     int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
 310     assert(count > 0, "room for args type but none found?");
 311     check_number_of_arguments(count);
 312 #endif
 313     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
 314   }
 315 
 316   if (has_return()) {
 317     assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
 318     _ret.post_initialize();
 319   }
 320 }
 321 
 322 void TypeStackSlotEntries::clean_weak_klass_links(bool always_clean) {
 323   for (int i = 0; i < _number_of_entries; i++) {
 324     intptr_t p = type(i);
 325     Klass* k = (Klass*)klass_part(p);
 326     if (k != nullptr && (always_clean || !k->is_loader_alive())) {
 327       set_type(i, with_status((Klass*)nullptr, p));
 328     }
 329   }
 330 }
 331 
 332 void ReturnTypeEntry::clean_weak_klass_links(bool always_clean) {
 333   intptr_t p = type();
 334   Klass* k = (Klass*)klass_part(p);
 335   if (k != nullptr && (always_clean || !k->is_loader_alive())) {
 336     set_type(with_status((Klass*)nullptr, p));
 337   }
 338 }
 339 
 340 bool TypeEntriesAtCall::return_profiling_enabled() {
 341   return MethodData::profile_return();
 342 }
 343 
 344 bool TypeEntriesAtCall::arguments_profiling_enabled() {
 345   return MethodData::profile_arguments();
 346 }
 347 
 348 void TypeEntries::print_klass(outputStream* st, intptr_t k) {
 349   if (is_type_none(k)) {
 350     st->print("none");
 351   } else if (is_type_unknown(k)) {
 352     st->print("unknown");
 353   } else {
 354     valid_klass(k)->print_value_on(st);
 355   }
 356   if (was_null_seen(k)) {
 357     st->print(" (null seen)");
 358   }
 359 }
 360 
 361 void TypeStackSlotEntries::print_data_on(outputStream* st) const {
 362   for (int i = 0; i < _number_of_entries; i++) {
 363     _pd->tab(st);
 364     st->print("%d: stack(%u) ", i, stack_slot(i));
 365     print_klass(st, type(i));
 366     st->cr();
 367   }
 368 }
 369 
 370 void ReturnTypeEntry::print_data_on(outputStream* st) const {
 371   _pd->tab(st);
 372   print_klass(st, type());
 373   st->cr();
 374 }
 375 
 376 void CallTypeData::print_data_on(outputStream* st, const char* extra) const {
 377   CounterData::print_data_on(st, extra);
 378   if (has_arguments()) {
 379     tab(st, true);
 380     st->print("argument types");
 381     _args.print_data_on(st);
 382   }
 383   if (has_return()) {
 384     tab(st, true);
 385     st->print("return type");
 386     _ret.print_data_on(st);
 387   }
 388 }
 389 
 390 void VirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
 391   VirtualCallData::print_data_on(st, extra);
 392   if (has_arguments()) {
 393     tab(st, true);
 394     st->print("argument types");
 395     _args.print_data_on(st);
 396   }
 397   if (has_return()) {
 398     tab(st, true);
 399     st->print("return type");
 400     _ret.print_data_on(st);
 401   }
 402 }
 403 
 404 // ==================================================================
 405 // ReceiverTypeData
 406 //
 407 // A ReceiverTypeData is used to access profiling information about a
 408 // dynamic type check.  It consists of a counter which counts the total times
 409 // that the check is reached, and a series of (Klass*, count) pairs
 410 // which are used to store a type profile for the receiver of the check.
 411 
 412 void ReceiverTypeData::clean_weak_klass_links(bool always_clean) {
 413     for (uint row = 0; row < row_limit(); row++) {
 414     Klass* p = receiver(row);
 415     if (p != nullptr && (always_clean || !p->is_loader_alive())) {
 416       clear_row(row);
 417     }
 418   }
 419 }
 420 
 421 void ReceiverTypeData::print_receiver_data_on(outputStream* st) const {
 422   uint row;
 423   int entries = 0;
 424   for (row = 0; row < row_limit(); row++) {
 425     if (receiver(row) != nullptr)  entries++;
 426   }
 427   st->print_cr("count(%u) entries(%u)", count(), entries);
 428   int total = count();
 429   for (row = 0; row < row_limit(); row++) {
 430     if (receiver(row) != nullptr) {
 431       total += receiver_count(row);
 432     }
 433   }
 434   for (row = 0; row < row_limit(); row++) {
 435     if (receiver(row) != nullptr) {
 436       tab(st);
 437       receiver(row)->print_value_on(st);
 438       st->print_cr("(%u %4.2f)", receiver_count(row), (float) receiver_count(row) / (float) total);
 439     }
 440   }
 441 }
 442 void ReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
 443   print_shared(st, "ReceiverTypeData", extra);
 444   print_receiver_data_on(st);
 445 }
 446 
 447 void VirtualCallData::print_data_on(outputStream* st, const char* extra) const {
 448   print_shared(st, "VirtualCallData", extra);
 449   print_receiver_data_on(st);
 450 }
 451 
 452 // ==================================================================
 453 // RetData
 454 //
 455 // A RetData is used to access profiling information for a ret bytecode.
 456 // It is composed of a count of the number of times that the ret has
 457 // been executed, followed by a series of triples of the form
 458 // (bci, count, di) which count the number of times that some bci was the
 459 // target of the ret and cache a corresponding displacement.
 460 
 461 void RetData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 462   for (uint row = 0; row < row_limit(); row++) {
 463     set_bci_displacement(row, -1);
 464     set_bci(row, no_bci);
 465   }
 466   // release so other threads see a consistent state.  bci is used as
 467   // a valid flag for bci_displacement.
 468   OrderAccess::release();
 469 }
 470 
 471 // This routine needs to atomically update the RetData structure, so the
 472 // caller needs to hold the RetData_lock before it gets here.  Since taking
 473 // the lock can block (and allow GC) and since RetData is a ProfileData is a
 474 // wrapper around a derived oop, taking the lock in _this_ method will
 475 // basically cause the 'this' pointer's _data field to contain junk after the
 476 // lock.  We require the caller to take the lock before making the ProfileData
 477 // structure.  Currently the only caller is InterpreterRuntime::update_mdp_for_ret
 478 address RetData::fixup_ret(int return_bci, MethodData* h_mdo) {
 479   // First find the mdp which corresponds to the return bci.
 480   address mdp = h_mdo->bci_to_dp(return_bci);
 481 
 482   // Now check to see if any of the cache slots are open.
 483   for (uint row = 0; row < row_limit(); row++) {
 484     if (bci(row) == no_bci) {
 485       set_bci_displacement(row, checked_cast<int>(mdp - dp()));
 486       set_bci_count(row, DataLayout::counter_increment);
 487       // Barrier to ensure displacement is written before the bci; allows
 488       // the interpreter to read displacement without fear of race condition.
 489       release_set_bci(row, return_bci);
 490       break;
 491     }
 492   }
 493   return mdp;
 494 }
 495 
 496 void RetData::print_data_on(outputStream* st, const char* extra) const {
 497   print_shared(st, "RetData", extra);
 498   uint row;
 499   int entries = 0;
 500   for (row = 0; row < row_limit(); row++) {
 501     if (bci(row) != no_bci)  entries++;
 502   }
 503   st->print_cr("count(%u) entries(%u)", count(), entries);
 504   for (row = 0; row < row_limit(); row++) {
 505     if (bci(row) != no_bci) {
 506       tab(st);
 507       st->print_cr("bci(%d: count(%u) displacement(%d))",
 508                    bci(row), bci_count(row), bci_displacement(row));
 509     }
 510   }
 511 }
 512 
 513 // ==================================================================
 514 // BranchData
 515 //
 516 // A BranchData is used to access profiling data for a two-way branch.
 517 // It consists of taken and not_taken counts as well as a data displacement
 518 // for the taken case.
 519 
 520 void BranchData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 521   assert(stream->bci() == bci(), "wrong pos");
 522   int target = stream->dest();
 523   int my_di = mdo->dp_to_di(dp());
 524   int target_di = mdo->bci_to_di(target);
 525   int offset = target_di - my_di;
 526   set_displacement(offset);
 527 }
 528 
 529 void BranchData::print_data_on(outputStream* st, const char* extra) const {
 530   print_shared(st, "BranchData", extra);
 531   st->print_cr("taken(%u) displacement(%d)",
 532                taken(), displacement());
 533   tab(st);
 534   st->print_cr("not taken(%u)", not_taken());
 535 }
 536 
 537 // ==================================================================
 538 // MultiBranchData
 539 //
 540 // A MultiBranchData is used to access profiling information for
 541 // a multi-way branch (*switch bytecodes).  It consists of a series
 542 // of (count, displacement) pairs, which count the number of times each
 543 // case was taken and specify the data displacement for each branch target.
 544 
 545 int MultiBranchData::compute_cell_count(BytecodeStream* stream) {
 546   int cell_count = 0;
 547   if (stream->code() == Bytecodes::_tableswitch) {
 548     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
 549     cell_count = 1 + per_case_cell_count * (1 + sw.length()); // 1 for default
 550   } else {
 551     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
 552     cell_count = 1 + per_case_cell_count * (sw.number_of_pairs() + 1); // 1 for default
 553   }
 554   return cell_count;
 555 }
 556 
 557 void MultiBranchData::post_initialize(BytecodeStream* stream,
 558                                       MethodData* mdo) {
 559   assert(stream->bci() == bci(), "wrong pos");
 560   int target;
 561   int my_di;
 562   int target_di;
 563   int offset;
 564   if (stream->code() == Bytecodes::_tableswitch) {
 565     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
 566     int len = sw.length();
 567     assert(array_len() == per_case_cell_count * (len + 1), "wrong len");
 568     for (int count = 0; count < len; count++) {
 569       target = sw.dest_offset_at(count) + bci();
 570       my_di = mdo->dp_to_di(dp());
 571       target_di = mdo->bci_to_di(target);
 572       offset = target_di - my_di;
 573       set_displacement_at(count, offset);
 574     }
 575     target = sw.default_offset() + bci();
 576     my_di = mdo->dp_to_di(dp());
 577     target_di = mdo->bci_to_di(target);
 578     offset = target_di - my_di;
 579     set_default_displacement(offset);
 580 
 581   } else {
 582     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
 583     int npairs = sw.number_of_pairs();
 584     assert(array_len() == per_case_cell_count * (npairs + 1), "wrong len");
 585     for (int count = 0; count < npairs; count++) {
 586       LookupswitchPair pair = sw.pair_at(count);
 587       target = pair.offset() + bci();
 588       my_di = mdo->dp_to_di(dp());
 589       target_di = mdo->bci_to_di(target);
 590       offset = target_di - my_di;
 591       set_displacement_at(count, offset);
 592     }
 593     target = sw.default_offset() + bci();
 594     my_di = mdo->dp_to_di(dp());
 595     target_di = mdo->bci_to_di(target);
 596     offset = target_di - my_di;
 597     set_default_displacement(offset);
 598   }
 599 }
 600 
 601 void MultiBranchData::print_data_on(outputStream* st, const char* extra) const {
 602   print_shared(st, "MultiBranchData", extra);
 603   st->print_cr("default_count(%u) displacement(%d)",
 604                default_count(), default_displacement());
 605   int cases = number_of_cases();
 606   for (int i = 0; i < cases; i++) {
 607     tab(st);
 608     st->print_cr("count(%u) displacement(%d)",
 609                  count_at(i), displacement_at(i));
 610   }
 611 }
 612 
 613 void ArgInfoData::print_data_on(outputStream* st, const char* extra) const {
 614   print_shared(st, "ArgInfoData", extra);
 615   int nargs = number_of_args();
 616   for (int i = 0; i < nargs; i++) {
 617     st->print("  0x%x", arg_modified(i));
 618   }
 619   st->cr();
 620 }
 621 
 622 int ParametersTypeData::compute_cell_count(Method* m) {
 623   if (!MethodData::profile_parameters_for_method(methodHandle(Thread::current(), m))) {
 624     return 0;
 625   }
 626   int max = TypeProfileParmsLimit == -1 ? INT_MAX : TypeProfileParmsLimit;
 627   int obj_args = TypeStackSlotEntries::compute_cell_count(m->signature(), !m->is_static(), max);
 628   if (obj_args > 0) {
 629     return obj_args + 1; // 1 cell for array len
 630   }
 631   return 0;
 632 }
 633 
 634 void ParametersTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
 635   _parameters.post_initialize(mdo->method()->signature(), !mdo->method()->is_static(), true);
 636 }
 637 
 638 bool ParametersTypeData::profiling_enabled() {
 639   return MethodData::profile_parameters();
 640 }
 641 
 642 void ParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
 643   print_shared(st, "ParametersTypeData", extra);
 644   tab(st);
 645   _parameters.print_data_on(st);
 646   st->cr();
 647 }
 648 
 649 void SpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
 650   print_shared(st, "SpeculativeTrapData", extra);
 651   tab(st);
 652   method()->print_short_name(st);
 653   st->cr();
 654 }
 655 
 656 // ==================================================================
 657 // MethodData*
 658 //
 659 // A MethodData* holds information which has been collected about
 660 // a method.
 661 
 662 MethodData* MethodData::allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS) {
 663   assert(!THREAD->owns_locks(), "Should not own any locks");
 664   int size = MethodData::compute_allocation_size_in_words(method);
 665 
 666   return new (loader_data, size, MetaspaceObj::MethodDataType, THREAD)
 667     MethodData(method);
 668 }
 669 
 670 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
 671   switch (code) {
 672   case Bytecodes::_checkcast:
 673   case Bytecodes::_instanceof:
 674   case Bytecodes::_aastore:
 675     if (TypeProfileCasts) {
 676       return ReceiverTypeData::static_cell_count();
 677     } else {
 678       return BitData::static_cell_count();
 679     }
 680   case Bytecodes::_invokespecial:
 681   case Bytecodes::_invokestatic:
 682     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 683       return variable_cell_count;
 684     } else {
 685       return CounterData::static_cell_count();
 686     }
 687   case Bytecodes::_goto:
 688   case Bytecodes::_goto_w:
 689   case Bytecodes::_jsr:
 690   case Bytecodes::_jsr_w:
 691     return JumpData::static_cell_count();
 692   case Bytecodes::_invokevirtual:
 693   case Bytecodes::_invokeinterface:
 694     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 695       return variable_cell_count;
 696     } else {
 697       return VirtualCallData::static_cell_count();
 698     }
 699   case Bytecodes::_invokedynamic:
 700     if (MethodData::profile_arguments() || MethodData::profile_return()) {
 701       return variable_cell_count;
 702     } else {
 703       return CounterData::static_cell_count();
 704     }
 705   case Bytecodes::_ret:
 706     return RetData::static_cell_count();
 707   case Bytecodes::_ifeq:
 708   case Bytecodes::_ifne:
 709   case Bytecodes::_iflt:
 710   case Bytecodes::_ifge:
 711   case Bytecodes::_ifgt:
 712   case Bytecodes::_ifle:
 713   case Bytecodes::_if_icmpeq:
 714   case Bytecodes::_if_icmpne:
 715   case Bytecodes::_if_icmplt:
 716   case Bytecodes::_if_icmpge:
 717   case Bytecodes::_if_icmpgt:
 718   case Bytecodes::_if_icmple:
 719   case Bytecodes::_if_acmpeq:
 720   case Bytecodes::_if_acmpne:
 721   case Bytecodes::_ifnull:
 722   case Bytecodes::_ifnonnull:
 723     return BranchData::static_cell_count();
 724   case Bytecodes::_lookupswitch:
 725   case Bytecodes::_tableswitch:
 726     return variable_cell_count;
 727   default:
 728     return no_profile_data;
 729   }
 730 }
 731 
 732 // Compute the size of the profiling information corresponding to
 733 // the current bytecode.
 734 int MethodData::compute_data_size(BytecodeStream* stream) {
 735   int cell_count = bytecode_cell_count(stream->code());
 736   if (cell_count == no_profile_data) {
 737     return 0;
 738   }
 739   if (cell_count == variable_cell_count) {
 740     switch (stream->code()) {
 741     case Bytecodes::_lookupswitch:
 742     case Bytecodes::_tableswitch:
 743       cell_count = MultiBranchData::compute_cell_count(stream);
 744       break;
 745     case Bytecodes::_invokespecial:
 746     case Bytecodes::_invokestatic:
 747     case Bytecodes::_invokedynamic:
 748       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
 749       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
 750           profile_return_for_invoke(stream->method(), stream->bci())) {
 751         cell_count = CallTypeData::compute_cell_count(stream);
 752       } else {
 753         cell_count = CounterData::static_cell_count();
 754       }
 755       break;
 756     case Bytecodes::_invokevirtual:
 757     case Bytecodes::_invokeinterface: {
 758       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
 759       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
 760           profile_return_for_invoke(stream->method(), stream->bci())) {
 761         cell_count = VirtualCallTypeData::compute_cell_count(stream);
 762       } else {
 763         cell_count = VirtualCallData::static_cell_count();
 764       }
 765       break;
 766     }
 767     default:
 768       fatal("unexpected bytecode for var length profile data");
 769     }
 770   }
 771   // Note:  cell_count might be zero, meaning that there is just
 772   //        a DataLayout header, with no extra cells.
 773   assert(cell_count >= 0, "sanity");
 774   return DataLayout::compute_size_in_bytes(cell_count);
 775 }
 776 
 777 bool MethodData::is_speculative_trap_bytecode(Bytecodes::Code code) {
 778   // Bytecodes for which we may use speculation
 779   switch (code) {
 780   case Bytecodes::_checkcast:
 781   case Bytecodes::_instanceof:
 782   case Bytecodes::_aastore:
 783   case Bytecodes::_invokevirtual:
 784   case Bytecodes::_invokeinterface:
 785   case Bytecodes::_if_acmpeq:
 786   case Bytecodes::_if_acmpne:
 787   case Bytecodes::_ifnull:
 788   case Bytecodes::_ifnonnull:
 789   case Bytecodes::_invokestatic:
 790 #ifdef COMPILER2
 791     if (CompilerConfig::is_c2_enabled()) {
 792       return UseTypeSpeculation;
 793     }
 794 #endif
 795   default:
 796     return false;
 797   }
 798   return false;
 799 }
 800 
 801 #if INCLUDE_JVMCI
 802 
 803 void* FailedSpeculation::operator new(size_t size, size_t fs_size) throw() {
 804   return CHeapObj<mtCompiler>::operator new(fs_size, std::nothrow);
 805 }
 806 
 807 FailedSpeculation::FailedSpeculation(address speculation, int speculation_len) : _data_len(speculation_len), _next(nullptr) {
 808   memcpy(data(), speculation, speculation_len);
 809 }
 810 
 811 // A heuristic check to detect nmethods that outlive a failed speculations list.
 812 static void guarantee_failed_speculations_alive(nmethod* nm, FailedSpeculation** failed_speculations_address) {
 813   jlong head = (jlong)(address) *failed_speculations_address;
 814   if ((head & 0x1) == 0x1) {
 815     stringStream st;
 816     if (nm != nullptr) {
 817       st.print("%d", nm->compile_id());
 818       Method* method = nm->method();
 819       st.print_raw("{");
 820       if (method != nullptr) {
 821         method->print_name(&st);
 822       } else {
 823         const char* jvmci_name = nm->jvmci_name();
 824         if (jvmci_name != nullptr) {
 825           st.print_raw(jvmci_name);
 826         }
 827       }
 828       st.print_raw("}");
 829     } else {
 830       st.print("<unknown>");
 831     }
 832     fatal("Adding to failed speculations list that appears to have been freed. Source: %s", st.as_string());
 833   }
 834 }
 835 
 836 bool FailedSpeculation::add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len) {
 837   assert(failed_speculations_address != nullptr, "must be");
 838   size_t fs_size = sizeof(FailedSpeculation) + speculation_len;
 839 
 840   guarantee_failed_speculations_alive(nm, failed_speculations_address);
 841 
 842   FailedSpeculation** cursor = failed_speculations_address;
 843   FailedSpeculation* fs = nullptr;
 844   do {
 845     if (*cursor == nullptr) {
 846       if (fs == nullptr) {
 847         // lazily allocate FailedSpeculation
 848         fs = new (fs_size) FailedSpeculation(speculation, speculation_len);
 849         if (fs == nullptr) {
 850           // no memory -> ignore failed speculation
 851           return false;
 852         }
 853         guarantee(is_aligned(fs, sizeof(FailedSpeculation*)), "FailedSpeculation objects must be pointer aligned");
 854       }
 855       FailedSpeculation* old_fs = Atomic::cmpxchg(cursor, (FailedSpeculation*) nullptr, fs);
 856       if (old_fs == nullptr) {
 857         // Successfully appended fs to end of the list
 858         return true;
 859       }
 860     }
 861     guarantee(*cursor != nullptr, "cursor must point to non-null FailedSpeculation");
 862     // check if the current entry matches this thread's failed speculation
 863     if ((*cursor)->data_len() == speculation_len && memcmp(speculation, (*cursor)->data(), speculation_len) == 0) {
 864       if (fs != nullptr) {
 865         delete fs;
 866       }
 867       return false;
 868     }
 869     cursor = (*cursor)->next_adr();
 870   } while (true);
 871 }
 872 
 873 void FailedSpeculation::free_failed_speculations(FailedSpeculation** failed_speculations_address) {
 874   assert(failed_speculations_address != nullptr, "must be");
 875   FailedSpeculation* fs = *failed_speculations_address;
 876   while (fs != nullptr) {
 877     FailedSpeculation* next = fs->next();
 878     delete fs;
 879     fs = next;
 880   }
 881 
 882   // Write an unaligned value to failed_speculations_address to denote
 883   // that it is no longer a valid pointer. This is allows for the check
 884   // in add_failed_speculation against adding to a freed failed
 885   // speculations list.
 886   long* head = (long*) failed_speculations_address;
 887   (*head) = (*head) | 0x1;
 888 }
 889 #endif // INCLUDE_JVMCI
 890 
 891 int MethodData::compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps) {
 892 #if INCLUDE_JVMCI
 893   if (ProfileTraps) {
 894     // Assume that up to 30% of the possibly trapping BCIs with no MDP will need to allocate one.
 895     int extra_data_count = MIN2(empty_bc_count, MAX2(4, (empty_bc_count * 30) / 100));
 896 
 897     // Make sure we have a minimum number of extra data slots to
 898     // allocate SpeculativeTrapData entries. We would want to have one
 899     // entry per compilation that inlines this method and for which
 900     // some type speculation assumption fails. So the room we need for
 901     // the SpeculativeTrapData entries doesn't directly depend on the
 902     // size of the method. Because it's hard to estimate, we reserve
 903     // space for an arbitrary number of entries.
 904     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
 905       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
 906 
 907     return MAX2(extra_data_count, spec_data_count);
 908   } else {
 909     return 0;
 910   }
 911 #else // INCLUDE_JVMCI
 912   if (ProfileTraps) {
 913     // Assume that up to 3% of BCIs with no MDP will need to allocate one.
 914     int extra_data_count = (uint)(empty_bc_count * 3) / 128 + 1;
 915     // If the method is large, let the extra BCIs grow numerous (to ~1%).
 916     int one_percent_of_data
 917       = (uint)data_size / (DataLayout::header_size_in_bytes()*128);
 918     if (extra_data_count < one_percent_of_data)
 919       extra_data_count = one_percent_of_data;
 920     if (extra_data_count > empty_bc_count)
 921       extra_data_count = empty_bc_count;  // no need for more
 922 
 923     // Make sure we have a minimum number of extra data slots to
 924     // allocate SpeculativeTrapData entries. We would want to have one
 925     // entry per compilation that inlines this method and for which
 926     // some type speculation assumption fails. So the room we need for
 927     // the SpeculativeTrapData entries doesn't directly depend on the
 928     // size of the method. Because it's hard to estimate, we reserve
 929     // space for an arbitrary number of entries.
 930     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
 931       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
 932 
 933     return MAX2(extra_data_count, spec_data_count);
 934   } else {
 935     return 0;
 936   }
 937 #endif // INCLUDE_JVMCI
 938 }
 939 
 940 // Compute the size of the MethodData* necessary to store
 941 // profiling information about a given method.  Size is in bytes.
 942 int MethodData::compute_allocation_size_in_bytes(const methodHandle& method) {
 943   int data_size = 0;
 944   BytecodeStream stream(method);
 945   Bytecodes::Code c;
 946   int empty_bc_count = 0;  // number of bytecodes lacking data
 947   bool needs_speculative_traps = false;
 948   while ((c = stream.next()) >= 0) {
 949     int size_in_bytes = compute_data_size(&stream);
 950     data_size += size_in_bytes;
 951     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
 952     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
 953   }
 954   int object_size = in_bytes(data_offset()) + data_size;
 955 
 956   // Add some extra DataLayout cells (at least one) to track stray traps.
 957   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
 958   object_size += extra_data_count * DataLayout::compute_size_in_bytes(0);
 959 
 960   // Add a cell to record information about modified arguments.
 961   int arg_size = method->size_of_parameters();
 962   object_size += DataLayout::compute_size_in_bytes(arg_size+1);
 963 
 964   // Reserve room for an area of the MDO dedicated to profiling of
 965   // parameters
 966   int args_cell = ParametersTypeData::compute_cell_count(method());
 967   if (args_cell > 0) {
 968     object_size += DataLayout::compute_size_in_bytes(args_cell);
 969   }
 970 
 971   if (ProfileExceptionHandlers && method()->has_exception_handler()) {
 972     int num_exception_handlers = method()->exception_table_length();
 973     object_size += num_exception_handlers * single_exception_handler_data_size();
 974   }
 975 
 976   return object_size;
 977 }
 978 
 979 // Compute the size of the MethodData* necessary to store
 980 // profiling information about a given method.  Size is in words
 981 int MethodData::compute_allocation_size_in_words(const methodHandle& method) {
 982   int byte_size = compute_allocation_size_in_bytes(method);
 983   int word_size = align_up(byte_size, BytesPerWord) / BytesPerWord;
 984   return align_metadata_size(word_size);
 985 }
 986 
 987 // Initialize an individual data segment.  Returns the size of
 988 // the segment in bytes.
 989 int MethodData::initialize_data(BytecodeStream* stream,
 990                                        int data_index) {
 991   int cell_count = -1;
 992   u1 tag = DataLayout::no_tag;
 993   DataLayout* data_layout = data_layout_at(data_index);
 994   Bytecodes::Code c = stream->code();
 995   switch (c) {
 996   case Bytecodes::_checkcast:
 997   case Bytecodes::_instanceof:
 998   case Bytecodes::_aastore:
 999     if (TypeProfileCasts) {
1000       cell_count = ReceiverTypeData::static_cell_count();
1001       tag = DataLayout::receiver_type_data_tag;
1002     } else {
1003       cell_count = BitData::static_cell_count();
1004       tag = DataLayout::bit_data_tag;
1005     }
1006     break;
1007   case Bytecodes::_invokespecial:
1008   case Bytecodes::_invokestatic: {
1009     int counter_data_cell_count = CounterData::static_cell_count();
1010     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1011         profile_return_for_invoke(stream->method(), stream->bci())) {
1012       cell_count = CallTypeData::compute_cell_count(stream);
1013     } else {
1014       cell_count = counter_data_cell_count;
1015     }
1016     if (cell_count > counter_data_cell_count) {
1017       tag = DataLayout::call_type_data_tag;
1018     } else {
1019       tag = DataLayout::counter_data_tag;
1020     }
1021     break;
1022   }
1023   case Bytecodes::_goto:
1024   case Bytecodes::_goto_w:
1025   case Bytecodes::_jsr:
1026   case Bytecodes::_jsr_w:
1027     cell_count = JumpData::static_cell_count();
1028     tag = DataLayout::jump_data_tag;
1029     break;
1030   case Bytecodes::_invokevirtual:
1031   case Bytecodes::_invokeinterface: {
1032     int virtual_call_data_cell_count = VirtualCallData::static_cell_count();
1033     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1034         profile_return_for_invoke(stream->method(), stream->bci())) {
1035       cell_count = VirtualCallTypeData::compute_cell_count(stream);
1036     } else {
1037       cell_count = virtual_call_data_cell_count;
1038     }
1039     if (cell_count > virtual_call_data_cell_count) {
1040       tag = DataLayout::virtual_call_type_data_tag;
1041     } else {
1042       tag = DataLayout::virtual_call_data_tag;
1043     }
1044     break;
1045   }
1046   case Bytecodes::_invokedynamic: {
1047     // %%% should make a type profile for any invokedynamic that takes a ref argument
1048     int counter_data_cell_count = CounterData::static_cell_count();
1049     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1050         profile_return_for_invoke(stream->method(), stream->bci())) {
1051       cell_count = CallTypeData::compute_cell_count(stream);
1052     } else {
1053       cell_count = counter_data_cell_count;
1054     }
1055     if (cell_count > counter_data_cell_count) {
1056       tag = DataLayout::call_type_data_tag;
1057     } else {
1058       tag = DataLayout::counter_data_tag;
1059     }
1060     break;
1061   }
1062   case Bytecodes::_ret:
1063     cell_count = RetData::static_cell_count();
1064     tag = DataLayout::ret_data_tag;
1065     break;
1066   case Bytecodes::_ifeq:
1067   case Bytecodes::_ifne:
1068   case Bytecodes::_iflt:
1069   case Bytecodes::_ifge:
1070   case Bytecodes::_ifgt:
1071   case Bytecodes::_ifle:
1072   case Bytecodes::_if_icmpeq:
1073   case Bytecodes::_if_icmpne:
1074   case Bytecodes::_if_icmplt:
1075   case Bytecodes::_if_icmpge:
1076   case Bytecodes::_if_icmpgt:
1077   case Bytecodes::_if_icmple:
1078   case Bytecodes::_if_acmpeq:
1079   case Bytecodes::_if_acmpne:
1080   case Bytecodes::_ifnull:
1081   case Bytecodes::_ifnonnull:
1082     cell_count = BranchData::static_cell_count();
1083     tag = DataLayout::branch_data_tag;
1084     break;
1085   case Bytecodes::_lookupswitch:
1086   case Bytecodes::_tableswitch:
1087     cell_count = MultiBranchData::compute_cell_count(stream);
1088     tag = DataLayout::multi_branch_data_tag;
1089     break;
1090   default:
1091     break;
1092   }
1093   assert(tag == DataLayout::multi_branch_data_tag ||
1094          ((MethodData::profile_arguments() || MethodData::profile_return()) &&
1095           (tag == DataLayout::call_type_data_tag ||
1096            tag == DataLayout::counter_data_tag ||
1097            tag == DataLayout::virtual_call_type_data_tag ||
1098            tag == DataLayout::virtual_call_data_tag)) ||
1099          cell_count == bytecode_cell_count(c), "cell counts must agree");
1100   if (cell_count >= 0) {
1101     assert(tag != DataLayout::no_tag, "bad tag");
1102     assert(bytecode_has_profile(c), "agree w/ BHP");
1103     data_layout->initialize(tag, checked_cast<u2>(stream->bci()), cell_count);
1104     return DataLayout::compute_size_in_bytes(cell_count);
1105   } else {
1106     assert(!bytecode_has_profile(c), "agree w/ !BHP");
1107     return 0;
1108   }
1109 }
1110 
1111 // Get the data at an arbitrary (sort of) data index.
1112 ProfileData* MethodData::data_at(int data_index) const {
1113   if (out_of_bounds(data_index)) {
1114     return nullptr;
1115   }
1116   DataLayout* data_layout = data_layout_at(data_index);
1117   return data_layout->data_in();
1118 }
1119 
1120 int DataLayout::cell_count() {
1121   switch (tag()) {
1122   case DataLayout::no_tag:
1123   default:
1124     ShouldNotReachHere();
1125     return 0;
1126   case DataLayout::bit_data_tag:
1127     return BitData::static_cell_count();
1128   case DataLayout::counter_data_tag:
1129     return CounterData::static_cell_count();
1130   case DataLayout::jump_data_tag:
1131     return JumpData::static_cell_count();
1132   case DataLayout::receiver_type_data_tag:
1133     return ReceiverTypeData::static_cell_count();
1134   case DataLayout::virtual_call_data_tag:
1135     return VirtualCallData::static_cell_count();
1136   case DataLayout::ret_data_tag:
1137     return RetData::static_cell_count();
1138   case DataLayout::branch_data_tag:
1139     return BranchData::static_cell_count();
1140   case DataLayout::multi_branch_data_tag:
1141     return ((new MultiBranchData(this))->cell_count());
1142   case DataLayout::arg_info_data_tag:
1143     return ((new ArgInfoData(this))->cell_count());
1144   case DataLayout::call_type_data_tag:
1145     return ((new CallTypeData(this))->cell_count());
1146   case DataLayout::virtual_call_type_data_tag:
1147     return ((new VirtualCallTypeData(this))->cell_count());
1148   case DataLayout::parameters_type_data_tag:
1149     return ((new ParametersTypeData(this))->cell_count());
1150   case DataLayout::speculative_trap_data_tag:
1151     return SpeculativeTrapData::static_cell_count();
1152   }
1153 }
1154 ProfileData* DataLayout::data_in() {
1155   switch (tag()) {
1156   case DataLayout::no_tag:
1157   default:
1158     ShouldNotReachHere();
1159     return nullptr;
1160   case DataLayout::bit_data_tag:
1161     return new BitData(this);
1162   case DataLayout::counter_data_tag:
1163     return new CounterData(this);
1164   case DataLayout::jump_data_tag:
1165     return new JumpData(this);
1166   case DataLayout::receiver_type_data_tag:
1167     return new ReceiverTypeData(this);
1168   case DataLayout::virtual_call_data_tag:
1169     return new VirtualCallData(this);
1170   case DataLayout::ret_data_tag:
1171     return new RetData(this);
1172   case DataLayout::branch_data_tag:
1173     return new BranchData(this);
1174   case DataLayout::multi_branch_data_tag:
1175     return new MultiBranchData(this);
1176   case DataLayout::arg_info_data_tag:
1177     return new ArgInfoData(this);
1178   case DataLayout::call_type_data_tag:
1179     return new CallTypeData(this);
1180   case DataLayout::virtual_call_type_data_tag:
1181     return new VirtualCallTypeData(this);
1182   case DataLayout::parameters_type_data_tag:
1183     return new ParametersTypeData(this);
1184   case DataLayout::speculative_trap_data_tag:
1185     return new SpeculativeTrapData(this);
1186   }
1187 }
1188 
1189 // Iteration over data.
1190 ProfileData* MethodData::next_data(ProfileData* current) const {
1191   int current_index = dp_to_di(current->dp());
1192   int next_index = current_index + current->size_in_bytes();
1193   ProfileData* next = data_at(next_index);
1194   return next;
1195 }
1196 
1197 DataLayout* MethodData::next_data_layout(DataLayout* current) const {
1198   int current_index = dp_to_di((address)current);
1199   int next_index = current_index + current->size_in_bytes();
1200   if (out_of_bounds(next_index)) {
1201     return nullptr;
1202   }
1203   DataLayout* next = data_layout_at(next_index);
1204   return next;
1205 }
1206 
1207 // Give each of the data entries a chance to perform specific
1208 // data initialization.
1209 void MethodData::post_initialize(BytecodeStream* stream) {
1210   ResourceMark rm;
1211   ProfileData* data;
1212   for (data = first_data(); is_valid(data); data = next_data(data)) {
1213     stream->set_start(data->bci());
1214     stream->next();
1215     data->post_initialize(stream, this);
1216   }
1217   if (_parameters_type_data_di != no_parameters) {
1218     parameters_type_data()->post_initialize(nullptr, this);
1219   }
1220 }
1221 
1222 // Initialize the MethodData* corresponding to a given method.
1223 MethodData::MethodData(const methodHandle& method)
1224   : _method(method()),
1225     // Holds Compile_lock
1226     _extra_data_lock(Mutex::nosafepoint, "MDOExtraData_lock"),
1227     _compiler_counters(),
1228     _parameters_type_data_di(parameters_uninitialized) {
1229   initialize();
1230 }
1231 
1232 // Reinitialize the storage of an existing MDO at a safepoint.  Doing it this way will ensure it's
1233 // not being accessed while the contents are being rewritten.
1234 class VM_ReinitializeMDO: public VM_Operation {
1235  private:
1236   MethodData* _mdo;
1237  public:
1238   VM_ReinitializeMDO(MethodData* mdo): _mdo(mdo) {}
1239   VMOp_Type type() const                         { return VMOp_ReinitializeMDO; }
1240   void doit() {
1241     // The extra data is being zero'd, we'd like to acquire the extra_data_lock but it can't be held
1242     // over a safepoint.  This means that we don't actually need to acquire the lock.
1243     _mdo->initialize();
1244   }
1245   bool allow_nested_vm_operations() const        { return true; }
1246 };
1247 
1248 void MethodData::reinitialize() {
1249   VM_ReinitializeMDO op(this);
1250   VMThread::execute(&op);
1251 }
1252 
1253 
1254 void MethodData::initialize() {
1255   Thread* thread = Thread::current();
1256   NoSafepointVerifier no_safepoint;  // init function atomic wrt GC
1257   ResourceMark rm(thread);
1258 
1259   init();
1260   set_creation_mileage(mileage_of(method()));
1261 
1262   // Go through the bytecodes and allocate and initialize the
1263   // corresponding data cells.
1264   int data_size = 0;
1265   int empty_bc_count = 0;  // number of bytecodes lacking data
1266   _data[0] = 0;  // apparently not set below.
1267   BytecodeStream stream(methodHandle(thread, method()));
1268   Bytecodes::Code c;
1269   bool needs_speculative_traps = false;
1270   while ((c = stream.next()) >= 0) {
1271     int size_in_bytes = initialize_data(&stream, data_size);
1272     data_size += size_in_bytes;
1273     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
1274     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
1275   }
1276   _data_size = data_size;
1277   int object_size = in_bytes(data_offset()) + data_size;
1278 
1279   // Add some extra DataLayout cells (at least one) to track stray traps.
1280   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
1281   int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);
1282 
1283   // Let's zero the space for the extra data
1284   if (extra_size > 0) {
1285     Copy::zero_to_bytes(((address)_data) + data_size, extra_size);
1286   }
1287 
1288   // Add a cell to record information about modified arguments.
1289   // Set up _args_modified array after traps cells so that
1290   // the code for traps cells works.
1291   DataLayout *dp = data_layout_at(data_size + extra_size);
1292 
1293   int arg_size = method()->size_of_parameters();
1294   dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);
1295 
1296   int arg_data_size = DataLayout::compute_size_in_bytes(arg_size+1);
1297   object_size += extra_size + arg_data_size;
1298 
1299   int parms_cell = ParametersTypeData::compute_cell_count(method());
1300   // If we are profiling parameters, we reserved an area near the end
1301   // of the MDO after the slots for bytecodes (because there's no bci
1302   // for method entry so they don't fit with the framework for the
1303   // profiling of bytecodes). We store the offset within the MDO of
1304   // this area (or -1 if no parameter is profiled)
1305   int parm_data_size = 0;
1306   if (parms_cell > 0) {
1307     parm_data_size = DataLayout::compute_size_in_bytes(parms_cell);
1308     object_size += parm_data_size;
1309     _parameters_type_data_di = data_size + extra_size + arg_data_size;
1310     DataLayout *dp = data_layout_at(data_size + extra_size + arg_data_size);
1311     dp->initialize(DataLayout::parameters_type_data_tag, 0, parms_cell);
1312   } else {
1313     _parameters_type_data_di = no_parameters;
1314   }
1315 
1316   _exception_handler_data_di = data_size + extra_size + arg_data_size + parm_data_size;
1317   if (ProfileExceptionHandlers && method()->has_exception_handler()) {
1318     int num_exception_handlers = method()->exception_table_length();
1319     object_size += num_exception_handlers * single_exception_handler_data_size();
1320     ExceptionTableElement* exception_handlers = method()->exception_table_start();
1321     for (int i = 0; i < num_exception_handlers; i++) {
1322       DataLayout *dp = exception_handler_data_at(i);
1323       dp->initialize(DataLayout::bit_data_tag, exception_handlers[i].handler_pc, single_exception_handler_data_cell_count());
1324     }
1325   }
1326 
1327   // Set an initial hint. Don't use set_hint_di() because
1328   // first_di() may be out of bounds if data_size is 0.
1329   // In that situation, _hint_di is never used, but at
1330   // least well-defined.
1331   _hint_di = first_di();
1332 
1333   post_initialize(&stream);
1334 
1335   assert(object_size == compute_allocation_size_in_bytes(methodHandle(thread, _method)), "MethodData: computed size != initialized size");
1336   set_size(object_size);
1337 }
1338 
1339 void MethodData::init() {
1340   _compiler_counters = CompilerCounters(); // reset compiler counters
1341   _invocation_counter.init();
1342   _backedge_counter.init();
1343   _invocation_counter_start = 0;
1344   _backedge_counter_start = 0;
1345 
1346   // Set per-method invoke- and backedge mask.
1347   double scale = 1.0;
1348   methodHandle mh(Thread::current(), _method);
1349   CompilerOracle::has_option_value(mh, CompileCommandEnum::CompileThresholdScaling, scale);
1350   _invoke_mask = (int)right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1351   _backedge_mask = (int)right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1352 
1353   _tenure_traps = 0;
1354   _num_loops = 0;
1355   _num_blocks = 0;
1356   _would_profile = unknown;
1357 
1358 #if INCLUDE_JVMCI
1359   _jvmci_ir_size = 0;
1360   _failed_speculations = nullptr;
1361 #endif
1362 
1363   // Initialize escape flags.
1364   clear_escape_info();
1365 }
1366 
1367 // Get a measure of how much mileage the method has on it.
1368 int MethodData::mileage_of(Method* method) {
1369   return MAX2(method->invocation_count(), method->backedge_count());
1370 }
1371 
1372 bool MethodData::is_mature() const {
1373   return CompilationPolicy::is_mature(_method);
1374 }
1375 
1376 // Translate a bci to its corresponding data index (di).
1377 address MethodData::bci_to_dp(int bci) {
1378   ResourceMark rm;
1379   DataLayout* data = data_layout_before(bci);
1380   DataLayout* prev = nullptr;
1381   for ( ; is_valid(data); data = next_data_layout(data)) {
1382     if (data->bci() >= bci) {
1383       if (data->bci() == bci)  set_hint_di(dp_to_di((address)data));
1384       else if (prev != nullptr)   set_hint_di(dp_to_di((address)prev));
1385       return (address)data;
1386     }
1387     prev = data;
1388   }
1389   return (address)limit_data_position();
1390 }
1391 
1392 // Translate a bci to its corresponding data, or null.
1393 ProfileData* MethodData::bci_to_data(int bci) {
1394   check_extra_data_locked();
1395 
1396   DataLayout* data = data_layout_before(bci);
1397   for ( ; is_valid(data); data = next_data_layout(data)) {
1398     if (data->bci() == bci) {
1399       set_hint_di(dp_to_di((address)data));
1400       return data->data_in();
1401     } else if (data->bci() > bci) {
1402       break;
1403     }
1404   }
1405   return bci_to_extra_data(bci, nullptr, false);
1406 }
1407 
1408 DataLayout* MethodData::exception_handler_bci_to_data_helper(int bci) {
1409   assert(ProfileExceptionHandlers, "not profiling");
1410   for (int i = 0; i < num_exception_handler_data(); i++) {
1411     DataLayout* exception_handler_data = exception_handler_data_at(i);
1412     if (exception_handler_data->bci() == bci) {
1413       return exception_handler_data;
1414     }
1415   }
1416   return nullptr;
1417 }
1418 
1419 BitData* MethodData::exception_handler_bci_to_data_or_null(int bci) {
1420   DataLayout* data = exception_handler_bci_to_data_helper(bci);
1421   return data != nullptr ? new BitData(data) : nullptr;
1422 }
1423 
1424 BitData MethodData::exception_handler_bci_to_data(int bci) {
1425   DataLayout* data = exception_handler_bci_to_data_helper(bci);
1426   assert(data != nullptr, "invalid bci");
1427   return BitData(data);
1428 }
1429 
1430 DataLayout* MethodData::next_extra(DataLayout* dp) {
1431   int nb_cells = 0;
1432   switch(dp->tag()) {
1433   case DataLayout::bit_data_tag:
1434   case DataLayout::no_tag:
1435     nb_cells = BitData::static_cell_count();
1436     break;
1437   case DataLayout::speculative_trap_data_tag:
1438     nb_cells = SpeculativeTrapData::static_cell_count();
1439     break;
1440   default:
1441     fatal("unexpected tag %d", dp->tag());
1442   }
1443   return (DataLayout*)((address)dp + DataLayout::compute_size_in_bytes(nb_cells));
1444 }
1445 
1446 ProfileData* MethodData::bci_to_extra_data_find(int bci, Method* m, DataLayout*& dp) {
1447   check_extra_data_locked();
1448 
1449   DataLayout* end = args_data_limit();
1450 
1451   for (;; dp = next_extra(dp)) {
1452     assert(dp < end, "moved past end of extra data");
1453     // No need for "Atomic::load_acquire" ops,
1454     // since the data structure is monotonic.
1455     switch(dp->tag()) {
1456     case DataLayout::no_tag:
1457       return nullptr;
1458     case DataLayout::arg_info_data_tag:
1459       dp = end;
1460       return nullptr; // ArgInfoData is at the end of extra data section.
1461     case DataLayout::bit_data_tag:
1462       if (m == nullptr && dp->bci() == bci) {
1463         return new BitData(dp);
1464       }
1465       break;
1466     case DataLayout::speculative_trap_data_tag:
1467       if (m != nullptr) {
1468         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1469         if (dp->bci() == bci) {
1470           assert(data->method() != nullptr, "method must be set");
1471           if (data->method() == m) {
1472             return data;
1473           }
1474         }
1475       }
1476       break;
1477     default:
1478       fatal("unexpected tag %d", dp->tag());
1479     }
1480   }
1481   return nullptr;
1482 }
1483 
1484 
1485 // Translate a bci to its corresponding extra data, or null.
1486 ProfileData* MethodData::bci_to_extra_data(int bci, Method* m, bool create_if_missing) {
1487   check_extra_data_locked();
1488 
1489   // This code assumes an entry for a SpeculativeTrapData is 2 cells
1490   assert(2*DataLayout::compute_size_in_bytes(BitData::static_cell_count()) ==
1491          DataLayout::compute_size_in_bytes(SpeculativeTrapData::static_cell_count()),
1492          "code needs to be adjusted");
1493 
1494   // Do not create one of these if method has been redefined.
1495   if (m != nullptr && m->is_old()) {
1496     return nullptr;
1497   }
1498 
1499   DataLayout* dp  = extra_data_base();
1500   DataLayout* end = args_data_limit();
1501 
1502   // Find if already exists
1503   ProfileData* result = bci_to_extra_data_find(bci, m, dp);
1504   if (result != nullptr || dp >= end) {
1505     return result;
1506   }
1507 
1508   if (create_if_missing) {
1509     // Not found -> Allocate
1510     assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != nullptr), "should be free");
1511     assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
1512     u1 tag = m == nullptr ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
1513     // SpeculativeTrapData is 2 slots. Make sure we have room.
1514     if (m != nullptr && next_extra(dp)->tag() != DataLayout::no_tag) {
1515       return nullptr;
1516     }
1517     DataLayout temp;
1518     temp.initialize(tag, checked_cast<u2>(bci), 0);
1519 
1520     dp->set_header(temp.header());
1521     assert(dp->tag() == tag, "sane");
1522     assert(dp->bci() == bci, "no concurrent allocation");
1523     if (tag == DataLayout::bit_data_tag) {
1524       return new BitData(dp);
1525     } else {
1526       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1527       data->set_method(m);
1528       return data;
1529     }
1530   }
1531   return nullptr;
1532 }
1533 
1534 ArgInfoData *MethodData::arg_info() {
1535   DataLayout* dp    = extra_data_base();
1536   DataLayout* end   = args_data_limit();
1537   for (; dp < end; dp = next_extra(dp)) {
1538     if (dp->tag() == DataLayout::arg_info_data_tag)
1539       return new ArgInfoData(dp);
1540   }
1541   return nullptr;
1542 }
1543 
1544 // Printing
1545 
1546 void MethodData::print_on(outputStream* st) const {
1547   assert(is_methodData(), "should be method data");
1548   st->print("method data for ");
1549   method()->print_value_on(st);
1550   st->cr();
1551   print_data_on(st);
1552 }
1553 
1554 void MethodData::print_value_on(outputStream* st) const {
1555   assert(is_methodData(), "should be method data");
1556   st->print("method data for ");
1557   method()->print_value_on(st);
1558 }
1559 
1560 void MethodData::print_data_on(outputStream* st) const {
1561   ConditionalMutexLocker ml(extra_data_lock(), !extra_data_lock()->owned_by_self(),
1562                             Mutex::_no_safepoint_check_flag);
1563   ResourceMark rm;
1564   ProfileData* data = first_data();
1565   if (_parameters_type_data_di != no_parameters) {
1566     parameters_type_data()->print_data_on(st);
1567   }
1568   for ( ; is_valid(data); data = next_data(data)) {
1569     st->print("%d", dp_to_di(data->dp()));
1570     st->fill_to(6);
1571     data->print_data_on(st, this);
1572   }
1573 
1574   st->print_cr("--- Extra data:");
1575   DataLayout* dp    = extra_data_base();
1576   DataLayout* end   = args_data_limit();
1577   for (;; dp = next_extra(dp)) {
1578     assert(dp < end, "moved past end of extra data");
1579     // No need for "Atomic::load_acquire" ops,
1580     // since the data structure is monotonic.
1581     switch(dp->tag()) {
1582     case DataLayout::no_tag:
1583       continue;
1584     case DataLayout::bit_data_tag:
1585       data = new BitData(dp);
1586       break;
1587     case DataLayout::speculative_trap_data_tag:
1588       data = new SpeculativeTrapData(dp);
1589       break;
1590     case DataLayout::arg_info_data_tag:
1591       data = new ArgInfoData(dp);
1592       dp = end; // ArgInfoData is at the end of extra data section.
1593       break;
1594     default:
1595       fatal("unexpected tag %d", dp->tag());
1596     }
1597     st->print("%d", dp_to_di(data->dp()));
1598     st->fill_to(6);
1599     data->print_data_on(st);
1600     if (dp >= end) return;
1601   }
1602 }
1603 
1604 // Verification
1605 
1606 void MethodData::verify_on(outputStream* st) {
1607   guarantee(is_methodData(), "object must be method data");
1608   // guarantee(m->is_perm(), "should be in permspace");
1609   this->verify_data_on(st);
1610 }
1611 
1612 void MethodData::verify_data_on(outputStream* st) {
1613   NEEDS_CLEANUP;
1614   // not yet implemented.
1615 }
1616 
1617 bool MethodData::profile_jsr292(const methodHandle& m, int bci) {
1618   if (m->is_compiled_lambda_form()) {
1619     return true;
1620   }
1621 
1622   Bytecode_invoke inv(m , bci);
1623   return inv.is_invokedynamic() || inv.is_invokehandle();
1624 }
1625 
1626 bool MethodData::profile_unsafe(const methodHandle& m, int bci) {
1627   Bytecode_invoke inv(m , bci);
1628   if (inv.is_invokevirtual()) {
1629     Symbol* klass = inv.klass();
1630     if (klass == vmSymbols::jdk_internal_misc_Unsafe() ||
1631         klass == vmSymbols::sun_misc_Unsafe() ||
1632         klass == vmSymbols::jdk_internal_misc_ScopedMemoryAccess()) {
1633       Symbol* name = inv.name();
1634       if (name->starts_with("get") || name->starts_with("put")) {
1635         return true;
1636       }
1637     }
1638   }
1639   return false;
1640 }
1641 
1642 int MethodData::profile_arguments_flag() {
1643   return TypeProfileLevel % 10;
1644 }
1645 
1646 bool MethodData::profile_arguments() {
1647   return profile_arguments_flag() > no_type_profile && profile_arguments_flag() <= type_profile_all && TypeProfileArgsLimit > 0;
1648 }
1649 
1650 bool MethodData::profile_arguments_jsr292_only() {
1651   return profile_arguments_flag() == type_profile_jsr292;
1652 }
1653 
1654 bool MethodData::profile_all_arguments() {
1655   return profile_arguments_flag() == type_profile_all;
1656 }
1657 
1658 bool MethodData::profile_arguments_for_invoke(const methodHandle& m, int bci) {
1659   if (!profile_arguments()) {
1660     return false;
1661   }
1662 
1663   if (profile_all_arguments()) {
1664     return true;
1665   }
1666 
1667   if (profile_unsafe(m, bci)) {
1668     return true;
1669   }
1670 
1671   assert(profile_arguments_jsr292_only(), "inconsistent");
1672   return profile_jsr292(m, bci);
1673 }
1674 
1675 int MethodData::profile_return_flag() {
1676   return (TypeProfileLevel % 100) / 10;
1677 }
1678 
1679 bool MethodData::profile_return() {
1680   return profile_return_flag() > no_type_profile && profile_return_flag() <= type_profile_all;
1681 }
1682 
1683 bool MethodData::profile_return_jsr292_only() {
1684   return profile_return_flag() == type_profile_jsr292;
1685 }
1686 
1687 bool MethodData::profile_all_return() {
1688   return profile_return_flag() == type_profile_all;
1689 }
1690 
1691 bool MethodData::profile_return_for_invoke(const methodHandle& m, int bci) {
1692   if (!profile_return()) {
1693     return false;
1694   }
1695 
1696   if (profile_all_return()) {
1697     return true;
1698   }
1699 
1700   assert(profile_return_jsr292_only(), "inconsistent");
1701   return profile_jsr292(m, bci);
1702 }
1703 
1704 int MethodData::profile_parameters_flag() {
1705   return TypeProfileLevel / 100;
1706 }
1707 
1708 bool MethodData::profile_parameters() {
1709   return profile_parameters_flag() > no_type_profile && profile_parameters_flag() <= type_profile_all;
1710 }
1711 
1712 bool MethodData::profile_parameters_jsr292_only() {
1713   return profile_parameters_flag() == type_profile_jsr292;
1714 }
1715 
1716 bool MethodData::profile_all_parameters() {
1717   return profile_parameters_flag() == type_profile_all;
1718 }
1719 
1720 bool MethodData::profile_parameters_for_method(const methodHandle& m) {
1721   if (!profile_parameters()) {
1722     return false;
1723   }
1724 
1725   if (profile_all_parameters()) {
1726     return true;
1727   }
1728 
1729   assert(profile_parameters_jsr292_only(), "inconsistent");
1730   return m->is_compiled_lambda_form();
1731 }
1732 
1733 void MethodData::metaspace_pointers_do(MetaspaceClosure* it) {
1734   log_trace(cds)("Iter(MethodData): %p", this);
1735   it->push(&_method);
1736 }
1737 
1738 void MethodData::clean_extra_data_helper(DataLayout* dp, int shift, bool reset) {
1739   check_extra_data_locked();
1740 
1741   if (shift == 0) {
1742     return;
1743   }
1744   if (!reset) {
1745     // Move all cells of trap entry at dp left by "shift" cells
1746     intptr_t* start = (intptr_t*)dp;
1747     intptr_t* end = (intptr_t*)next_extra(dp);
1748     for (intptr_t* ptr = start; ptr < end; ptr++) {
1749       *(ptr-shift) = *ptr;
1750     }
1751   } else {
1752     // Reset "shift" cells stopping at dp
1753     intptr_t* start = ((intptr_t*)dp) - shift;
1754     intptr_t* end = (intptr_t*)dp;
1755     for (intptr_t* ptr = start; ptr < end; ptr++) {
1756       *ptr = 0;
1757     }
1758   }
1759 }
1760 
1761 // Check for entries that reference an unloaded method
1762 class CleanExtraDataKlassClosure : public CleanExtraDataClosure {
1763   bool _always_clean;
1764 public:
1765   CleanExtraDataKlassClosure(bool always_clean) : _always_clean(always_clean) {}
1766   bool is_live(Method* m) {
1767     return !(_always_clean) && m->method_holder()->is_loader_alive();
1768   }
1769 };
1770 
1771 // Check for entries that reference a redefined method
1772 class CleanExtraDataMethodClosure : public CleanExtraDataClosure {
1773 public:
1774   CleanExtraDataMethodClosure() {}
1775   bool is_live(Method* m) { return !m->is_old(); }
1776 };
1777 
1778 
1779 // Remove SpeculativeTrapData entries that reference an unloaded or
1780 // redefined method
1781 void MethodData::clean_extra_data(CleanExtraDataClosure* cl) {
1782   check_extra_data_locked();
1783 
1784   DataLayout* dp  = extra_data_base();
1785   DataLayout* end = args_data_limit();
1786 
1787   int shift = 0;
1788   for (; dp < end; dp = next_extra(dp)) {
1789     switch(dp->tag()) {
1790     case DataLayout::speculative_trap_data_tag: {
1791       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1792       Method* m = data->method();
1793       assert(m != nullptr, "should have a method");
1794       if (!cl->is_live(m)) {
1795         // "shift" accumulates the number of cells for dead
1796         // SpeculativeTrapData entries that have been seen so
1797         // far. Following entries must be shifted left by that many
1798         // cells to remove the dead SpeculativeTrapData entries.
1799         shift += (int)((intptr_t*)next_extra(dp) - (intptr_t*)dp);
1800       } else {
1801         // Shift this entry left if it follows dead
1802         // SpeculativeTrapData entries
1803         clean_extra_data_helper(dp, shift);
1804       }
1805       break;
1806     }
1807     case DataLayout::bit_data_tag:
1808       // Shift this entry left if it follows dead SpeculativeTrapData
1809       // entries
1810       clean_extra_data_helper(dp, shift);
1811       continue;
1812     case DataLayout::no_tag:
1813     case DataLayout::arg_info_data_tag:
1814       // We are at end of the live trap entries. The previous "shift"
1815       // cells contain entries that are either dead or were shifted
1816       // left. They need to be reset to no_tag
1817       clean_extra_data_helper(dp, shift, true);
1818       return;
1819     default:
1820       fatal("unexpected tag %d", dp->tag());
1821     }
1822   }
1823 }
1824 
1825 // Verify there's no unloaded or redefined method referenced by a
1826 // SpeculativeTrapData entry
1827 void MethodData::verify_extra_data_clean(CleanExtraDataClosure* cl) {
1828   check_extra_data_locked();
1829 
1830 #ifdef ASSERT
1831   DataLayout* dp  = extra_data_base();
1832   DataLayout* end = args_data_limit();
1833 
1834   for (; dp < end; dp = next_extra(dp)) {
1835     switch(dp->tag()) {
1836     case DataLayout::speculative_trap_data_tag: {
1837       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1838       Method* m = data->method();
1839       assert(m != nullptr && cl->is_live(m), "Method should exist");
1840       break;
1841     }
1842     case DataLayout::bit_data_tag:
1843       continue;
1844     case DataLayout::no_tag:
1845     case DataLayout::arg_info_data_tag:
1846       return;
1847     default:
1848       fatal("unexpected tag %d", dp->tag());
1849     }
1850   }
1851 #endif
1852 }
1853 
1854 void MethodData::clean_method_data(bool always_clean) {
1855   ResourceMark rm;
1856   for (ProfileData* data = first_data();
1857        is_valid(data);
1858        data = next_data(data)) {
1859     data->clean_weak_klass_links(always_clean);
1860   }
1861   ParametersTypeData* parameters = parameters_type_data();
1862   if (parameters != nullptr) {
1863     parameters->clean_weak_klass_links(always_clean);
1864   }
1865 
1866   CleanExtraDataKlassClosure cl(always_clean);
1867 
1868   // Lock to modify extra data, and prevent Safepoint from breaking the lock
1869   MutexLocker ml(extra_data_lock(), Mutex::_no_safepoint_check_flag);
1870 
1871   clean_extra_data(&cl);
1872   verify_extra_data_clean(&cl);
1873 }
1874 
1875 // This is called during redefinition to clean all "old" redefined
1876 // methods out of MethodData for all methods.
1877 void MethodData::clean_weak_method_links() {
1878   ResourceMark rm;
1879   CleanExtraDataMethodClosure cl;
1880 
1881   // Lock to modify extra data, and prevent Safepoint from breaking the lock
1882   MutexLocker ml(extra_data_lock(), Mutex::_no_safepoint_check_flag);
1883 
1884   clean_extra_data(&cl);
1885   verify_extra_data_clean(&cl);
1886 }
1887 
1888 void MethodData::deallocate_contents(ClassLoaderData* loader_data) {
1889   release_C_heap_structures();
1890 }
1891 
1892 void MethodData::release_C_heap_structures() {
1893 #if INCLUDE_JVMCI
1894   FailedSpeculation::free_failed_speculations(get_failed_speculations_address());
1895 #endif
1896 }
1897 
1898 #ifdef ASSERT
1899 void MethodData::check_extra_data_locked() const {
1900     // Cast const away, just to be able to verify the lock
1901     // Usually we only want non-const accesses on the lock,
1902     // so this here is an exception.
1903     MethodData* self = (MethodData*)this;
1904     assert(self->extra_data_lock()->owned_by_self(), "must have lock");
1905     assert(!Thread::current()->is_Java_thread() ||
1906            JavaThread::current()->is_in_no_safepoint_scope(),
1907            "JavaThread must have NoSafepointVerifier inside lock scope");
1908 }
1909 #endif