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