1 /*
   2  * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_OOPS_METHODDATA_HPP
  26 #define SHARE_OOPS_METHODDATA_HPP
  27 
  28 #include "interpreter/bytecodes.hpp"
  29 #include "interpreter/invocationCounter.hpp"
  30 #include "oops/metadata.hpp"
  31 #include "oops/method.hpp"
  32 #include "oops/oop.hpp"
  33 #include "runtime/atomic.hpp"
  34 #include "runtime/deoptimization.hpp"
  35 #include "runtime/mutex.hpp"
  36 #include "utilities/align.hpp"
  37 #include "utilities/copy.hpp"
  38 
  39 class BytecodeStream;
  40 
  41 // The MethodData object collects counts and other profile information
  42 // during zeroth-tier (interpreter) and third-tier (C1 with full profiling)
  43 // execution.
  44 //
  45 // The profile is used later by compilation heuristics.  Some heuristics
  46 // enable use of aggressive (or "heroic") optimizations.  An aggressive
  47 // optimization often has a down-side, a corner case that it handles
  48 // poorly, but which is thought to be rare.  The profile provides
  49 // evidence of this rarity for a given method or even BCI.  It allows
  50 // the compiler to back out of the optimization at places where it
  51 // has historically been a poor choice.  Other heuristics try to use
  52 // specific information gathered about types observed at a given site.
  53 //
  54 // All data in the profile is approximate.  It is expected to be accurate
  55 // on the whole, but the system expects occasional inaccuraces, due to
  56 // counter overflow, multiprocessor races during data collection, space
  57 // limitations, missing MDO blocks, etc.  Bad or missing data will degrade
  58 // optimization quality but will not affect correctness.  Also, each MDO
  59 // can be checked for its "maturity" by calling is_mature().
  60 //
  61 // Short (<32-bit) counters are designed to overflow to a known "saturated"
  62 // state.  Also, certain recorded per-BCI events are given one-bit counters
  63 // which overflow to a saturated state which applied to all counters at
  64 // that BCI.  In other words, there is a small lattice which approximates
  65 // the ideal of an infinite-precision counter for each event at each BCI,
  66 // and the lattice quickly "bottoms out" in a state where all counters
  67 // are taken to be indefinitely large.
  68 //
  69 // The reader will find many data races in profile gathering code, starting
  70 // with invocation counter incrementation.  None of these races harm correct
  71 // execution of the compiled code.
  72 
  73 // forward decl
  74 class ProfileData;
  75 
  76 // DataLayout
  77 //
  78 // Overlay for generic profiling data.
  79 class DataLayout {
  80   friend class VMStructs;
  81   friend class JVMCIVMStructs;
  82 
  83 private:
  84   // Every data layout begins with a header.  This header
  85   // contains a tag, which is used to indicate the size/layout
  86   // of the data, 8 bits of flags, which can be used in any way,
  87   // 32 bits of trap history (none/one reason/many reasons),
  88   // and a bci, which is used to tie this piece of data to a
  89   // specific bci in the bytecodes.
  90   union {
  91     u8 _bits;
  92     struct {
  93       u1 _tag;
  94       u1 _flags;
  95       u2 _bci;
  96       u4 _traps;
  97     } _struct;
  98   } _header;
  99 
 100   // The data layout has an arbitrary number of cells, each sized
 101   // to accommodate a pointer or an integer.
 102   intptr_t _cells[1];
 103 
 104   // Some types of data layouts need a length field.
 105   static bool needs_array_len(u1 tag);
 106 
 107 public:
 108   enum {
 109     counter_increment = 1
 110   };
 111 
 112   enum {
 113     cell_size = sizeof(intptr_t)
 114   };
 115 
 116   // Tag values
 117   enum : u1 {
 118     no_tag,
 119     bit_data_tag,
 120     counter_data_tag,
 121     jump_data_tag,
 122     receiver_type_data_tag,
 123     virtual_call_data_tag,
 124     ret_data_tag,
 125     branch_data_tag,
 126     multi_branch_data_tag,
 127     arg_info_data_tag,
 128     call_type_data_tag,
 129     virtual_call_type_data_tag,
 130     parameters_type_data_tag,
 131     speculative_trap_data_tag
 132   };
 133 
 134   enum {
 135     // The trap state breaks down as [recompile:1 | reason:31].
 136     // This further breakdown is defined in deoptimization.cpp.
 137     // See Deoptimization::trap_state_reason for an assert that
 138     // trap_bits is big enough to hold reasons < Reason_RECORDED_LIMIT.
 139     //
 140     // The trap_state is collected only if ProfileTraps is true.
 141     trap_bits = 1+31,  // 31: enough to distinguish [0..Reason_RECORDED_LIMIT].
 142     trap_mask = -1,
 143     first_flag = 0
 144   };
 145 
 146   // Size computation
 147   static int header_size_in_bytes() {
 148     return header_size_in_cells() * cell_size;
 149   }
 150   static int header_size_in_cells() {
 151     return LP64_ONLY(1) NOT_LP64(2);
 152   }
 153 
 154   static int compute_size_in_bytes(int cell_count) {
 155     return header_size_in_bytes() + cell_count * cell_size;
 156   }
 157 
 158   // Initialization
 159   void initialize(u1 tag, u2 bci, int cell_count);
 160 
 161   // Accessors
 162   u1 tag() {
 163     return _header._struct._tag;
 164   }
 165 
 166   // Return 32 bits of trap state.
 167   // The state tells if traps with zero, one, or many reasons have occurred.
 168   // It also tells whether zero or many recompilations have occurred.
 169   // The associated trap histogram in the MDO itself tells whether
 170   // traps are common or not.  If a BCI shows that a trap X has
 171   // occurred, and the MDO shows N occurrences of X, we make the
 172   // simplifying assumption that all N occurrences can be blamed
 173   // on that BCI.
 174   uint trap_state() const {
 175     return _header._struct._traps;
 176   }
 177 
 178   void set_trap_state(uint new_state) {
 179     assert(ProfileTraps, "used only under +ProfileTraps");
 180     uint old_flags = _header._struct._traps;
 181     _header._struct._traps = new_state | old_flags;
 182   }
 183 
 184   u1 flags() const {
 185     return Atomic::load_acquire(&_header._struct._flags);
 186   }
 187 
 188   u2 bci() const {
 189     return _header._struct._bci;
 190   }
 191 
 192   void set_header(u8 value) {
 193     _header._bits = value;
 194   }
 195   u8 header() {
 196     return _header._bits;
 197   }
 198   void set_cell_at(int index, intptr_t value) {
 199     _cells[index] = value;
 200   }
 201   void release_set_cell_at(int index, intptr_t value);
 202   intptr_t cell_at(int index) const {
 203     return _cells[index];
 204   }
 205 
 206   bool set_flag_at(u1 flag_number) {
 207     const u1 bit = 1 << flag_number;
 208     u1 compare_value;
 209     do {
 210       compare_value = _header._struct._flags;
 211       if ((compare_value & bit) == bit) {
 212         // already set.
 213         return false;
 214       }
 215     } while (compare_value != Atomic::cmpxchg(&_header._struct._flags, compare_value, static_cast<u1>(compare_value | bit)));
 216     return true;
 217   }
 218 
 219   bool clear_flag_at(u1 flag_number) {
 220     const u1 bit = 1 << flag_number;
 221     u1 compare_value;
 222     u1 exchange_value;
 223     do {
 224       compare_value = _header._struct._flags;
 225       if ((compare_value & bit) == 0) {
 226         // already cleaed.
 227         return false;
 228       }
 229       exchange_value = compare_value & ~bit;
 230     } while (compare_value != Atomic::cmpxchg(&_header._struct._flags, compare_value, exchange_value));
 231     return true;
 232   }
 233 
 234   bool flag_at(u1 flag_number) const {
 235     return (flags() & (1 << flag_number)) != 0;
 236   }
 237 
 238   // Low-level support for code generation.
 239   static ByteSize header_offset() {
 240     return byte_offset_of(DataLayout, _header);
 241   }
 242   static ByteSize tag_offset() {
 243     return byte_offset_of(DataLayout, _header._struct._tag);
 244   }
 245   static ByteSize flags_offset() {
 246     return byte_offset_of(DataLayout, _header._struct._flags);
 247   }
 248   static ByteSize bci_offset() {
 249     return byte_offset_of(DataLayout, _header._struct._bci);
 250   }
 251   static ByteSize cell_offset(int index) {
 252     return byte_offset_of(DataLayout, _cells) + in_ByteSize(index * cell_size);
 253   }
 254   // Return a value which, when or-ed as a byte into _flags, sets the flag.
 255   static u1 flag_number_to_constant(u1 flag_number) {
 256     DataLayout temp; temp.set_header(0);
 257     temp.set_flag_at(flag_number);
 258     return temp._header._struct._flags;
 259   }
 260   // Return a value which, when or-ed as a word into _header, sets the flag.
 261   static u8 flag_mask_to_header_mask(u1 byte_constant) {
 262     DataLayout temp; temp.set_header(0);
 263     temp._header._struct._flags = byte_constant;
 264     return temp._header._bits;
 265   }
 266 
 267   ProfileData* data_in();
 268 
 269   int size_in_bytes() {
 270     int cells = cell_count();
 271     assert(cells >= 0, "invalid number of cells");
 272     return DataLayout::compute_size_in_bytes(cells);
 273   }
 274   int cell_count();
 275 
 276   // GC support
 277   void clean_weak_klass_links(bool always_clean);
 278 };
 279 
 280 
 281 // ProfileData class hierarchy
 282 class ProfileData;
 283 class   BitData;
 284 class     CounterData;
 285 class       ReceiverTypeData;
 286 class         VirtualCallData;
 287 class           VirtualCallTypeData;
 288 class       RetData;
 289 class       CallTypeData;
 290 class   JumpData;
 291 class     BranchData;
 292 class   ArrayData;
 293 class     MultiBranchData;
 294 class     ArgInfoData;
 295 class     ParametersTypeData;
 296 class   SpeculativeTrapData;
 297 
 298 // ProfileData
 299 //
 300 // A ProfileData object is created to refer to a section of profiling
 301 // data in a structured way.
 302 class ProfileData : public ResourceObj {
 303   friend class TypeEntries;
 304   friend class ReturnTypeEntry;
 305   friend class TypeStackSlotEntries;
 306 private:
 307   enum {
 308     tab_width_one = 16,
 309     tab_width_two = 36
 310   };
 311 
 312   // This is a pointer to a section of profiling data.
 313   DataLayout* _data;
 314 
 315   char* print_data_on_helper(const MethodData* md) const;
 316 
 317 protected:
 318   DataLayout* data() { return _data; }
 319   const DataLayout* data() const { return _data; }
 320 
 321   enum {
 322     cell_size = DataLayout::cell_size
 323   };
 324 
 325 public:
 326   // How many cells are in this?
 327   virtual int cell_count() const {
 328     ShouldNotReachHere();
 329     return -1;
 330   }
 331 
 332   // Return the size of this data.
 333   int size_in_bytes() {
 334     return DataLayout::compute_size_in_bytes(cell_count());
 335   }
 336 
 337 protected:
 338   // Low-level accessors for underlying data
 339   void set_intptr_at(int index, intptr_t value) {
 340     assert(0 <= index && index < cell_count(), "oob");
 341     data()->set_cell_at(index, value);
 342   }
 343   void release_set_intptr_at(int index, intptr_t value);
 344   intptr_t intptr_at(int index) const {
 345     assert(0 <= index && index < cell_count(), "oob");
 346     return data()->cell_at(index);
 347   }
 348   void set_uint_at(int index, uint value) {
 349     set_intptr_at(index, (intptr_t) value);
 350   }
 351   void release_set_uint_at(int index, uint value);
 352   uint uint_at(int index) const {
 353     return (uint)intptr_at(index);
 354   }
 355   void set_int_at(int index, int value) {
 356     set_intptr_at(index, (intptr_t) value);
 357   }
 358   void release_set_int_at(int index, int value);
 359   int int_at(int index) const {
 360     return (int)intptr_at(index);
 361   }
 362   int int_at_unchecked(int index) const {
 363     return (int)data()->cell_at(index);
 364   }
 365   void set_oop_at(int index, oop value) {
 366     set_intptr_at(index, cast_from_oop<intptr_t>(value));
 367   }
 368   oop oop_at(int index) const {
 369     return cast_to_oop(intptr_at(index));
 370   }
 371 
 372   void set_flag_at(u1 flag_number) {
 373     data()->set_flag_at(flag_number);
 374   }
 375   bool flag_at(u1 flag_number) const {
 376     return data()->flag_at(flag_number);
 377   }
 378 
 379   // two convenient imports for use by subclasses:
 380   static ByteSize cell_offset(int index) {
 381     return DataLayout::cell_offset(index);
 382   }
 383   static u1 flag_number_to_constant(u1 flag_number) {
 384     return DataLayout::flag_number_to_constant(flag_number);
 385   }
 386 
 387   ProfileData(DataLayout* data) {
 388     _data = data;
 389   }
 390 
 391 public:
 392   // Constructor for invalid ProfileData.
 393   ProfileData();
 394 
 395   u2 bci() const {
 396     return data()->bci();
 397   }
 398 
 399   address dp() {
 400     return (address)_data;
 401   }
 402 
 403   int trap_state() const {
 404     return data()->trap_state();
 405   }
 406   void set_trap_state(int new_state) {
 407     data()->set_trap_state(new_state);
 408   }
 409 
 410   // Type checking
 411   virtual bool is_BitData()         const { return false; }
 412   virtual bool is_CounterData()     const { return false; }
 413   virtual bool is_JumpData()        const { return false; }
 414   virtual bool is_ReceiverTypeData()const { return false; }
 415   virtual bool is_VirtualCallData() const { return false; }
 416   virtual bool is_RetData()         const { return false; }
 417   virtual bool is_BranchData()      const { return false; }
 418   virtual bool is_ArrayData()       const { return false; }
 419   virtual bool is_MultiBranchData() const { return false; }
 420   virtual bool is_ArgInfoData()     const { return false; }
 421   virtual bool is_CallTypeData()    const { return false; }
 422   virtual bool is_VirtualCallTypeData()const { return false; }
 423   virtual bool is_ParametersTypeData() const { return false; }
 424   virtual bool is_SpeculativeTrapData()const { return false; }
 425 
 426 
 427   BitData* as_BitData() const {
 428     assert(is_BitData(), "wrong type");
 429     return is_BitData()         ? (BitData*)        this : nullptr;
 430   }
 431   CounterData* as_CounterData() const {
 432     assert(is_CounterData(), "wrong type");
 433     return is_CounterData()     ? (CounterData*)    this : nullptr;
 434   }
 435   JumpData* as_JumpData() const {
 436     assert(is_JumpData(), "wrong type");
 437     return is_JumpData()        ? (JumpData*)       this : nullptr;
 438   }
 439   ReceiverTypeData* as_ReceiverTypeData() const {
 440     assert(is_ReceiverTypeData(), "wrong type");
 441     return is_ReceiverTypeData() ? (ReceiverTypeData*)this : nullptr;
 442   }
 443   VirtualCallData* as_VirtualCallData() const {
 444     assert(is_VirtualCallData(), "wrong type");
 445     return is_VirtualCallData() ? (VirtualCallData*)this : nullptr;
 446   }
 447   RetData* as_RetData() const {
 448     assert(is_RetData(), "wrong type");
 449     return is_RetData()         ? (RetData*)        this : nullptr;
 450   }
 451   BranchData* as_BranchData() const {
 452     assert(is_BranchData(), "wrong type");
 453     return is_BranchData()      ? (BranchData*)     this : nullptr;
 454   }
 455   ArrayData* as_ArrayData() const {
 456     assert(is_ArrayData(), "wrong type");
 457     return is_ArrayData()       ? (ArrayData*)      this : nullptr;
 458   }
 459   MultiBranchData* as_MultiBranchData() const {
 460     assert(is_MultiBranchData(), "wrong type");
 461     return is_MultiBranchData() ? (MultiBranchData*)this : nullptr;
 462   }
 463   ArgInfoData* as_ArgInfoData() const {
 464     assert(is_ArgInfoData(), "wrong type");
 465     return is_ArgInfoData() ? (ArgInfoData*)this : nullptr;
 466   }
 467   CallTypeData* as_CallTypeData() const {
 468     assert(is_CallTypeData(), "wrong type");
 469     return is_CallTypeData() ? (CallTypeData*)this : nullptr;
 470   }
 471   VirtualCallTypeData* as_VirtualCallTypeData() const {
 472     assert(is_VirtualCallTypeData(), "wrong type");
 473     return is_VirtualCallTypeData() ? (VirtualCallTypeData*)this : nullptr;
 474   }
 475   ParametersTypeData* as_ParametersTypeData() const {
 476     assert(is_ParametersTypeData(), "wrong type");
 477     return is_ParametersTypeData() ? (ParametersTypeData*)this : nullptr;
 478   }
 479   SpeculativeTrapData* as_SpeculativeTrapData() const {
 480     assert(is_SpeculativeTrapData(), "wrong type");
 481     return is_SpeculativeTrapData() ? (SpeculativeTrapData*)this : nullptr;
 482   }
 483 
 484 
 485   // Subclass specific initialization
 486   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo) {}
 487 
 488   // GC support
 489   virtual void clean_weak_klass_links(bool always_clean) {}
 490 
 491   // CI translation: ProfileData can represent both MethodDataOop data
 492   // as well as CIMethodData data. This function is provided for translating
 493   // an oop in a ProfileData to the ci equivalent. Generally speaking,
 494   // most ProfileData don't require any translation, so we provide the null
 495   // translation here, and the required translators are in the ci subclasses.
 496   virtual void translate_from(const ProfileData* data) {}
 497 
 498   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const {
 499     ShouldNotReachHere();
 500   }
 501 
 502   void print_data_on(outputStream* st, const MethodData* md) const;
 503 
 504   void print_shared(outputStream* st, const char* name, const char* extra) const;
 505   void tab(outputStream* st, bool first = false) const;
 506 };
 507 
 508 // BitData
 509 //
 510 // A BitData holds a flag or two in its header.
 511 class BitData : public ProfileData {
 512   friend class VMStructs;
 513   friend class JVMCIVMStructs;
 514 protected:
 515   enum : u1 {
 516     // null_seen:
 517     //  saw a null operand (cast/aastore/instanceof)
 518       null_seen_flag                  = DataLayout::first_flag + 0,
 519       exception_handler_entered_flag  = null_seen_flag + 1,
 520       deprecated_method_callsite_flag = exception_handler_entered_flag + 1
 521 #if INCLUDE_JVMCI
 522     // bytecode threw any exception
 523     , exception_seen_flag             = deprecated_method_callsite_flag + 1
 524 #endif
 525   };
 526   enum { bit_cell_count = 0 };  // no additional data fields needed.
 527 public:
 528   BitData(DataLayout* layout) : ProfileData(layout) {
 529   }
 530 
 531   virtual bool is_BitData() const { return true; }
 532 
 533   static int static_cell_count() {
 534     return bit_cell_count;
 535   }
 536 
 537   virtual int cell_count() const {
 538     return static_cell_count();
 539   }
 540 
 541   // Accessor
 542 
 543   // The null_seen flag bit is specially known to the interpreter.
 544   // Consulting it allows the compiler to avoid setting up null_check traps.
 545   bool null_seen()     { return flag_at(null_seen_flag); }
 546   void set_null_seen()    { set_flag_at(null_seen_flag); }
 547   bool deprecated_method_call_site() const { return flag_at(deprecated_method_callsite_flag); }
 548   bool set_deprecated_method_call_site() { return data()->set_flag_at(deprecated_method_callsite_flag); }
 549   bool clear_deprecated_method_call_site() { return data()->clear_flag_at(deprecated_method_callsite_flag); }
 550 
 551 #if INCLUDE_JVMCI
 552   // true if an exception was thrown at the specific BCI
 553   bool exception_seen() { return flag_at(exception_seen_flag); }
 554   void set_exception_seen() { set_flag_at(exception_seen_flag); }
 555 #endif
 556 
 557   // true if a ex handler block at this bci was entered
 558   bool exception_handler_entered() { return flag_at(exception_handler_entered_flag); }
 559   void set_exception_handler_entered() { set_flag_at(exception_handler_entered_flag); }
 560 
 561   // Code generation support
 562   static u1 null_seen_byte_constant() {
 563     return flag_number_to_constant(null_seen_flag);
 564   }
 565 
 566   static ByteSize bit_data_size() {
 567     return cell_offset(bit_cell_count);
 568   }
 569 
 570   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 571 };
 572 
 573 // CounterData
 574 //
 575 // A CounterData corresponds to a simple counter.
 576 class CounterData : public BitData {
 577   friend class VMStructs;
 578   friend class JVMCIVMStructs;
 579 protected:
 580   enum {
 581     count_off,
 582     counter_cell_count
 583   };
 584 public:
 585   CounterData(DataLayout* layout) : BitData(layout) {}
 586 
 587   virtual bool is_CounterData() const { return true; }
 588 
 589   static int static_cell_count() {
 590     return counter_cell_count;
 591   }
 592 
 593   virtual int cell_count() const {
 594     return static_cell_count();
 595   }
 596 
 597   // Direct accessor
 598   int count() const {
 599     intptr_t raw_data = intptr_at(count_off);
 600     if (raw_data > max_jint) {
 601       raw_data = max_jint;
 602     } else if (raw_data < min_jint) {
 603       raw_data = min_jint;
 604     }
 605     return int(raw_data);
 606   }
 607 
 608   // Code generation support
 609   static ByteSize count_offset() {
 610     return cell_offset(count_off);
 611   }
 612   static ByteSize counter_data_size() {
 613     return cell_offset(counter_cell_count);
 614   }
 615 
 616   void set_count(int count) {
 617     set_int_at(count_off, count);
 618   }
 619 
 620   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 621 };
 622 
 623 // JumpData
 624 //
 625 // A JumpData is used to access profiling information for a direct
 626 // branch.  It is a counter, used for counting the number of branches,
 627 // plus a data displacement, used for realigning the data pointer to
 628 // the corresponding target bci.
 629 class JumpData : public ProfileData {
 630   friend class VMStructs;
 631   friend class JVMCIVMStructs;
 632 protected:
 633   enum {
 634     taken_off_set,
 635     displacement_off_set,
 636     jump_cell_count
 637   };
 638 
 639   void set_displacement(int displacement) {
 640     set_int_at(displacement_off_set, displacement);
 641   }
 642 
 643 public:
 644   JumpData(DataLayout* layout) : ProfileData(layout) {
 645     assert(layout->tag() == DataLayout::jump_data_tag ||
 646       layout->tag() == DataLayout::branch_data_tag, "wrong type");
 647   }
 648 
 649   virtual bool is_JumpData() const { return true; }
 650 
 651   static int static_cell_count() {
 652     return jump_cell_count;
 653   }
 654 
 655   virtual int cell_count() const {
 656     return static_cell_count();
 657   }
 658 
 659   // Direct accessor
 660   uint taken() const {
 661     return uint_at(taken_off_set);
 662   }
 663 
 664   void set_taken(uint cnt) {
 665     set_uint_at(taken_off_set, cnt);
 666   }
 667 
 668   // Saturating counter
 669   uint inc_taken() {
 670     uint cnt = taken() + 1;
 671     // Did we wrap? Will compiler screw us??
 672     if (cnt == 0) cnt--;
 673     set_uint_at(taken_off_set, cnt);
 674     return cnt;
 675   }
 676 
 677   int displacement() const {
 678     return int_at(displacement_off_set);
 679   }
 680 
 681   // Code generation support
 682   static ByteSize taken_offset() {
 683     return cell_offset(taken_off_set);
 684   }
 685 
 686   static ByteSize displacement_offset() {
 687     return cell_offset(displacement_off_set);
 688   }
 689 
 690   // Specific initialization.
 691   void post_initialize(BytecodeStream* stream, MethodData* mdo);
 692 
 693   void print_data_on(outputStream* st, const char* extra = nullptr) const;
 694 };
 695 
 696 // Entries in a ProfileData object to record types: it can either be
 697 // none (no profile), unknown (conflicting profile data) or a klass if
 698 // a single one is seen. Whether a null reference was seen is also
 699 // recorded. No counter is associated with the type and a single type
 700 // is tracked (unlike VirtualCallData).
 701 class TypeEntries {
 702 
 703 public:
 704 
 705   // A single cell is used to record information for a type:
 706   // - the cell is initialized to 0
 707   // - when a type is discovered it is stored in the cell
 708   // - bit zero of the cell is used to record whether a null reference
 709   // was encountered or not
 710   // - bit 1 is set to record a conflict in the type information
 711 
 712   enum {
 713     null_seen = 1,
 714     type_mask = ~null_seen,
 715     type_unknown = 2,
 716     status_bits = null_seen | type_unknown,
 717     type_klass_mask = ~status_bits
 718   };
 719 
 720   // what to initialize a cell to
 721   static intptr_t type_none() {
 722     return 0;
 723   }
 724 
 725   // null seen = bit 0 set?
 726   static bool was_null_seen(intptr_t v) {
 727     return (v & null_seen) != 0;
 728   }
 729 
 730   // conflicting type information = bit 1 set?
 731   static bool is_type_unknown(intptr_t v) {
 732     return (v & type_unknown) != 0;
 733   }
 734 
 735   // not type information yet = all bits cleared, ignoring bit 0?
 736   static bool is_type_none(intptr_t v) {
 737     return (v & type_mask) == 0;
 738   }
 739 
 740   // recorded type: cell without bit 0 and 1
 741   static intptr_t klass_part(intptr_t v) {
 742     intptr_t r = v & type_klass_mask;
 743     return r;
 744   }
 745 
 746   // type recorded
 747   static Klass* valid_klass(intptr_t k) {
 748     if (!is_type_none(k) &&
 749         !is_type_unknown(k)) {
 750       Klass* res = (Klass*)klass_part(k);
 751       assert(res != nullptr, "invalid");
 752       return res;
 753     } else {
 754       return nullptr;
 755     }
 756   }
 757 
 758   static intptr_t with_status(intptr_t k, intptr_t in) {
 759     return k | (in & status_bits);
 760   }
 761 
 762   static intptr_t with_status(Klass* k, intptr_t in) {
 763     return with_status((intptr_t)k, in);
 764   }
 765 
 766   static void print_klass(outputStream* st, intptr_t k);
 767 
 768 protected:
 769   // ProfileData object these entries are part of
 770   ProfileData* _pd;
 771   // offset within the ProfileData object where the entries start
 772   const int _base_off;
 773 
 774   TypeEntries(int base_off)
 775     : _pd(nullptr), _base_off(base_off) {}
 776 
 777   void set_intptr_at(int index, intptr_t value) {
 778     _pd->set_intptr_at(index, value);
 779   }
 780 
 781   intptr_t intptr_at(int index) const {
 782     return _pd->intptr_at(index);
 783   }
 784 
 785 public:
 786   void set_profile_data(ProfileData* pd) {
 787     _pd = pd;
 788   }
 789 };
 790 
 791 // Type entries used for arguments passed at a call and parameters on
 792 // method entry. 2 cells per entry: one for the type encoded as in
 793 // TypeEntries and one initialized with the stack slot where the
 794 // profiled object is to be found so that the interpreter can locate
 795 // it quickly.
 796 class TypeStackSlotEntries : public TypeEntries {
 797 
 798 private:
 799   enum {
 800     stack_slot_entry,
 801     type_entry,
 802     per_arg_cell_count
 803   };
 804 
 805   // offset of cell for stack slot for entry i within ProfileData object
 806   int stack_slot_offset(int i) const {
 807     return _base_off + stack_slot_local_offset(i);
 808   }
 809 
 810   const int _number_of_entries;
 811 
 812   // offset of cell for type for entry i within ProfileData object
 813   int type_offset_in_cells(int i) const {
 814     return _base_off + type_local_offset(i);
 815   }
 816 
 817 public:
 818 
 819   TypeStackSlotEntries(int base_off, int nb_entries)
 820     : TypeEntries(base_off), _number_of_entries(nb_entries) {}
 821 
 822   static int compute_cell_count(Symbol* signature, bool include_receiver, int max);
 823 
 824   void post_initialize(Symbol* signature, bool has_receiver, bool include_receiver);
 825 
 826   int number_of_entries() const { return _number_of_entries; }
 827 
 828   // offset of cell for stack slot for entry i within this block of cells for a TypeStackSlotEntries
 829   static int stack_slot_local_offset(int i) {
 830     return i * per_arg_cell_count + stack_slot_entry;
 831   }
 832 
 833   // offset of cell for type for entry i within this block of cells for a TypeStackSlotEntries
 834   static int type_local_offset(int i) {
 835     return i * per_arg_cell_count + type_entry;
 836   }
 837 
 838   // stack slot for entry i
 839   uint stack_slot(int i) const {
 840     assert(i >= 0 && i < _number_of_entries, "oob");
 841     return _pd->uint_at(stack_slot_offset(i));
 842   }
 843 
 844   // set stack slot for entry i
 845   void set_stack_slot(int i, uint num) {
 846     assert(i >= 0 && i < _number_of_entries, "oob");
 847     _pd->set_uint_at(stack_slot_offset(i), num);
 848   }
 849 
 850   // type for entry i
 851   intptr_t type(int i) const {
 852     assert(i >= 0 && i < _number_of_entries, "oob");
 853     return _pd->intptr_at(type_offset_in_cells(i));
 854   }
 855 
 856   // set type for entry i
 857   void set_type(int i, intptr_t k) {
 858     assert(i >= 0 && i < _number_of_entries, "oob");
 859     _pd->set_intptr_at(type_offset_in_cells(i), k);
 860   }
 861 
 862   static ByteSize per_arg_size() {
 863     return in_ByteSize(per_arg_cell_count * DataLayout::cell_size);
 864   }
 865 
 866   static int per_arg_count() {
 867     return per_arg_cell_count;
 868   }
 869 
 870   ByteSize type_offset(int i) const {
 871     return DataLayout::cell_offset(type_offset_in_cells(i));
 872   }
 873 
 874   // GC support
 875   void clean_weak_klass_links(bool always_clean);
 876 
 877   void print_data_on(outputStream* st) const;
 878 };
 879 
 880 // Type entry used for return from a call. A single cell to record the
 881 // type.
 882 class ReturnTypeEntry : public TypeEntries {
 883 
 884 private:
 885   enum {
 886     cell_count = 1
 887   };
 888 
 889 public:
 890   ReturnTypeEntry(int base_off)
 891     : TypeEntries(base_off) {}
 892 
 893   void post_initialize() {
 894     set_type(type_none());
 895   }
 896 
 897   intptr_t type() const {
 898     return _pd->intptr_at(_base_off);
 899   }
 900 
 901   void set_type(intptr_t k) {
 902     _pd->set_intptr_at(_base_off, k);
 903   }
 904 
 905   static int static_cell_count() {
 906     return cell_count;
 907   }
 908 
 909   static ByteSize size() {
 910     return in_ByteSize(cell_count * DataLayout::cell_size);
 911   }
 912 
 913   ByteSize type_offset() {
 914     return DataLayout::cell_offset(_base_off);
 915   }
 916 
 917   // GC support
 918   void clean_weak_klass_links(bool always_clean);
 919 
 920   void print_data_on(outputStream* st) const;
 921 };
 922 
 923 // Entries to collect type information at a call: contains arguments
 924 // (TypeStackSlotEntries), a return type (ReturnTypeEntry) and a
 925 // number of cells. Because the number of cells for the return type is
 926 // smaller than the number of cells for the type of an arguments, the
 927 // number of cells is used to tell how many arguments are profiled and
 928 // whether a return value is profiled. See has_arguments() and
 929 // has_return().
 930 class TypeEntriesAtCall {
 931 private:
 932   static int stack_slot_local_offset(int i) {
 933     return header_cell_count() + TypeStackSlotEntries::stack_slot_local_offset(i);
 934   }
 935 
 936   static int argument_type_local_offset(int i) {
 937     return header_cell_count() + TypeStackSlotEntries::type_local_offset(i);
 938   }
 939 
 940 public:
 941 
 942   static int header_cell_count() {
 943     return 1;
 944   }
 945 
 946   static int cell_count_local_offset() {
 947     return 0;
 948   }
 949 
 950   static int compute_cell_count(BytecodeStream* stream);
 951 
 952   static void initialize(DataLayout* dl, int base, int cell_count) {
 953     int off = base + cell_count_local_offset();
 954     dl->set_cell_at(off, cell_count - base - header_cell_count());
 955   }
 956 
 957   static bool arguments_profiling_enabled();
 958   static bool return_profiling_enabled();
 959 
 960   // Code generation support
 961   static ByteSize cell_count_offset() {
 962     return in_ByteSize(cell_count_local_offset() * DataLayout::cell_size);
 963   }
 964 
 965   static ByteSize args_data_offset() {
 966     return in_ByteSize(header_cell_count() * DataLayout::cell_size);
 967   }
 968 
 969   static ByteSize stack_slot_offset(int i) {
 970     return in_ByteSize(stack_slot_local_offset(i) * DataLayout::cell_size);
 971   }
 972 
 973   static ByteSize argument_type_offset(int i) {
 974     return in_ByteSize(argument_type_local_offset(i) * DataLayout::cell_size);
 975   }
 976 
 977   static ByteSize return_only_size() {
 978     return ReturnTypeEntry::size() + in_ByteSize(header_cell_count() * DataLayout::cell_size);
 979   }
 980 
 981 };
 982 
 983 // CallTypeData
 984 //
 985 // A CallTypeData is used to access profiling information about a non
 986 // virtual call for which we collect type information about arguments
 987 // and return value.
 988 class CallTypeData : public CounterData {
 989 private:
 990   // entries for arguments if any
 991   TypeStackSlotEntries _args;
 992   // entry for return type if any
 993   ReturnTypeEntry _ret;
 994 
 995   int cell_count_global_offset() const {
 996     return CounterData::static_cell_count() + TypeEntriesAtCall::cell_count_local_offset();
 997   }
 998 
 999   // number of cells not counting the header
1000   int cell_count_no_header() const {
1001     return uint_at(cell_count_global_offset());
1002   }
1003 
1004   void check_number_of_arguments(int total) {
1005     assert(number_of_arguments() == total, "should be set in DataLayout::initialize");
1006   }
1007 
1008 public:
1009   CallTypeData(DataLayout* layout) :
1010     CounterData(layout),
1011     _args(CounterData::static_cell_count()+TypeEntriesAtCall::header_cell_count(), number_of_arguments()),
1012     _ret(cell_count() - ReturnTypeEntry::static_cell_count())
1013   {
1014     assert(layout->tag() == DataLayout::call_type_data_tag, "wrong type");
1015     // Some compilers (VC++) don't want this passed in member initialization list
1016     _args.set_profile_data(this);
1017     _ret.set_profile_data(this);
1018   }
1019 
1020   const TypeStackSlotEntries* args() const {
1021     assert(has_arguments(), "no profiling of arguments");
1022     return &_args;
1023   }
1024 
1025   const ReturnTypeEntry* ret() const {
1026     assert(has_return(), "no profiling of return value");
1027     return &_ret;
1028   }
1029 
1030   virtual bool is_CallTypeData() const { return true; }
1031 
1032   static int static_cell_count() {
1033     return -1;
1034   }
1035 
1036   static int compute_cell_count(BytecodeStream* stream) {
1037     return CounterData::static_cell_count() + TypeEntriesAtCall::compute_cell_count(stream);
1038   }
1039 
1040   static void initialize(DataLayout* dl, int cell_count) {
1041     TypeEntriesAtCall::initialize(dl, CounterData::static_cell_count(), cell_count);
1042   }
1043 
1044   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1045 
1046   virtual int cell_count() const {
1047     return CounterData::static_cell_count() +
1048       TypeEntriesAtCall::header_cell_count() +
1049       int_at_unchecked(cell_count_global_offset());
1050   }
1051 
1052   int number_of_arguments() const {
1053     return cell_count_no_header() / TypeStackSlotEntries::per_arg_count();
1054   }
1055 
1056   void set_argument_type(int i, Klass* k) {
1057     assert(has_arguments(), "no arguments!");
1058     intptr_t current = _args.type(i);
1059     _args.set_type(i, TypeEntries::with_status(k, current));
1060   }
1061 
1062   void set_return_type(Klass* k) {
1063     assert(has_return(), "no return!");
1064     intptr_t current = _ret.type();
1065     _ret.set_type(TypeEntries::with_status(k, current));
1066   }
1067 
1068   // An entry for a return value takes less space than an entry for an
1069   // argument so if the number of cells exceeds the number of cells
1070   // needed for an argument, this object contains type information for
1071   // at least one argument.
1072   bool has_arguments() const {
1073     bool res = cell_count_no_header() >= TypeStackSlotEntries::per_arg_count();
1074     assert (!res || TypeEntriesAtCall::arguments_profiling_enabled(), "no profiling of arguments");
1075     return res;
1076   }
1077 
1078   // An entry for a return value takes less space than an entry for an
1079   // argument, so if the remainder of the number of cells divided by
1080   // the number of cells for an argument is not null, a return value
1081   // is profiled in this object.
1082   bool has_return() const {
1083     bool res = (cell_count_no_header() % TypeStackSlotEntries::per_arg_count()) != 0;
1084     assert (!res || TypeEntriesAtCall::return_profiling_enabled(), "no profiling of return values");
1085     return res;
1086   }
1087 
1088   // Code generation support
1089   static ByteSize args_data_offset() {
1090     return cell_offset(CounterData::static_cell_count()) + TypeEntriesAtCall::args_data_offset();
1091   }
1092 
1093   ByteSize argument_type_offset(int i) {
1094     return _args.type_offset(i);
1095   }
1096 
1097   ByteSize return_type_offset() {
1098     return _ret.type_offset();
1099   }
1100 
1101   // GC support
1102   virtual void clean_weak_klass_links(bool always_clean) {
1103     if (has_arguments()) {
1104       _args.clean_weak_klass_links(always_clean);
1105     }
1106     if (has_return()) {
1107       _ret.clean_weak_klass_links(always_clean);
1108     }
1109   }
1110 
1111   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1112 };
1113 
1114 // ReceiverTypeData
1115 //
1116 // A ReceiverTypeData is used to access profiling information about a
1117 // dynamic type check.  It consists of a series of (Klass*, count)
1118 // pairs which are used to store a type profile for the receiver of
1119 // the check, the associated count is incremented every time the type
1120 // is seen. A per ReceiverTypeData counter is incremented on type
1121 // overflow (when there's no more room for a not yet profiled Klass*).
1122 //
1123 class ReceiverTypeData : public CounterData {
1124   friend class VMStructs;
1125   friend class JVMCIVMStructs;
1126 protected:
1127   enum {
1128     receiver0_offset = counter_cell_count,
1129     count0_offset,
1130     receiver_type_row_cell_count = (count0_offset + 1) - receiver0_offset
1131   };
1132 
1133 public:
1134   ReceiverTypeData(DataLayout* layout) : CounterData(layout) {
1135     assert(layout->tag() == DataLayout::receiver_type_data_tag ||
1136            layout->tag() == DataLayout::virtual_call_data_tag ||
1137            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1138   }
1139 
1140   virtual bool is_ReceiverTypeData() const { return true; }
1141 
1142   static int static_cell_count() {
1143     return counter_cell_count + (uint) TypeProfileWidth * receiver_type_row_cell_count;
1144   }
1145 
1146   virtual int cell_count() const {
1147     return static_cell_count();
1148   }
1149 
1150   // Direct accessors
1151   static uint row_limit() {
1152     return (uint) TypeProfileWidth;
1153   }
1154   static int receiver_cell_index(uint row) {
1155     return receiver0_offset + row * receiver_type_row_cell_count;
1156   }
1157   static int receiver_count_cell_index(uint row) {
1158     return count0_offset + row * receiver_type_row_cell_count;
1159   }
1160 
1161   Klass* receiver(uint row) const {
1162     assert(row < row_limit(), "oob");
1163 
1164     Klass* recv = (Klass*)intptr_at(receiver_cell_index(row));
1165     assert(recv == nullptr || recv->is_klass(), "wrong type");
1166     return recv;
1167   }
1168 
1169   void set_receiver(uint row, Klass* k) {
1170     assert((uint)row < row_limit(), "oob");
1171     set_intptr_at(receiver_cell_index(row), (uintptr_t)k);
1172   }
1173 
1174   uint receiver_count(uint row) const {
1175     assert(row < row_limit(), "oob");
1176     return uint_at(receiver_count_cell_index(row));
1177   }
1178 
1179   void set_receiver_count(uint row, uint count) {
1180     assert(row < row_limit(), "oob");
1181     set_uint_at(receiver_count_cell_index(row), count);
1182   }
1183 
1184   void clear_row(uint row) {
1185     assert(row < row_limit(), "oob");
1186     // Clear total count - indicator of polymorphic call site.
1187     // The site may look like as monomorphic after that but
1188     // it allow to have more accurate profiling information because
1189     // there was execution phase change since klasses were unloaded.
1190     // If the site is still polymorphic then MDO will be updated
1191     // to reflect it. But it could be the case that the site becomes
1192     // only bimorphic. Then keeping total count not 0 will be wrong.
1193     // Even if we use monomorphic (when it is not) for compilation
1194     // we will only have trap, deoptimization and recompile again
1195     // with updated MDO after executing method in Interpreter.
1196     // An additional receiver will be recorded in the cleaned row
1197     // during next call execution.
1198     //
1199     // Note: our profiling logic works with empty rows in any slot.
1200     // We do sorting a profiling info (ciCallProfile) for compilation.
1201     //
1202     set_count(0);
1203     set_receiver(row, nullptr);
1204     set_receiver_count(row, 0);
1205   }
1206 
1207   // Code generation support
1208   static ByteSize receiver_offset(uint row) {
1209     return cell_offset(receiver_cell_index(row));
1210   }
1211   static ByteSize receiver_count_offset(uint row) {
1212     return cell_offset(receiver_count_cell_index(row));
1213   }
1214   static ByteSize receiver_type_data_size() {
1215     return cell_offset(static_cell_count());
1216   }
1217 
1218   // GC support
1219   virtual void clean_weak_klass_links(bool always_clean);
1220 
1221   void print_receiver_data_on(outputStream* st) const;
1222   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1223 };
1224 
1225 // VirtualCallData
1226 //
1227 // A VirtualCallData is used to access profiling information about a
1228 // virtual call.  For now, it has nothing more than a ReceiverTypeData.
1229 class VirtualCallData : public ReceiverTypeData {
1230 public:
1231   VirtualCallData(DataLayout* layout) : ReceiverTypeData(layout) {
1232     assert(layout->tag() == DataLayout::virtual_call_data_tag ||
1233            layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1234   }
1235 
1236   virtual bool is_VirtualCallData() const { return true; }
1237 
1238   static int static_cell_count() {
1239     // At this point we could add more profile state, e.g., for arguments.
1240     // But for now it's the same size as the base record type.
1241     return ReceiverTypeData::static_cell_count();
1242   }
1243 
1244   virtual int cell_count() const {
1245     return static_cell_count();
1246   }
1247 
1248   // Direct accessors
1249   static ByteSize virtual_call_data_size() {
1250     return cell_offset(static_cell_count());
1251   }
1252 
1253   void print_method_data_on(outputStream* st) const NOT_JVMCI_RETURN;
1254   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1255 };
1256 
1257 // VirtualCallTypeData
1258 //
1259 // A VirtualCallTypeData is used to access profiling information about
1260 // a virtual call for which we collect type information about
1261 // arguments and return value.
1262 class VirtualCallTypeData : public VirtualCallData {
1263 private:
1264   // entries for arguments if any
1265   TypeStackSlotEntries _args;
1266   // entry for return type if any
1267   ReturnTypeEntry _ret;
1268 
1269   int cell_count_global_offset() const {
1270     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::cell_count_local_offset();
1271   }
1272 
1273   // number of cells not counting the header
1274   int cell_count_no_header() const {
1275     return uint_at(cell_count_global_offset());
1276   }
1277 
1278   void check_number_of_arguments(int total) {
1279     assert(number_of_arguments() == total, "should be set in DataLayout::initialize");
1280   }
1281 
1282 public:
1283   VirtualCallTypeData(DataLayout* layout) :
1284     VirtualCallData(layout),
1285     _args(VirtualCallData::static_cell_count()+TypeEntriesAtCall::header_cell_count(), number_of_arguments()),
1286     _ret(cell_count() - ReturnTypeEntry::static_cell_count())
1287   {
1288     assert(layout->tag() == DataLayout::virtual_call_type_data_tag, "wrong type");
1289     // Some compilers (VC++) don't want this passed in member initialization list
1290     _args.set_profile_data(this);
1291     _ret.set_profile_data(this);
1292   }
1293 
1294   const TypeStackSlotEntries* args() const {
1295     assert(has_arguments(), "no profiling of arguments");
1296     return &_args;
1297   }
1298 
1299   const ReturnTypeEntry* ret() const {
1300     assert(has_return(), "no profiling of return value");
1301     return &_ret;
1302   }
1303 
1304   virtual bool is_VirtualCallTypeData() const { return true; }
1305 
1306   static int static_cell_count() {
1307     return -1;
1308   }
1309 
1310   static int compute_cell_count(BytecodeStream* stream) {
1311     return VirtualCallData::static_cell_count() + TypeEntriesAtCall::compute_cell_count(stream);
1312   }
1313 
1314   static void initialize(DataLayout* dl, int cell_count) {
1315     TypeEntriesAtCall::initialize(dl, VirtualCallData::static_cell_count(), cell_count);
1316   }
1317 
1318   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1319 
1320   virtual int cell_count() const {
1321     return VirtualCallData::static_cell_count() +
1322       TypeEntriesAtCall::header_cell_count() +
1323       int_at_unchecked(cell_count_global_offset());
1324   }
1325 
1326   int number_of_arguments() const {
1327     return cell_count_no_header() / TypeStackSlotEntries::per_arg_count();
1328   }
1329 
1330   void set_argument_type(int i, Klass* k) {
1331     assert(has_arguments(), "no arguments!");
1332     intptr_t current = _args.type(i);
1333     _args.set_type(i, TypeEntries::with_status(k, current));
1334   }
1335 
1336   void set_return_type(Klass* k) {
1337     assert(has_return(), "no return!");
1338     intptr_t current = _ret.type();
1339     _ret.set_type(TypeEntries::with_status(k, current));
1340   }
1341 
1342   // An entry for a return value takes less space than an entry for an
1343   // argument, so if the remainder of the number of cells divided by
1344   // the number of cells for an argument is not null, a return value
1345   // is profiled in this object.
1346   bool has_return() const {
1347     bool res = (cell_count_no_header() % TypeStackSlotEntries::per_arg_count()) != 0;
1348     assert (!res || TypeEntriesAtCall::return_profiling_enabled(), "no profiling of return values");
1349     return res;
1350   }
1351 
1352   // An entry for a return value takes less space than an entry for an
1353   // argument so if the number of cells exceeds the number of cells
1354   // needed for an argument, this object contains type information for
1355   // at least one argument.
1356   bool has_arguments() const {
1357     bool res = cell_count_no_header() >= TypeStackSlotEntries::per_arg_count();
1358     assert (!res || TypeEntriesAtCall::arguments_profiling_enabled(), "no profiling of arguments");
1359     return res;
1360   }
1361 
1362   // Code generation support
1363   static ByteSize args_data_offset() {
1364     return cell_offset(VirtualCallData::static_cell_count()) + TypeEntriesAtCall::args_data_offset();
1365   }
1366 
1367   ByteSize argument_type_offset(int i) {
1368     return _args.type_offset(i);
1369   }
1370 
1371   ByteSize return_type_offset() {
1372     return _ret.type_offset();
1373   }
1374 
1375   // GC support
1376   virtual void clean_weak_klass_links(bool always_clean) {
1377     ReceiverTypeData::clean_weak_klass_links(always_clean);
1378     if (has_arguments()) {
1379       _args.clean_weak_klass_links(always_clean);
1380     }
1381     if (has_return()) {
1382       _ret.clean_weak_klass_links(always_clean);
1383     }
1384   }
1385 
1386   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1387 };
1388 
1389 // RetData
1390 //
1391 // A RetData is used to access profiling information for a ret bytecode.
1392 // It is composed of a count of the number of times that the ret has
1393 // been executed, followed by a series of triples of the form
1394 // (bci, count, di) which count the number of times that some bci was the
1395 // target of the ret and cache a corresponding data displacement.
1396 class RetData : public CounterData {
1397 protected:
1398   enum {
1399     bci0_offset = counter_cell_count,
1400     count0_offset,
1401     displacement0_offset,
1402     ret_row_cell_count = (displacement0_offset + 1) - bci0_offset
1403   };
1404 
1405   void set_bci(uint row, int bci) {
1406     assert((uint)row < row_limit(), "oob");
1407     set_int_at(bci0_offset + row * ret_row_cell_count, bci);
1408   }
1409   void release_set_bci(uint row, int bci);
1410   void set_bci_count(uint row, uint count) {
1411     assert((uint)row < row_limit(), "oob");
1412     set_uint_at(count0_offset + row * ret_row_cell_count, count);
1413   }
1414   void set_bci_displacement(uint row, int disp) {
1415     set_int_at(displacement0_offset + row * ret_row_cell_count, disp);
1416   }
1417 
1418 public:
1419   RetData(DataLayout* layout) : CounterData(layout) {
1420     assert(layout->tag() == DataLayout::ret_data_tag, "wrong type");
1421   }
1422 
1423   virtual bool is_RetData() const { return true; }
1424 
1425   enum {
1426     no_bci = -1 // value of bci when bci1/2 are not in use.
1427   };
1428 
1429   static int static_cell_count() {
1430     return counter_cell_count + (uint) BciProfileWidth * ret_row_cell_count;
1431   }
1432 
1433   virtual int cell_count() const {
1434     return static_cell_count();
1435   }
1436 
1437   static uint row_limit() {
1438     return (uint) BciProfileWidth;
1439   }
1440   static int bci_cell_index(uint row) {
1441     return bci0_offset + row * ret_row_cell_count;
1442   }
1443   static int bci_count_cell_index(uint row) {
1444     return count0_offset + row * ret_row_cell_count;
1445   }
1446   static int bci_displacement_cell_index(uint row) {
1447     return displacement0_offset + row * ret_row_cell_count;
1448   }
1449 
1450   // Direct accessors
1451   int bci(uint row) const {
1452     return int_at(bci_cell_index(row));
1453   }
1454   uint bci_count(uint row) const {
1455     return uint_at(bci_count_cell_index(row));
1456   }
1457   int bci_displacement(uint row) const {
1458     return int_at(bci_displacement_cell_index(row));
1459   }
1460 
1461   // Interpreter Runtime support
1462   address fixup_ret(int return_bci, MethodData* mdo);
1463 
1464   // Code generation support
1465   static ByteSize bci_offset(uint row) {
1466     return cell_offset(bci_cell_index(row));
1467   }
1468   static ByteSize bci_count_offset(uint row) {
1469     return cell_offset(bci_count_cell_index(row));
1470   }
1471   static ByteSize bci_displacement_offset(uint row) {
1472     return cell_offset(bci_displacement_cell_index(row));
1473   }
1474 
1475   // Specific initialization.
1476   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1477 
1478   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1479 };
1480 
1481 // BranchData
1482 //
1483 // A BranchData is used to access profiling data for a two-way branch.
1484 // It consists of taken and not_taken counts as well as a data displacement
1485 // for the taken case.
1486 class BranchData : public JumpData {
1487   friend class VMStructs;
1488   friend class JVMCIVMStructs;
1489 protected:
1490   enum {
1491     not_taken_off_set = jump_cell_count,
1492     branch_cell_count
1493   };
1494 
1495   void set_displacement(int displacement) {
1496     set_int_at(displacement_off_set, displacement);
1497   }
1498 
1499 public:
1500   BranchData(DataLayout* layout) : JumpData(layout) {
1501     assert(layout->tag() == DataLayout::branch_data_tag, "wrong type");
1502   }
1503 
1504   virtual bool is_BranchData() const { return true; }
1505 
1506   static int static_cell_count() {
1507     return branch_cell_count;
1508   }
1509 
1510   virtual int cell_count() const {
1511     return static_cell_count();
1512   }
1513 
1514   // Direct accessor
1515   uint not_taken() const {
1516     return uint_at(not_taken_off_set);
1517   }
1518 
1519   void set_not_taken(uint cnt) {
1520     set_uint_at(not_taken_off_set, cnt);
1521   }
1522 
1523   uint inc_not_taken() {
1524     uint cnt = not_taken() + 1;
1525     // Did we wrap? Will compiler screw us??
1526     if (cnt == 0) cnt--;
1527     set_uint_at(not_taken_off_set, cnt);
1528     return cnt;
1529   }
1530 
1531   // Code generation support
1532   static ByteSize not_taken_offset() {
1533     return cell_offset(not_taken_off_set);
1534   }
1535   static ByteSize branch_data_size() {
1536     return cell_offset(branch_cell_count);
1537   }
1538 
1539   // Specific initialization.
1540   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1541 
1542   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1543 };
1544 
1545 // ArrayData
1546 //
1547 // A ArrayData is a base class for accessing profiling data which does
1548 // not have a statically known size.  It consists of an array length
1549 // and an array start.
1550 class ArrayData : public ProfileData {
1551   friend class VMStructs;
1552   friend class JVMCIVMStructs;
1553 protected:
1554   friend class DataLayout;
1555 
1556   enum {
1557     array_len_off_set,
1558     array_start_off_set
1559   };
1560 
1561   uint array_uint_at(int index) const {
1562     int aindex = index + array_start_off_set;
1563     return uint_at(aindex);
1564   }
1565   int array_int_at(int index) const {
1566     int aindex = index + array_start_off_set;
1567     return int_at(aindex);
1568   }
1569   oop array_oop_at(int index) const {
1570     int aindex = index + array_start_off_set;
1571     return oop_at(aindex);
1572   }
1573   void array_set_int_at(int index, int value) {
1574     int aindex = index + array_start_off_set;
1575     set_int_at(aindex, value);
1576   }
1577 
1578   // Code generation support for subclasses.
1579   static ByteSize array_element_offset(int index) {
1580     return cell_offset(array_start_off_set + index);
1581   }
1582 
1583 public:
1584   ArrayData(DataLayout* layout) : ProfileData(layout) {}
1585 
1586   virtual bool is_ArrayData() const { return true; }
1587 
1588   static int static_cell_count() {
1589     return -1;
1590   }
1591 
1592   int array_len() const {
1593     return int_at_unchecked(array_len_off_set);
1594   }
1595 
1596   virtual int cell_count() const {
1597     return array_len() + 1;
1598   }
1599 
1600   // Code generation support
1601   static ByteSize array_len_offset() {
1602     return cell_offset(array_len_off_set);
1603   }
1604   static ByteSize array_start_offset() {
1605     return cell_offset(array_start_off_set);
1606   }
1607 };
1608 
1609 // MultiBranchData
1610 //
1611 // A MultiBranchData is used to access profiling information for
1612 // a multi-way branch (*switch bytecodes).  It consists of a series
1613 // of (count, displacement) pairs, which count the number of times each
1614 // case was taken and specify the data displacement for each branch target.
1615 class MultiBranchData : public ArrayData {
1616   friend class VMStructs;
1617   friend class JVMCIVMStructs;
1618 protected:
1619   enum {
1620     default_count_off_set,
1621     default_disaplacement_off_set,
1622     case_array_start
1623   };
1624   enum {
1625     relative_count_off_set,
1626     relative_displacement_off_set,
1627     per_case_cell_count
1628   };
1629 
1630   void set_default_displacement(int displacement) {
1631     array_set_int_at(default_disaplacement_off_set, displacement);
1632   }
1633   void set_displacement_at(int index, int displacement) {
1634     array_set_int_at(case_array_start +
1635                      index * per_case_cell_count +
1636                      relative_displacement_off_set,
1637                      displacement);
1638   }
1639 
1640 public:
1641   MultiBranchData(DataLayout* layout) : ArrayData(layout) {
1642     assert(layout->tag() == DataLayout::multi_branch_data_tag, "wrong type");
1643   }
1644 
1645   virtual bool is_MultiBranchData() const { return true; }
1646 
1647   static int compute_cell_count(BytecodeStream* stream);
1648 
1649   int number_of_cases() const {
1650     int alen = array_len() - 2; // get rid of default case here.
1651     assert(alen % per_case_cell_count == 0, "must be even");
1652     return (alen / per_case_cell_count);
1653   }
1654 
1655   uint default_count() const {
1656     return array_uint_at(default_count_off_set);
1657   }
1658   int default_displacement() const {
1659     return array_int_at(default_disaplacement_off_set);
1660   }
1661 
1662   uint count_at(int index) const {
1663     return array_uint_at(case_array_start +
1664                          index * per_case_cell_count +
1665                          relative_count_off_set);
1666   }
1667   int displacement_at(int index) const {
1668     return array_int_at(case_array_start +
1669                         index * per_case_cell_count +
1670                         relative_displacement_off_set);
1671   }
1672 
1673   // Code generation support
1674   static ByteSize default_count_offset() {
1675     return array_element_offset(default_count_off_set);
1676   }
1677   static ByteSize default_displacement_offset() {
1678     return array_element_offset(default_disaplacement_off_set);
1679   }
1680   static ByteSize case_count_offset(int index) {
1681     return case_array_offset() +
1682            (per_case_size() * index) +
1683            relative_count_offset();
1684   }
1685   static ByteSize case_array_offset() {
1686     return array_element_offset(case_array_start);
1687   }
1688   static ByteSize per_case_size() {
1689     return in_ByteSize(per_case_cell_count) * cell_size;
1690   }
1691   static ByteSize relative_count_offset() {
1692     return in_ByteSize(relative_count_off_set) * cell_size;
1693   }
1694   static ByteSize relative_displacement_offset() {
1695     return in_ByteSize(relative_displacement_off_set) * cell_size;
1696   }
1697 
1698   // Specific initialization.
1699   void post_initialize(BytecodeStream* stream, MethodData* mdo);
1700 
1701   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1702 };
1703 
1704 class ArgInfoData : public ArrayData {
1705 
1706 public:
1707   ArgInfoData(DataLayout* layout) : ArrayData(layout) {
1708     assert(layout->tag() == DataLayout::arg_info_data_tag, "wrong type");
1709   }
1710 
1711   virtual bool is_ArgInfoData() const { return true; }
1712 
1713 
1714   int number_of_args() const {
1715     return array_len();
1716   }
1717 
1718   uint arg_modified(int arg) const {
1719     return array_uint_at(arg);
1720   }
1721 
1722   void set_arg_modified(int arg, uint val) {
1723     array_set_int_at(arg, val);
1724   }
1725 
1726   void print_data_on(outputStream* st, const char* extra = nullptr) const;
1727 };
1728 
1729 // ParametersTypeData
1730 //
1731 // A ParametersTypeData is used to access profiling information about
1732 // types of parameters to a method
1733 class ParametersTypeData : public ArrayData {
1734 
1735 private:
1736   TypeStackSlotEntries _parameters;
1737 
1738   static int stack_slot_local_offset(int i) {
1739     assert_profiling_enabled();
1740     return array_start_off_set + TypeStackSlotEntries::stack_slot_local_offset(i);
1741   }
1742 
1743   static int type_local_offset(int i) {
1744     assert_profiling_enabled();
1745     return array_start_off_set + TypeStackSlotEntries::type_local_offset(i);
1746   }
1747 
1748   static bool profiling_enabled();
1749   static void assert_profiling_enabled() {
1750     assert(profiling_enabled(), "method parameters profiling should be on");
1751   }
1752 
1753 public:
1754   ParametersTypeData(DataLayout* layout) : ArrayData(layout), _parameters(1, number_of_parameters()) {
1755     assert(layout->tag() == DataLayout::parameters_type_data_tag, "wrong type");
1756     // Some compilers (VC++) don't want this passed in member initialization list
1757     _parameters.set_profile_data(this);
1758   }
1759 
1760   static int compute_cell_count(Method* m);
1761 
1762   virtual bool is_ParametersTypeData() const { return true; }
1763 
1764   virtual void post_initialize(BytecodeStream* stream, MethodData* mdo);
1765 
1766   int number_of_parameters() const {
1767     return array_len() / TypeStackSlotEntries::per_arg_count();
1768   }
1769 
1770   const TypeStackSlotEntries* parameters() const { return &_parameters; }
1771 
1772   uint stack_slot(int i) const {
1773     return _parameters.stack_slot(i);
1774   }
1775 
1776   void set_type(int i, Klass* k) {
1777     intptr_t current = _parameters.type(i);
1778     _parameters.set_type(i, TypeEntries::with_status((intptr_t)k, current));
1779   }
1780 
1781   virtual void clean_weak_klass_links(bool always_clean) {
1782     _parameters.clean_weak_klass_links(always_clean);
1783   }
1784 
1785   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1786 
1787   static ByteSize stack_slot_offset(int i) {
1788     return cell_offset(stack_slot_local_offset(i));
1789   }
1790 
1791   static ByteSize type_offset(int i) {
1792     return cell_offset(type_local_offset(i));
1793   }
1794 };
1795 
1796 // SpeculativeTrapData
1797 //
1798 // A SpeculativeTrapData is used to record traps due to type
1799 // speculation. It records the root of the compilation: that type
1800 // speculation is wrong in the context of one compilation (for
1801 // method1) doesn't mean it's wrong in the context of another one (for
1802 // method2). Type speculation could have more/different data in the
1803 // context of the compilation of method2 and it's worthwhile to try an
1804 // optimization that failed for compilation of method1 in the context
1805 // of compilation of method2.
1806 // Space for SpeculativeTrapData entries is allocated from the extra
1807 // data space in the MDO. If we run out of space, the trap data for
1808 // the ProfileData at that bci is updated.
1809 class SpeculativeTrapData : public ProfileData {
1810 protected:
1811   enum {
1812     speculative_trap_method,
1813 #ifndef _LP64
1814     // The size of the area for traps is a multiple of the header
1815     // size, 2 cells on 32 bits. Packed at the end of this area are
1816     // argument info entries (with tag
1817     // DataLayout::arg_info_data_tag). The logic in
1818     // MethodData::bci_to_extra_data() that guarantees traps don't
1819     // overflow over argument info entries assumes the size of a
1820     // SpeculativeTrapData is twice the header size. On 32 bits, a
1821     // SpeculativeTrapData must be 4 cells.
1822     padding,
1823 #endif
1824     speculative_trap_cell_count
1825   };
1826 public:
1827   SpeculativeTrapData(DataLayout* layout) : ProfileData(layout) {
1828     assert(layout->tag() == DataLayout::speculative_trap_data_tag, "wrong type");
1829   }
1830 
1831   virtual bool is_SpeculativeTrapData() const { return true; }
1832 
1833   static int static_cell_count() {
1834     return speculative_trap_cell_count;
1835   }
1836 
1837   virtual int cell_count() const {
1838     return static_cell_count();
1839   }
1840 
1841   // Direct accessor
1842   Method* method() const {
1843     return (Method*)intptr_at(speculative_trap_method);
1844   }
1845 
1846   void set_method(Method* m) {
1847     assert(!m->is_old(), "cannot add old methods");
1848     set_intptr_at(speculative_trap_method, (intptr_t)m);
1849   }
1850 
1851   static ByteSize method_offset() {
1852     return cell_offset(speculative_trap_method);
1853   }
1854 
1855   virtual void print_data_on(outputStream* st, const char* extra = nullptr) const;
1856 };
1857 
1858 // MethodData*
1859 //
1860 // A MethodData* holds information which has been collected about
1861 // a method.  Its layout looks like this:
1862 //
1863 // -----------------------------
1864 // | header                    |
1865 // | klass                     |
1866 // -----------------------------
1867 // | method                    |
1868 // | size of the MethodData* |
1869 // -----------------------------
1870 // | Data entries...           |
1871 // |   (variable size)         |
1872 // |                           |
1873 // .                           .
1874 // .                           .
1875 // .                           .
1876 // |                           |
1877 // -----------------------------
1878 //
1879 // The data entry area is a heterogeneous array of DataLayouts. Each
1880 // DataLayout in the array corresponds to a specific bytecode in the
1881 // method.  The entries in the array are sorted by the corresponding
1882 // bytecode.  Access to the data is via resource-allocated ProfileData,
1883 // which point to the underlying blocks of DataLayout structures.
1884 //
1885 // During interpretation, if profiling in enabled, the interpreter
1886 // maintains a method data pointer (mdp), which points at the entry
1887 // in the array corresponding to the current bci.  In the course of
1888 // interpretation, when a bytecode is encountered that has profile data
1889 // associated with it, the entry pointed to by mdp is updated, then the
1890 // mdp is adjusted to point to the next appropriate DataLayout.  If mdp
1891 // is null to begin with, the interpreter assumes that the current method
1892 // is not (yet) being profiled.
1893 //
1894 // In MethodData* parlance, "dp" is a "data pointer", the actual address
1895 // of a DataLayout element.  A "di" is a "data index", the offset in bytes
1896 // from the base of the data entry array.  A "displacement" is the byte offset
1897 // in certain ProfileData objects that indicate the amount the mdp must be
1898 // adjusted in the event of a change in control flow.
1899 //
1900 
1901 class CleanExtraDataClosure : public StackObj {
1902 public:
1903   virtual bool is_live(Method* m) = 0;
1904 };
1905 
1906 
1907 #if INCLUDE_JVMCI
1908 // Encapsulates an encoded speculation reason. These are linked together in
1909 // a list that is atomically appended to during deoptimization. Entries are
1910 // never removed from the list.
1911 // @see jdk.vm.ci.hotspot.HotSpotSpeculationLog.HotSpotSpeculationEncoding
1912 class FailedSpeculation: public CHeapObj<mtCompiler> {
1913  private:
1914   // The length of HotSpotSpeculationEncoding.toByteArray(). The data itself
1915   // is an array embedded at the end of this object.
1916   int   _data_len;
1917 
1918   // Next entry in a linked list.
1919   FailedSpeculation* _next;
1920 
1921   FailedSpeculation(address data, int data_len);
1922 
1923   FailedSpeculation** next_adr() { return &_next; }
1924 
1925   // Placement new operator for inlining the speculation data into
1926   // the FailedSpeculation object.
1927   void* operator new(size_t size, size_t fs_size) throw();
1928 
1929  public:
1930   char* data()         { return (char*)(((address) this) + sizeof(FailedSpeculation)); }
1931   int data_len() const { return _data_len; }
1932   FailedSpeculation* next() const { return _next; }
1933 
1934   // Atomically appends a speculation from nm to the list whose head is at (*failed_speculations_address).
1935   // Returns false if the FailedSpeculation object could not be allocated.
1936   static bool add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len);
1937 
1938   // Frees all entries in the linked list whose head is at (*failed_speculations_address).
1939   static void free_failed_speculations(FailedSpeculation** failed_speculations_address);
1940 };
1941 #endif
1942 
1943 class ciMethodData;
1944 
1945 class MethodData : public Metadata {
1946   friend class VMStructs;
1947   friend class JVMCIVMStructs;
1948   friend class ProfileData;
1949   friend class TypeEntriesAtCall;
1950   friend class ciMethodData;
1951   friend class VM_ReinitializeMDO;
1952 
1953   // If you add a new field that points to any metaspace object, you
1954   // must add this field to MethodData::metaspace_pointers_do().
1955 
1956   // Back pointer to the Method*
1957   Method* _method;
1958 
1959   // Size of this oop in bytes
1960   int _size;
1961 
1962   // Cached hint for bci_to_dp and bci_to_data
1963   int _hint_di;
1964 
1965   Mutex _extra_data_lock;
1966 
1967   MethodData(const methodHandle& method);
1968 
1969   void initialize();
1970 
1971 public:
1972   static MethodData* allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS);
1973 
1974   virtual bool is_methodData() const { return true; }
1975 
1976   // Safely reinitialize the data in the MDO.  This is intended as a testing facility as the
1977   // reinitialization is performed at a safepoint so it's isn't cheap and it doesn't ensure that all
1978   // readers will see consistent profile data.
1979   void reinitialize();
1980 
1981   // Whole-method sticky bits and flags
1982   enum {
1983     _trap_hist_limit    = Deoptimization::Reason_TRAP_HISTORY_LENGTH,
1984     _trap_hist_mask     = max_jubyte,
1985     _extra_data_count   = 4     // extra DataLayout headers, for trap history
1986   }; // Public flag values
1987 
1988   // Compiler-related counters.
1989   class CompilerCounters {
1990     friend class VMStructs;
1991     friend class JVMCIVMStructs;
1992 
1993     uint _nof_decompiles;             // count of all nmethod removals
1994     uint _nof_overflow_recompiles;    // recompile count, excluding recomp. bits
1995     uint _nof_overflow_traps;         // trap count, excluding _trap_hist
1996     union {
1997       intptr_t _align;
1998       // JVMCI separates trap history for OSR compilations from normal compilations
1999       u1 _array[JVMCI_ONLY(2 *) MethodData::_trap_hist_limit];
2000     } _trap_hist;
2001 
2002   public:
2003     CompilerCounters() : _nof_decompiles(0), _nof_overflow_recompiles(0), _nof_overflow_traps(0) {
2004 #ifndef ZERO
2005       // Some Zero platforms do not have expected alignment, and do not use
2006       // this code. static_assert would still fire and fail for them.
2007       static_assert(sizeof(_trap_hist) % HeapWordSize == 0, "align");
2008 #endif
2009       uint size_in_words = sizeof(_trap_hist) / HeapWordSize;
2010       Copy::zero_to_words((HeapWord*) &_trap_hist, size_in_words);
2011     }
2012 
2013     // Return (uint)-1 for overflow.
2014     uint trap_count(int reason) const {
2015       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2016       return (int)((_trap_hist._array[reason]+1) & _trap_hist_mask) - 1;
2017     }
2018 
2019     uint inc_trap_count(int reason) {
2020       // Count another trap, anywhere in this method.
2021       assert(reason >= 0, "must be single trap");
2022       assert((uint)reason < ARRAY_SIZE(_trap_hist._array), "oob");
2023       uint cnt1 = 1 + _trap_hist._array[reason];
2024       if ((cnt1 & _trap_hist_mask) != 0) {  // if no counter overflow...
2025         _trap_hist._array[reason] = (u1)cnt1;
2026         return cnt1;
2027       } else {
2028         return _trap_hist_mask + (++_nof_overflow_traps);
2029       }
2030     }
2031 
2032     uint overflow_trap_count() const {
2033       return _nof_overflow_traps;
2034     }
2035     uint overflow_recompile_count() const {
2036       return _nof_overflow_recompiles;
2037     }
2038     uint inc_overflow_recompile_count() {
2039       return ++_nof_overflow_recompiles;
2040     }
2041     uint decompile_count() const {
2042       return _nof_decompiles;
2043     }
2044     uint inc_decompile_count() {
2045       return ++_nof_decompiles;
2046     }
2047 
2048     // Support for code generation
2049     static ByteSize trap_history_offset() {
2050       return byte_offset_of(CompilerCounters, _trap_hist._array);
2051     }
2052   };
2053 
2054 private:
2055   CompilerCounters _compiler_counters;
2056 
2057   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2058   intx              _eflags;          // flags on escape information
2059   intx              _arg_local;       // bit set of non-escaping arguments
2060   intx              _arg_stack;       // bit set of stack-allocatable arguments
2061   intx              _arg_returned;    // bit set of returned arguments
2062 
2063   // How many invocations has this MDO seen?
2064   // These counters are used to determine the exact age of MDO.
2065   // We need those because in tiered a method can be concurrently
2066   // executed at different levels.
2067   InvocationCounter _invocation_counter;
2068   // Same for backedges.
2069   InvocationCounter _backedge_counter;
2070   // Counter values at the time profiling started.
2071   int               _invocation_counter_start;
2072   int               _backedge_counter_start;
2073   uint              _tenure_traps;
2074   int               _invoke_mask;      // per-method Tier0InvokeNotifyFreqLog
2075   int               _backedge_mask;    // per-method Tier0BackedgeNotifyFreqLog
2076 
2077   // Number of loops and blocks is computed when compiling the first
2078   // time with C1. It is used to determine if method is trivial.
2079   short             _num_loops;
2080   short             _num_blocks;
2081   // Does this method contain anything worth profiling?
2082   enum WouldProfile {unknown, no_profile, profile};
2083   WouldProfile      _would_profile;
2084 
2085 #if INCLUDE_JVMCI
2086   // Support for HotSpotMethodData.setCompiledIRSize(int)
2087   FailedSpeculation* _failed_speculations;
2088   int                _jvmci_ir_size;
2089 #endif
2090 
2091   // Size of _data array in bytes.  (Excludes header and extra_data fields.)
2092   int _data_size;
2093 
2094   // data index for the area dedicated to parameters. -1 if no
2095   // parameter profiling.
2096   enum { no_parameters = -2, parameters_uninitialized = -1 };
2097   int _parameters_type_data_di;
2098 
2099   // data index of exception handler profiling data
2100   int _exception_handler_data_di;
2101 
2102   // Beginning of the data entries
2103   // See comment in ciMethodData::load_data
2104   intptr_t _data[1];
2105 
2106   // Helper for size computation
2107   static int compute_data_size(BytecodeStream* stream);
2108   static int bytecode_cell_count(Bytecodes::Code code);
2109   static bool is_speculative_trap_bytecode(Bytecodes::Code code);
2110   enum { no_profile_data = -1, variable_cell_count = -2 };
2111 
2112   // Helper for initialization
2113   DataLayout* data_layout_at(int data_index) const {
2114     assert(data_index % sizeof(intptr_t) == 0, "unaligned");
2115     return (DataLayout*) (((address)_data) + data_index);
2116   }
2117 
2118   static int single_exception_handler_data_cell_count() {
2119     return BitData::static_cell_count();
2120   }
2121 
2122   static int single_exception_handler_data_size() {
2123     return DataLayout::compute_size_in_bytes(single_exception_handler_data_cell_count());
2124   }
2125 
2126   DataLayout* exception_handler_data_at(int exception_handler_index) const {
2127     return data_layout_at(_exception_handler_data_di + (exception_handler_index * single_exception_handler_data_size()));
2128   }
2129 
2130   int num_exception_handler_data() const {
2131     return exception_handlers_data_size() / single_exception_handler_data_size();
2132   }
2133 
2134   // Initialize an individual data segment.  Returns the size of
2135   // the segment in bytes.
2136   int initialize_data(BytecodeStream* stream, int data_index);
2137 
2138   // Helper for data_at
2139   DataLayout* limit_data_position() const {
2140     return data_layout_at(_data_size);
2141   }
2142   bool out_of_bounds(int data_index) const {
2143     return data_index >= data_size();
2144   }
2145 
2146   // Give each of the data entries a chance to perform specific
2147   // data initialization.
2148   void post_initialize(BytecodeStream* stream);
2149 
2150   // hint accessors
2151   int      hint_di() const  { return _hint_di; }
2152   void set_hint_di(int di)  {
2153     assert(!out_of_bounds(di), "hint_di out of bounds");
2154     _hint_di = di;
2155   }
2156 
2157   DataLayout* data_layout_before(int bci) {
2158     // avoid SEGV on this edge case
2159     if (data_size() == 0)
2160       return nullptr;
2161     DataLayout* layout = data_layout_at(hint_di());
2162     if (layout->bci() <= bci)
2163       return layout;
2164     return data_layout_at(first_di());
2165   }
2166 
2167   // What is the index of the first data entry?
2168   int first_di() const { return 0; }
2169 
2170   ProfileData* bci_to_extra_data_find(int bci, Method* m, DataLayout*& dp);
2171   // Find or create an extra ProfileData:
2172   ProfileData* bci_to_extra_data(int bci, Method* m, bool create_if_missing);
2173 
2174   // return the argument info cell
2175   ArgInfoData *arg_info();
2176 
2177   enum {
2178     no_type_profile = 0,
2179     type_profile_jsr292 = 1,
2180     type_profile_all = 2
2181   };
2182 
2183   static bool profile_jsr292(const methodHandle& m, int bci);
2184   static bool profile_unsafe(const methodHandle& m, int bci);
2185   static bool profile_memory_access(const methodHandle& m, int bci);
2186   static int profile_arguments_flag();
2187   static bool profile_all_arguments();
2188   static bool profile_arguments_for_invoke(const methodHandle& m, int bci);
2189   static int profile_return_flag();
2190   static bool profile_all_return();
2191   static bool profile_return_for_invoke(const methodHandle& m, int bci);
2192   static int profile_parameters_flag();
2193   static bool profile_parameters_jsr292_only();
2194   static bool profile_all_parameters();
2195 
2196   void clean_extra_data_helper(DataLayout* dp, int shift, bool reset = false);
2197   void verify_extra_data_clean(CleanExtraDataClosure* cl);
2198 
2199   DataLayout* exception_handler_bci_to_data_helper(int bci);
2200 
2201 public:
2202   void clean_extra_data(CleanExtraDataClosure* cl);
2203 
2204   static int header_size() {
2205     return sizeof(MethodData)/wordSize;
2206   }
2207 
2208   // Compute the size of a MethodData* before it is created.
2209   static int compute_allocation_size_in_bytes(const methodHandle& method);
2210   static int compute_allocation_size_in_words(const methodHandle& method);
2211   static int compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps);
2212 
2213   // Determine if a given bytecode can have profile information.
2214   static bool bytecode_has_profile(Bytecodes::Code code) {
2215     return bytecode_cell_count(code) != no_profile_data;
2216   }
2217 
2218   // reset into original state
2219   void init();
2220 
2221   // My size
2222   int size_in_bytes() const { return _size; }
2223   int size() const    { return align_metadata_size(align_up(_size, BytesPerWord)/BytesPerWord); }
2224 
2225   int invocation_count() {
2226     if (invocation_counter()->carry()) {
2227       return InvocationCounter::count_limit;
2228     }
2229     return invocation_counter()->count();
2230   }
2231   int backedge_count() {
2232     if (backedge_counter()->carry()) {
2233       return InvocationCounter::count_limit;
2234     }
2235     return backedge_counter()->count();
2236   }
2237 
2238   int invocation_count_start() {
2239     if (invocation_counter()->carry()) {
2240       return 0;
2241     }
2242     return _invocation_counter_start;
2243   }
2244 
2245   int backedge_count_start() {
2246     if (backedge_counter()->carry()) {
2247       return 0;
2248     }
2249     return _backedge_counter_start;
2250   }
2251 
2252   int invocation_count_delta() { return invocation_count() - invocation_count_start(); }
2253   int backedge_count_delta()   { return backedge_count()   - backedge_count_start();   }
2254 
2255   void reset_start_counters() {
2256     _invocation_counter_start = invocation_count();
2257     _backedge_counter_start = backedge_count();
2258   }
2259 
2260   InvocationCounter* invocation_counter()     { return &_invocation_counter; }
2261   InvocationCounter* backedge_counter()       { return &_backedge_counter;   }
2262 
2263 #if INCLUDE_JVMCI
2264   FailedSpeculation** get_failed_speculations_address() {
2265     return &_failed_speculations;
2266   }
2267 #endif
2268 
2269   void set_would_profile(bool p)              { _would_profile = p ? profile : no_profile; }
2270   bool would_profile() const                  { return _would_profile != no_profile; }
2271 
2272   int num_loops() const                       { return _num_loops;  }
2273   void set_num_loops(short n)                 { _num_loops = n;     }
2274   int num_blocks() const                      { return _num_blocks; }
2275   void set_num_blocks(short n)                { _num_blocks = n;    }
2276 
2277   bool is_mature() const;
2278 
2279   // Support for interprocedural escape analysis, from Thomas Kotzmann.
2280   enum EscapeFlag {
2281     estimated    = 1 << 0,
2282     return_local = 1 << 1,
2283     return_allocated = 1 << 2,
2284     allocated_escapes = 1 << 3,
2285     unknown_modified = 1 << 4
2286   };
2287 
2288   intx eflags()                                  { return _eflags; }
2289   intx arg_local()                               { return _arg_local; }
2290   intx arg_stack()                               { return _arg_stack; }
2291   intx arg_returned()                            { return _arg_returned; }
2292   uint arg_modified(int a);
2293   void set_eflags(intx v)                        { _eflags = v; }
2294   void set_arg_local(intx v)                     { _arg_local = v; }
2295   void set_arg_stack(intx v)                     { _arg_stack = v; }
2296   void set_arg_returned(intx v)                  { _arg_returned = v; }
2297   void set_arg_modified(int a, uint v);
2298   void clear_escape_info()                       { _eflags = _arg_local = _arg_stack = _arg_returned = 0; }
2299 
2300   // Location and size of data area
2301   address data_base() const {
2302     return (address) _data;
2303   }
2304   int data_size() const {
2305     return _data_size;
2306   }
2307 
2308   int parameters_size_in_bytes() const {
2309     return pointer_delta_as_int((address) parameters_data_limit(), (address) parameters_data_base());
2310   }
2311 
2312   int exception_handlers_data_size() const {
2313     return pointer_delta_as_int((address) exception_handler_data_limit(), (address) exception_handler_data_base());
2314   }
2315 
2316   // Accessors
2317   Method* method() const { return _method; }
2318 
2319   // Get the data at an arbitrary (sort of) data index.
2320   ProfileData* data_at(int data_index) const;
2321 
2322   // Walk through the data in order.
2323   ProfileData* first_data() const { return data_at(first_di()); }
2324   ProfileData* next_data(ProfileData* current) const;
2325   DataLayout*  next_data_layout(DataLayout* current) const;
2326   bool is_valid(ProfileData* current) const { return current != nullptr; }
2327   bool is_valid(DataLayout*  current) const { return current != nullptr; }
2328 
2329   // Convert a dp (data pointer) to a di (data index).
2330   int dp_to_di(address dp) const {
2331     return (int)(dp - ((address)_data));
2332   }
2333 
2334   // bci to di/dp conversion.
2335   address bci_to_dp(int bci);
2336   int bci_to_di(int bci) {
2337     return dp_to_di(bci_to_dp(bci));
2338   }
2339 
2340   // Get the data at an arbitrary bci, or null if there is none.
2341   ProfileData* bci_to_data(int bci);
2342 
2343   // Same, but try to create an extra_data record if one is needed:
2344   ProfileData* allocate_bci_to_data(int bci, Method* m) {
2345     check_extra_data_locked();
2346 
2347     ProfileData* data = nullptr;
2348     // If m not null, try to allocate a SpeculativeTrapData entry
2349     if (m == nullptr) {
2350       data = bci_to_data(bci);
2351     }
2352     if (data != nullptr) {
2353       return data;
2354     }
2355     data = bci_to_extra_data(bci, m, true);
2356     if (data != nullptr) {
2357       return data;
2358     }
2359     // If SpeculativeTrapData allocation fails try to allocate a
2360     // regular entry
2361     data = bci_to_data(bci);
2362     if (data != nullptr) {
2363       return data;
2364     }
2365     return bci_to_extra_data(bci, nullptr, true);
2366   }
2367 
2368   BitData* exception_handler_bci_to_data_or_null(int bci);
2369   BitData exception_handler_bci_to_data(int bci);
2370 
2371   // Add a handful of extra data records, for trap tracking.
2372   // Only valid after 'set_size' is called at the end of MethodData::initialize
2373   DataLayout* extra_data_base() const  {
2374     check_extra_data_locked();
2375     return limit_data_position();
2376   }
2377   DataLayout* extra_data_limit() const { return (DataLayout*)((address)this + size_in_bytes()); }
2378   // pointers to sections in extra data
2379   DataLayout* args_data_limit() const  { return parameters_data_base(); }
2380   DataLayout* parameters_data_base() const {
2381     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2382     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di) : parameters_data_limit();
2383   }
2384   DataLayout* parameters_data_limit() const {
2385     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2386     return exception_handler_data_base();
2387   }
2388   DataLayout* exception_handler_data_base() const { return data_layout_at(_exception_handler_data_di); }
2389   DataLayout* exception_handler_data_limit() const { return extra_data_limit(); }
2390 
2391   int extra_data_size() const          { return (int)((address)extra_data_limit() - (address)limit_data_position()); }
2392   static DataLayout* next_extra(DataLayout* dp);
2393 
2394   // Return (uint)-1 for overflow.
2395   uint trap_count(int reason) const {
2396     return _compiler_counters.trap_count(reason);
2397   }
2398   // For loops:
2399   static uint trap_reason_limit() { return _trap_hist_limit; }
2400   static uint trap_count_limit()  { return _trap_hist_mask; }
2401   uint inc_trap_count(int reason) {
2402     return _compiler_counters.inc_trap_count(reason);
2403   }
2404 
2405   uint overflow_trap_count() const {
2406     return _compiler_counters.overflow_trap_count();
2407   }
2408   uint overflow_recompile_count() const {
2409     return _compiler_counters.overflow_recompile_count();
2410   }
2411   uint inc_overflow_recompile_count() {
2412     return _compiler_counters.inc_overflow_recompile_count();
2413   }
2414   uint decompile_count() const {
2415     return _compiler_counters.decompile_count();
2416   }
2417   uint inc_decompile_count() {
2418     uint dec_count = _compiler_counters.inc_decompile_count();
2419     if (dec_count > (uint)PerMethodRecompilationCutoff) {
2420       method()->set_not_compilable("decompile_count > PerMethodRecompilationCutoff", CompLevel_full_optimization);
2421     }
2422     return dec_count;
2423   }
2424   uint tenure_traps() const {
2425     return _tenure_traps;
2426   }
2427   void inc_tenure_traps() {
2428     _tenure_traps += 1;
2429   }
2430 
2431   // Return pointer to area dedicated to parameters in MDO
2432   ParametersTypeData* parameters_type_data() const {
2433     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2434     return _parameters_type_data_di != no_parameters ? data_layout_at(_parameters_type_data_di)->data_in()->as_ParametersTypeData() : nullptr;
2435   }
2436 
2437   int parameters_type_data_di() const {
2438     assert(_parameters_type_data_di != parameters_uninitialized, "called too early");
2439     return _parameters_type_data_di != no_parameters ? _parameters_type_data_di : exception_handlers_data_di();
2440   }
2441 
2442   int exception_handlers_data_di() const {
2443     return _exception_handler_data_di;
2444   }
2445 
2446   // Support for code generation
2447   static ByteSize data_offset() {
2448     return byte_offset_of(MethodData, _data[0]);
2449   }
2450 
2451   static ByteSize trap_history_offset() {
2452     return byte_offset_of(MethodData, _compiler_counters) + CompilerCounters::trap_history_offset();
2453   }
2454 
2455   static ByteSize invocation_counter_offset() {
2456     return byte_offset_of(MethodData, _invocation_counter);
2457   }
2458 
2459   static ByteSize backedge_counter_offset() {
2460     return byte_offset_of(MethodData, _backedge_counter);
2461   }
2462 
2463   static ByteSize invoke_mask_offset() {
2464     return byte_offset_of(MethodData, _invoke_mask);
2465   }
2466 
2467   static ByteSize backedge_mask_offset() {
2468     return byte_offset_of(MethodData, _backedge_mask);
2469   }
2470 
2471   static ByteSize parameters_type_data_di_offset() {
2472     return byte_offset_of(MethodData, _parameters_type_data_di);
2473   }
2474 
2475   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
2476   virtual MetaspaceObj::Type type() const { return MethodDataType; }
2477 
2478   // Deallocation support
2479   void deallocate_contents(ClassLoaderData* loader_data);
2480   void release_C_heap_structures();
2481 
2482   // GC support
2483   void set_size(int object_size_in_bytes) { _size = object_size_in_bytes; }
2484 
2485   // Printing
2486   void print_on      (outputStream* st) const;
2487   void print_value_on(outputStream* st) const;
2488 
2489   // printing support for method data
2490   void print_data_on(outputStream* st) const;
2491 
2492   const char* internal_name() const { return "{method data}"; }
2493 
2494   // verification
2495   void verify_on(outputStream* st);
2496   void verify_data_on(outputStream* st);
2497 
2498   static bool profile_parameters_for_method(const methodHandle& m);
2499   static bool profile_arguments();
2500   static bool profile_arguments_jsr292_only();
2501   static bool profile_return();
2502   static bool profile_parameters();
2503   static bool profile_return_jsr292_only();
2504 
2505   void clean_method_data(bool always_clean);
2506   void clean_weak_method_links();
2507   Mutex* extra_data_lock() const { return const_cast<Mutex*>(&_extra_data_lock); }
2508   void check_extra_data_locked() const NOT_DEBUG_RETURN;
2509 };
2510 
2511 #endif // SHARE_OOPS_METHODDATA_HPP