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