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