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