1 /*
   2  * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018, 2019 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "code/codeHeapState.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "runtime/sweeper.hpp"
  30 
  31 // -------------------------
  32 // |  General Description  |
  33 // -------------------------
  34 // The CodeHeap state analytics are divided in two parts.
  35 // The first part examines the entire CodeHeap and aggregates all
  36 // information that is believed useful/important.
  37 //
  38 // Aggregation condenses the information of a piece of the CodeHeap
  39 // (4096 bytes by default) into an analysis granule. These granules
  40 // contain enough detail to gain initial insight while keeping the
  41 // internal structure sizes in check.
  42 //
  43 // The second part, which consists of several, independent steps,
  44 // prints the previously collected information with emphasis on
  45 // various aspects.
  46 //
  47 // The CodeHeap is a living thing. Therefore, protection against concurrent
  48 // modification (by acquiring the CodeCache_lock) is necessary. It has
  49 // to be provided by the caller of the analysis functions.
  50 // If the CodeCache_lock is not held, the analysis functions may print
  51 // less detailed information or may just do nothing. It is by intention
  52 // that an unprotected invocation is not abnormally terminated.
  53 //
  54 // Data collection and printing is done on an "on request" basis.
  55 // While no request is being processed, there is no impact on performance.
  56 // The CodeHeap state analytics do have some memory footprint.
  57 // The "aggregate" step allocates some data structures to hold the aggregated
  58 // information for later output. These data structures live until they are
  59 // explicitly discarded (function "discard") or until the VM terminates.
  60 // There is one exception: the function "all" does not leave any data
  61 // structures allocated.
  62 //
  63 // Requests for real-time, on-the-fly analysis can be issued via
  64 //   jcmd <pid> Compiler.CodeHeap_Analytics [<function>] [<granularity>]
  65 //
  66 // If you are (only) interested in how the CodeHeap looks like after running
  67 // a sample workload, you can use the command line option
  68 //   -XX:+PrintCodeHeapAnalytics
  69 // It will cause a full analysis to be written to tty. In addition, a full
  70 // analysis will be written the first time a "CodeCache full" condition is
  71 // detected.
  72 //
  73 // The command line option produces output identical to the jcmd function
  74 //   jcmd <pid> Compiler.CodeHeap_Analytics all 4096
  75 // ---------------------------------------------------------------------------------
  76 
  77 // With this declaration macro, it is possible to switch between
  78 //  - direct output into an argument-passed outputStream and
  79 //  - buffered output into a bufferedStream with subsequent flush
  80 //    of the filled buffer to the outputStream.
  81 #define USE_BUFFEREDSTREAM
  82 
  83 // There are instances when composing an output line or a small set of
  84 // output lines out of many tty->print() calls creates significant overhead.
  85 // Writing to a bufferedStream buffer first has a significant advantage:
  86 // It uses noticeably less cpu cycles and reduces (when writing to a
  87 // network file) the required bandwidth by at least a factor of ten. Observed on MacOS.
  88 // That clearly makes up for the increased code complexity.
  89 //
  90 // Conversion of existing code is easy and straightforward, if the code already
  91 // uses a parameterized output destination, e.g. "outputStream st".
  92 //  - rename the formal parameter to any other name, e.g. out_st.
  93 //  - at a suitable place in your code, insert
  94 //      BUFFEREDSTEAM_DECL(buf_st, out_st)
  95 // This will provide all the declarations necessary. After that, all
  96 // buf_st->print() (and the like) calls will be directed to a bufferedStream object.
  97 // Once a block of output (a line or a small set of lines) is composed, insert
  98 //      BUFFEREDSTREAM_FLUSH(termstring)
  99 // to flush the bufferedStream to the final destination out_st. termstring is just
 100 // an arbitrary string (e.g. "\n") which is appended to the bufferedStream before
 101 // being written to out_st. Be aware that the last character written MUST be a '\n'.
 102 // Otherwise, buf_st->position() does not correspond to out_st->position() any longer.
 103 //      BUFFEREDSTREAM_FLUSH_LOCKED(termstring)
 104 // does the same thing, protected by the ttyLocker lock.
 105 //      BUFFEREDSTREAM_FLUSH_IF(termstring, remSize)
 106 // does a flush only if the remaining buffer space is less than remSize.
 107 //
 108 // To activate, #define USE_BUFFERED_STREAM before including this header.
 109 // If not activated, output will directly go to the originally used outputStream
 110 // with no additional overhead.
 111 //
 112 #if defined(USE_BUFFEREDSTREAM)
 113 // All necessary declarations to print via a bufferedStream
 114 // This macro must be placed before any other BUFFEREDSTREAM*
 115 // macro in the function.
 116 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 117     ResourceMark         _rm;                                 \
 118     /* _anyst  name of the stream as used in the code */      \
 119     /* _outst  stream where final output will go to   */      \
 120     /* _capa   allocated capacity of stream buffer    */      \
 121     size_t           _nflush = 0;                             \
 122     size_t     _nforcedflush = 0;                             \
 123     size_t      _nsavedflush = 0;                             \
 124     size_t     _nlockedflush = 0;                             \
 125     size_t     _nflush_bytes = 0;                             \
 126     size_t         _capacity = _capa;                         \
 127     bufferedStream   _sstobj = bufferedStream(_capa);         \
 128     bufferedStream*  _sstbuf = &_sstobj;                      \
 129     outputStream*    _outbuf = _outst;                        \
 130     bufferedStream*   _anyst = &_sstobj; /* any stream. Use this to just print - no buffer flush.  */
 131 
 132 // Same as above, but with fixed buffer size.
 133 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 134     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K);
 135 
 136 // Flush the buffer contents unconditionally.
 137 // No action if the buffer is empty.
 138 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 139     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 140       _sstbuf->print("%s", _termString);                      \
 141     }                                                         \
 142     if (_sstbuf != _outbuf) {                                 \
 143       if (_sstbuf->size() != 0) {                             \
 144         _nforcedflush++; _nflush_bytes += _sstbuf->size();    \
 145         _outbuf->print("%s", _sstbuf->as_string());           \
 146         _sstbuf->reset();                                     \
 147       }                                                       \
 148     }
 149 
 150 // Flush the buffer contents if the remaining capacity is
 151 // less than the given threshold.
 152 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 153     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 154       _sstbuf->print("%s", _termString);                      \
 155     }                                                         \
 156     if (_sstbuf != _outbuf) {                                 \
 157       if ((_capacity - _sstbuf->size()) < (size_t)(_remSize)){\
 158         _nflush++; _nforcedflush--;                           \
 159         BUFFEREDSTREAM_FLUSH("")                              \
 160       } else {                                                \
 161         _nsavedflush++;                                       \
 162       }                                                       \
 163     }
 164 
 165 // Flush the buffer contents if the remaining capacity is less
 166 // than the calculated threshold (256 bytes + capacity/16)
 167 // That should suffice for all reasonably sized output lines.
 168 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 169     BUFFEREDSTREAM_FLUSH_IF(_termString, 256+(_capacity>>4))
 170 
 171 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 172     { ttyLocker ttyl;/* keep this output block together */    \
 173       _nlockedflush++;                                        \
 174       BUFFEREDSTREAM_FLUSH(_termString)                       \
 175     }
 176 
 177 // #define BUFFEREDSTREAM_FLUSH_STAT()                           \
 178 //     if (_sstbuf != _outbuf) {                                 \
 179 //       _outbuf->print_cr("%ld flushes (buffer full), %ld forced, %ld locked, %ld bytes total, %ld flushes saved", _nflush, _nforcedflush, _nlockedflush, _nflush_bytes, _nsavedflush); \
 180 //    }
 181 
 182 #define BUFFEREDSTREAM_FLUSH_STAT()
 183 #else
 184 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 185     size_t       _capacity = _capa;                           \
 186     outputStream*  _outbuf = _outst;                          \
 187     outputStream*  _anyst  = _outst;   /* any stream. Use this to just print - no buffer flush.  */
 188 
 189 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 190     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K)
 191 
 192 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 193     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 194       _outbuf->print("%s", _termString);                      \
 195     }
 196 
 197 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 198     BUFFEREDSTREAM_FLUSH(_termString)
 199 
 200 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 201     BUFFEREDSTREAM_FLUSH(_termString)
 202 
 203 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 204     BUFFEREDSTREAM_FLUSH(_termString)
 205 
 206 #define BUFFEREDSTREAM_FLUSH_STAT()
 207 #endif
 208 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
 209 
 210 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 211 const char* blobTypeName[] = {"noType"
 212                              ,     "nMethod (under construction)"
 213                              ,          "nMethod (active)"
 214                              ,               "nMethod (inactive)"
 215                              ,                    "nMethod (deopt)"
 216                              ,                         "nMethod (zombie)"
 217                              ,                              "nMethod (unloaded)"
 218                              ,                                   "runtime stub"
 219                              ,                                        "ricochet stub"
 220                              ,                                             "deopt stub"
 221                              ,                                                  "uncommon trap stub"
 222                              ,                                                       "exception stub"
 223                              ,                                                            "safepoint stub"
 224                              ,                                                                 "adapter blob"
 225                              ,                                                                      "MH adapter blob"
 226                              ,                                                                           "buffer blob"
 227                              ,                                                                                "lastType"
 228                              };
 229 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 230 
 231 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 232 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 233 const  unsigned int        maxTopSizeBlocks  = 50;
 234 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 235 const  unsigned int        maxHeaps          = 10;
 236 static unsigned int        nHeaps            = 0;
 237 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 238 
 239 // static struct StatElement *StatArray      = NULL;
 240 static StatElement* StatArray             = NULL;
 241 static int          log2_seg_size         = 0;
 242 static size_t       seg_size              = 0;
 243 static size_t       alloc_granules        = 0;
 244 static size_t       granule_size          = 0;
 245 static bool         segment_granules      = false;
 246 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 247 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 248 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 249 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.
 250 static unsigned int nBlocks_inconstr      = 0;  // counting "inconstruction" nmethods only. This is a transient state.
 251 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 252 static unsigned int nBlocks_stub          = 0;
 253 
 254 static struct FreeBlk*          FreeArray = NULL;
 255 static unsigned int      alloc_freeBlocks = 0;
 256 
 257 static struct TopSizeBlk*    TopSizeArray = NULL;
 258 static unsigned int   alloc_topSizeBlocks = 0;
 259 static unsigned int    used_topSizeBlocks = 0;
 260 
 261 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 262 
 263 // nMethod temperature (hotness) indicators.
 264 static int                     avgTemp    = 0;
 265 static int                     maxTemp    = 0;
 266 static int                     minTemp    = 0;
 267 
 268 static unsigned int  latest_compilation_id   = 0;
 269 static volatile bool initialization_complete = false;
 270 
 271 const char* CodeHeapState::get_heapName(CodeHeap* heap) {
 272   if (SegmentedCodeCache) {
 273     return heap->name();
 274   } else {
 275     return "CodeHeap";
 276   }
 277 }
 278 
 279 // returns the index for the heap being processed.
 280 unsigned int CodeHeapState::findHeapIndex(outputStream* out, const char* heapName) {
 281   if (heapName == NULL) {
 282     return maxHeaps;
 283   }
 284   if (SegmentedCodeCache) {
 285     // Search for a pre-existing entry. If found, return that index.
 286     for (unsigned int i = 0; i < nHeaps; i++) {
 287       if (CodeHeapStatArray[i].heapName != NULL && strcmp(heapName, CodeHeapStatArray[i].heapName) == 0) {
 288         return i;
 289       }
 290     }
 291 
 292     // check if there are more code heap segments than we can handle.
 293     if (nHeaps == maxHeaps) {
 294       out->print_cr("Too many heap segments for current limit(%d).", maxHeaps);
 295       return maxHeaps;
 296     }
 297 
 298     // allocate new slot in StatArray.
 299     CodeHeapStatArray[nHeaps].heapName = heapName;
 300     return nHeaps++;
 301   } else {
 302     nHeaps = 1;
 303     CodeHeapStatArray[0].heapName = heapName;
 304     return 0; // This is the default index if CodeCache is not segmented.
 305   }
 306 }
 307 
 308 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 309   unsigned int ix = findHeapIndex(out, heapName);
 310   if (ix < maxHeaps) {
 311     StatArray             = CodeHeapStatArray[ix].StatArray;
 312     seg_size              = CodeHeapStatArray[ix].segment_size;
 313     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 314     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 315     granule_size          = CodeHeapStatArray[ix].granule_size;
 316     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 317     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 318     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 319     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 320     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;
 321     nBlocks_inconstr      = CodeHeapStatArray[ix].nBlocks_inconstr;
 322     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 323     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 324     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 325     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 326     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 327     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 328     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 329     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 330     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 331     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 332     minTemp               = CodeHeapStatArray[ix].minTemp;
 333   } else {
 334     StatArray             = NULL;
 335     seg_size              = 0;
 336     log2_seg_size         = 0;
 337     alloc_granules        = 0;
 338     granule_size          = 0;
 339     segment_granules      = false;
 340     nBlocks_t1            = 0;
 341     nBlocks_t2            = 0;
 342     nBlocks_alive         = 0;
 343     nBlocks_dead          = 0;
 344     nBlocks_inconstr      = 0;
 345     nBlocks_unloaded      = 0;
 346     nBlocks_stub          = 0;
 347     FreeArray             = NULL;
 348     alloc_freeBlocks      = 0;
 349     TopSizeArray          = NULL;
 350     alloc_topSizeBlocks   = 0;
 351     used_topSizeBlocks    = 0;
 352     SizeDistributionArray = NULL;
 353     avgTemp               = 0;
 354     maxTemp               = 0;
 355     minTemp               = 0;
 356   }
 357 }
 358 
 359 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 360   unsigned int ix = findHeapIndex(out, heapName);
 361   if (ix < maxHeaps) {
 362     CodeHeapStatArray[ix].StatArray             = StatArray;
 363     CodeHeapStatArray[ix].segment_size          = seg_size;
 364     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 365     CodeHeapStatArray[ix].granule_size          = granule_size;
 366     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 367     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 368     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 369     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 370     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;
 371     CodeHeapStatArray[ix].nBlocks_inconstr      = nBlocks_inconstr;
 372     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 373     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 374     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 375     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 376     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 377     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 378     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 379     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 380     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 381     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 382     CodeHeapStatArray[ix].minTemp               = minTemp;
 383   }
 384 }
 385 
 386 //---<  get a new statistics array  >---
 387 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 388   if (StatArray == NULL) {
 389     StatArray      = new StatElement[nElem];
 390     //---<  reset some counts  >---
 391     alloc_granules = nElem;
 392     granule_size   = granularity;
 393   }
 394 
 395   if (StatArray == NULL) {
 396     //---<  just do nothing if allocation failed  >---
 397     out->print_cr("Statistics could not be collected for %s, probably out of memory.", heapName);
 398     out->print_cr("Current granularity is " SIZE_FORMAT " bytes. Try a coarser granularity.", granularity);
 399     alloc_granules = 0;
 400     granule_size   = 0;
 401   } else {
 402     //---<  initialize statistics array  >---
 403     memset((void*)StatArray, 0, nElem*sizeof(StatElement));
 404   }
 405 }
 406 
 407 //---<  get a new free block array  >---
 408 void CodeHeapState::prepare_FreeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 409   if (FreeArray == NULL) {
 410     FreeArray      = new FreeBlk[nElem];
 411     //---<  reset some counts  >---
 412     alloc_freeBlocks = nElem;
 413   }
 414 
 415   if (FreeArray == NULL) {
 416     //---<  just do nothing if allocation failed  >---
 417     out->print_cr("Free space analysis cannot be done for %s, probably out of memory.", heapName);
 418     alloc_freeBlocks = 0;
 419   } else {
 420     //---<  initialize free block array  >---
 421     memset((void*)FreeArray, 0, alloc_freeBlocks*sizeof(FreeBlk));
 422   }
 423 }
 424 
 425 //---<  get a new TopSizeArray  >---
 426 void CodeHeapState::prepare_TopSizeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 427   if (TopSizeArray == NULL) {
 428     TopSizeArray   = new TopSizeBlk[nElem];
 429     //---<  reset some counts  >---
 430     alloc_topSizeBlocks = nElem;
 431     used_topSizeBlocks  = 0;
 432   }
 433 
 434   if (TopSizeArray == NULL) {
 435     //---<  just do nothing if allocation failed  >---
 436     out->print_cr("Top-%d list of largest CodeHeap blocks can not be collected for %s, probably out of memory.", nElem, heapName);
 437     alloc_topSizeBlocks = 0;
 438   } else {
 439     //---<  initialize TopSizeArray  >---
 440     memset((void*)TopSizeArray, 0, nElem*sizeof(TopSizeBlk));
 441     used_topSizeBlocks  = 0;
 442   }
 443 }
 444 
 445 //---<  get a new SizeDistributionArray  >---
 446 void CodeHeapState::prepare_SizeDistArray(outputStream* out, unsigned int nElem, const char* heapName) {
 447   if (SizeDistributionArray == NULL) {
 448     SizeDistributionArray = new SizeDistributionElement[nElem];
 449   }
 450 
 451   if (SizeDistributionArray == NULL) {
 452     //---<  just do nothing if allocation failed  >---
 453     out->print_cr("Size distribution can not be collected for %s, probably out of memory.", heapName);
 454   } else {
 455     //---<  initialize SizeDistArray  >---
 456     memset((void*)SizeDistributionArray, 0, nElem*sizeof(SizeDistributionElement));
 457     // Logarithmic range growth. First range starts at _segment_size.
 458     SizeDistributionArray[log2_seg_size-1].rangeEnd = 1U;
 459     for (unsigned int i = log2_seg_size; i < nElem; i++) {
 460       SizeDistributionArray[i].rangeStart = 1U << (i     - log2_seg_size);
 461       SizeDistributionArray[i].rangeEnd   = 1U << ((i+1) - log2_seg_size);
 462     }
 463   }
 464 }
 465 
 466 //---<  get a new SizeDistributionArray  >---
 467 void CodeHeapState::update_SizeDistArray(outputStream* out, unsigned int len) {
 468   if (SizeDistributionArray != NULL) {
 469     for (unsigned int i = log2_seg_size-1; i < nSizeDistElements; i++) {
 470       if ((SizeDistributionArray[i].rangeStart <= len) && (len < SizeDistributionArray[i].rangeEnd)) {
 471         SizeDistributionArray[i].lenSum += len;
 472         SizeDistributionArray[i].count++;
 473         break;
 474       }
 475     }
 476   }
 477 }
 478 
 479 void CodeHeapState::discard_StatArray(outputStream* out) {
 480   if (StatArray != NULL) {
 481     delete StatArray;
 482     StatArray        = NULL;
 483     alloc_granules   = 0;
 484     granule_size     = 0;
 485   }
 486 }
 487 
 488 void CodeHeapState::discard_FreeArray(outputStream* out) {
 489   if (FreeArray != NULL) {
 490     delete[] FreeArray;
 491     FreeArray        = NULL;
 492     alloc_freeBlocks = 0;
 493   }
 494 }
 495 
 496 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 497   if (TopSizeArray != NULL) {
 498     delete[] TopSizeArray;
 499     TopSizeArray        = NULL;
 500     alloc_topSizeBlocks = 0;
 501     used_topSizeBlocks  = 0;
 502   }
 503 }
 504 
 505 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 506   if (SizeDistributionArray != NULL) {
 507     delete[] SizeDistributionArray;
 508     SizeDistributionArray = NULL;
 509   }
 510 }
 511 
 512 // Discard all allocated internal data structures.
 513 // This should be done after an analysis session is completed.
 514 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 515   if (!initialization_complete) {
 516     return;
 517   }
 518 
 519   if (nHeaps > 0) {
 520     for (unsigned int ix = 0; ix < nHeaps; ix++) {
 521       get_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 522       discard_StatArray(out);
 523       discard_FreeArray(out);
 524       discard_TopSizeArray(out);
 525       discard_SizeDistArray(out);
 526       set_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 527       CodeHeapStatArray[ix].heapName = NULL;
 528     }
 529     nHeaps = 0;
 530   }
 531 }
 532 
 533 void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, const char* granularity_request) {
 534   unsigned int nBlocks_free    = 0;
 535   unsigned int nBlocks_used    = 0;
 536   unsigned int nBlocks_zomb    = 0;
 537   unsigned int nBlocks_disconn = 0;
 538   unsigned int nBlocks_notentr = 0;
 539 
 540   //---<  max & min of TopSizeArray  >---
 541   //  it is sufficient to have these sizes as 32bit unsigned ints.
 542   //  The CodeHeap is limited in size to 4GB. Furthermore, the sizes
 543   //  are stored in _segment_size units, scaling them down by a factor of 64 (at least).
 544   unsigned int  currMax          = 0;
 545   unsigned int  currMin          = 0;
 546   unsigned int  currMin_ix       = 0;
 547   unsigned long total_iterations = 0;
 548 
 549   bool  done             = false;
 550   const int min_granules = 256;
 551   const int max_granules = 512*K; // limits analyzable CodeHeap (with segment_granules) to 32M..128M
 552                                   // results in StatArray size of 24M (= max_granules * 48 Bytes per element)
 553                                   // For a 1GB CodeHeap, the granule size must be at least 2kB to not violate the max_granles limit.
 554   const char* heapName   = get_heapName(heap);
 555   BUFFEREDSTREAM_DECL(ast, out)
 556 
 557   if (!initialization_complete) {
 558     memset(CodeHeapStatArray, 0, sizeof(CodeHeapStatArray));
 559     initialization_complete = true;
 560 
 561     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (general remarks)", NULL);
 562     ast->print_cr("   The code heap analysis function provides deep insights into\n"
 563                   "   the inner workings and the internal state of the Java VM's\n"
 564                   "   code cache - the place where all the JVM generated machine\n"
 565                   "   code is stored.\n"
 566                   "   \n"
 567                   "   This function is designed and provided for support engineers\n"
 568                   "   to help them understand and solve issues in customer systems.\n"
 569                   "   It is not intended for use and interpretation by other persons.\n"
 570                   "   \n");
 571     BUFFEREDSTREAM_FLUSH("")
 572   }
 573   get_HeapStatGlobals(out, heapName);
 574 
 575 
 576   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 577   // all heap information is "constant" and can be safely extracted/calculated before we
 578   // enter the while() loop. Actually, the loop will only be iterated once.
 579   char*  low_bound     = heap->low_boundary();
 580   size_t size          = heap->capacity();
 581   size_t res_size      = heap->max_capacity();
 582   seg_size             = heap->segment_size();
 583   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 584 
 585   if (seg_size == 0) {
 586     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 587     BUFFEREDSTREAM_FLUSH("")
 588     return;
 589   }
 590 
 591   if (!CodeCache_lock->owned_by_self()) {
 592     printBox(ast, '-', "aggregate function called without holding the CodeCache_lock for ", heapName);
 593     BUFFEREDSTREAM_FLUSH("")
 594     return;
 595   }
 596 
 597   // Calculate granularity of analysis (and output).
 598   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 599   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 600   //
 601   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 602   //   level of detail, i.e. inspecting and printing each segment on its own.
 603   //
 604   //   The granularity parameter allows to specify the level of detail available in the analysis.
 605   //   It must be a positive multiple of the segment size and should be selected such that enough
 606   //   detail is provided while, at the same time, the printed output does not explode.
 607   //
 608   //   By manipulating the granularity value, we enforce that at least min_granules units
 609   //   of analysis are available. We also enforce an upper limit of max_granules units to
 610   //   keep the amount of allocated storage in check.
 611   //
 612   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.
 613   //   This is necessary to prevent an unsigned short overflow while accumulating space information.
 614   //
 615   size_t granularity = strtol(granularity_request, NULL, 0);
 616   if (granularity > size) {
 617     granularity = size;
 618   }
 619   if (size/granularity < min_granules) {
 620     granularity = size/min_granules;                                   // at least min_granules granules
 621   }
 622   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 623   if (granularity < seg_size) {
 624     granularity = seg_size;                                            // must be at least seg_size
 625   }
 626   if (size/granularity > max_granules) {
 627     granularity = size/max_granules;                                   // at most max_granules granules
 628   }
 629   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 630   if (granularity>>log2_seg_size >= (1L<<sizeof(unsigned short)*8)) {
 631     granularity = ((1L<<(sizeof(unsigned short)*8))-1)<<log2_seg_size; // Limit: (64k-1) * seg_size
 632   }
 633   segment_granules = granularity == seg_size;
 634   size_t granules  = (size + (granularity-1))/granularity;
 635 
 636   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (used blocks) for segment ", heapName);
 637   ast->print_cr("   The aggregate step takes an aggregated snapshot of the CodeHeap.\n"
 638                 "   Subsequent print functions create their output based on this snapshot.\n"
 639                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 640                 "   collected data to be consistent. Only the method names and signatures\n"
 641                 "   are retrieved at print time. That may lead to rare cases where the\n"
 642                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 643   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 644                 size/(size_t)K, size/(size_t)M, res_size/(size_t)K, res_size/(size_t)M, (unsigned int)(100.0*size/res_size));
 645   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 646   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 647   ast->print_cr("   Each granule takes " SIZE_FORMAT " bytes of C heap, that is " SIZE_FORMAT "K in total for statistics data.", sizeof(StatElement), (sizeof(StatElement)*granules)/(size_t)K);
 648   ast->print_cr("   The number of granules is limited to %dk, requiring a granules size of at least %d bytes for a 1GB heap.", (unsigned int)(max_granules/K), (unsigned int)(G/max_granules));
 649   BUFFEREDSTREAM_FLUSH("\n")
 650 
 651 
 652   while (!done) {
 653     //---<  reset counters with every aggregation  >---
 654     nBlocks_t1       = 0;
 655     nBlocks_t2       = 0;
 656     nBlocks_alive    = 0;
 657     nBlocks_dead     = 0;
 658     nBlocks_inconstr = 0;
 659     nBlocks_unloaded = 0;
 660     nBlocks_stub     = 0;
 661 
 662     nBlocks_free     = 0;
 663     nBlocks_used     = 0;
 664     nBlocks_zomb     = 0;
 665     nBlocks_disconn  = 0;
 666     nBlocks_notentr  = 0;
 667 
 668     //---<  discard old arrays if size does not match  >---
 669     if (granules != alloc_granules) {
 670       discard_StatArray(out);
 671       discard_TopSizeArray(out);
 672     }
 673 
 674     //---<  allocate arrays if they don't yet exist, initialize  >---
 675     prepare_StatArray(out, granules, granularity, heapName);
 676     if (StatArray == NULL) {
 677       set_HeapStatGlobals(out, heapName);
 678       return;
 679     }
 680     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 681     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 682 
 683     latest_compilation_id = CompileBroker::get_compilation_id();
 684     unsigned int highest_compilation_id = 0;
 685     size_t       usedSpace     = 0;
 686     size_t       t1Space       = 0;
 687     size_t       t2Space       = 0;
 688     size_t       aliveSpace    = 0;
 689     size_t       disconnSpace  = 0;
 690     size_t       notentrSpace  = 0;
 691     size_t       deadSpace     = 0;
 692     size_t       inconstrSpace = 0;
 693     size_t       unloadedSpace = 0;
 694     size_t       stubSpace     = 0;
 695     size_t       freeSpace     = 0;
 696     size_t       maxFreeSize   = 0;
 697     HeapBlock*   maxFreeBlock  = NULL;
 698     bool         insane        = false;
 699 
 700     int64_t hotnessAccumulator = 0;
 701     unsigned int n_methods     = 0;
 702     avgTemp       = 0;
 703     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 704     maxTemp       = -minTemp;
 705 
 706     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 707       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 708       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 709       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 710       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 711       unsigned int compile_id = 0;
 712       CompLevel    comp_lvl   = CompLevel_none;
 713       compType     cType      = noComp;
 714       blobType     cbType     = noType;
 715 
 716       //---<  some sanity checks  >---
 717       // Do not assert here, just check, print error message and return.
 718       // This is a diagnostic function. It is not supposed to tear down the VM.
 719       if ((char*)h <  low_bound) {
 720         insane = true; ast->print_cr("Sanity check: HeapBlock @%p below low bound (%p)", (char*)h, low_bound);
 721       }
 722       if ((char*)h >  (low_bound + res_size)) {
 723         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside reserved range (%p)", (char*)h, low_bound + res_size);
 724       }
 725       if ((char*)h >  (low_bound + size)) {
 726         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside used range (%p)", (char*)h, low_bound + size);
 727       }
 728       if (ix_end   >= granules) {
 729         insane = true; ast->print_cr("Sanity check: end index (%d) out of bounds (" SIZE_FORMAT ")", ix_end, granules);
 730       }
 731       if (size     != heap->capacity()) {
 732         insane = true; ast->print_cr("Sanity check: code heap capacity has changed (" SIZE_FORMAT "K to " SIZE_FORMAT "K)", size/(size_t)K, heap->capacity()/(size_t)K);
 733       }
 734       if (ix_beg   >  ix_end) {
 735         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 736       }
 737       if (insane) {
 738         BUFFEREDSTREAM_FLUSH("")
 739         continue;
 740       }
 741 
 742       if (h->free()) {
 743         nBlocks_free++;
 744         freeSpace    += hb_bytelen;
 745         if (hb_bytelen > maxFreeSize) {
 746           maxFreeSize   = hb_bytelen;
 747           maxFreeBlock  = h;
 748         }
 749       } else {
 750         update_SizeDistArray(out, hb_len);
 751         nBlocks_used++;
 752         usedSpace    += hb_bytelen;
 753         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 754         if (cb != NULL) {
 755           cbType = get_cbType(cb);
 756           nmethod*  nm = cb->as_nmethod_or_null();
 757           if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
 758             compile_id = nm->compile_id();
 759             comp_lvl   = (CompLevel)(nm->comp_level());
 760             if (nm->is_compiled_by_c1()) {
 761               cType = c1;
 762             }
 763             if (nm->is_compiled_by_c2()) {
 764               cType = c2;
 765             }
 766             if (nm->is_compiled_by_jvmci()) {
 767               cType = jvmci;
 768             }
 769             switch (cbType) {
 770               case nMethod_inuse: { // only for executable methods!!!
 771                 // space for these cbs is accounted for later.
 772                 int temperature = nm->hotness_counter();
 773                 hotnessAccumulator += temperature;
 774                 n_methods++;
 775                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 776                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 777                 break;
 778               }
 779               case nMethod_notused:
 780                 nBlocks_alive++;
 781                 nBlocks_disconn++;
 782                 aliveSpace     += hb_bytelen;
 783                 disconnSpace   += hb_bytelen;
 784                 break;
 785               case nMethod_notentrant:  // equivalent to nMethod_alive
 786                 nBlocks_alive++;
 787                 nBlocks_notentr++;
 788                 aliveSpace     += hb_bytelen;
 789                 notentrSpace   += hb_bytelen;
 790                 break;
 791               case nMethod_unloaded:
 792                 nBlocks_unloaded++;
 793                 unloadedSpace  += hb_bytelen;
 794                 break;
 795               case nMethod_dead:
 796                 nBlocks_dead++;
 797                 deadSpace      += hb_bytelen;
 798                 break;
 799               case nMethod_inconstruction:
 800                 nBlocks_inconstr++;
 801                 inconstrSpace  += hb_bytelen;
 802                 break;
 803               default:
 804                 break;
 805             }
 806           }
 807 
 808           //------------------------------------------
 809           //---<  register block in TopSizeArray  >---
 810           //------------------------------------------
 811           if (alloc_topSizeBlocks > 0) {
 812             if (used_topSizeBlocks == 0) {
 813               TopSizeArray[0].start    = h;
 814               TopSizeArray[0].len      = hb_len;
 815               TopSizeArray[0].index    = tsbStopper;
 816               TopSizeArray[0].compiler = cType;
 817               TopSizeArray[0].level    = comp_lvl;
 818               TopSizeArray[0].type     = cbType;
 819               currMax    = hb_len;
 820               currMin    = hb_len;
 821               currMin_ix = 0;
 822               used_topSizeBlocks++;
 823             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 824             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 825               //---<  all blocks in list are larger, but there is room left in array  >---
 826               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 827               TopSizeArray[used_topSizeBlocks].start    = h;
 828               TopSizeArray[used_topSizeBlocks].len      = hb_len;
 829               TopSizeArray[used_topSizeBlocks].index    = tsbStopper;
 830               TopSizeArray[used_topSizeBlocks].compiler = cType;
 831               TopSizeArray[used_topSizeBlocks].level    = comp_lvl;
 832               TopSizeArray[used_topSizeBlocks].type     = cbType;
 833               currMin    = hb_len;
 834               currMin_ix = used_topSizeBlocks;
 835               used_topSizeBlocks++;
 836             } else {
 837               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 838               //   We don't need to search the list if we know beforehand that the current block size is
 839               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 840               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 841                 if (currMax < hb_len) {
 842                   currMax = hb_len;
 843                 }
 844                 unsigned int i;
 845                 unsigned int prev_i  = tsbStopper;
 846                 unsigned int limit_i =  0;
 847                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 848                   if (limit_i++ >= alloc_topSizeBlocks) {
 849                     insane = true; break; // emergency exit
 850                   }
 851                   if (i >= used_topSizeBlocks)  {
 852                     insane = true; break; // emergency exit
 853                   }
 854                   total_iterations++;
 855                   if (TopSizeArray[i].len < hb_len) {
 856                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 857                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 858                       // old entry gets moved to the next free element of the array.
 859                       // That's necessary to keep the entry for the largest block at index 0.
 860                       // This move might cause the current minimum to be moved to another place
 861                       if (i == currMin_ix) {
 862                         assert(TopSizeArray[i].len == currMin, "sort error");
 863                         currMin_ix = used_topSizeBlocks;
 864                       }
 865                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 866                       TopSizeArray[i].start    = h;
 867                       TopSizeArray[i].len      = hb_len;
 868                       TopSizeArray[i].index    = used_topSizeBlocks;
 869                       TopSizeArray[i].compiler = cType;
 870                       TopSizeArray[i].level    = comp_lvl;
 871                       TopSizeArray[i].type     = cbType;
 872                       used_topSizeBlocks++;
 873                     } else { // no room for new entries, current block replaces entry for smallest block
 874                       //---<  Find last entry (entry for smallest remembered block)  >---
 875                       unsigned int      j  = i;
 876                       unsigned int prev_j  = tsbStopper;
 877                       unsigned int limit_j = 0;
 878                       while (TopSizeArray[j].index != tsbStopper) {
 879                         if (limit_j++ >= alloc_topSizeBlocks) {
 880                           insane = true; break; // emergency exit
 881                         }
 882                         if (j >= used_topSizeBlocks)  {
 883                           insane = true; break; // emergency exit
 884                         }
 885                         total_iterations++;
 886                         prev_j = j;
 887                         j      = TopSizeArray[j].index;
 888                       }
 889                       if (!insane) {
 890                         if (prev_j == tsbStopper) {
 891                           //---<  Above while loop did not iterate, we already are the min entry  >---
 892                           //---<  We have to just replace the smallest entry                      >---
 893                           currMin    = hb_len;
 894                           currMin_ix = j;
 895                           TopSizeArray[j].start    = h;
 896                           TopSizeArray[j].len      = hb_len;
 897                           TopSizeArray[j].index    = tsbStopper; // already set!!
 898                           TopSizeArray[j].compiler = cType;
 899                           TopSizeArray[j].level    = comp_lvl;
 900                           TopSizeArray[j].type     = cbType;
 901                         } else {
 902                           //---<  second-smallest entry is now smallest  >---
 903                           TopSizeArray[prev_j].index = tsbStopper;
 904                           currMin    = TopSizeArray[prev_j].len;
 905                           currMin_ix = prev_j;
 906                           //---<  smallest entry gets overwritten  >---
 907                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 908                           TopSizeArray[i].start    = h;
 909                           TopSizeArray[i].len      = hb_len;
 910                           TopSizeArray[i].index    = j;
 911                           TopSizeArray[i].compiler = cType;
 912                           TopSizeArray[i].level    = comp_lvl;
 913                           TopSizeArray[i].type     = cbType;
 914                         }
 915                       } // insane
 916                     }
 917                     break;
 918                   }
 919                   prev_i = i;
 920                 }
 921                 if (insane) {
 922                   // Note: regular analysis could probably continue by resetting "insane" flag.
 923                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 924                   discard_TopSizeArray(out);
 925                 }
 926               }
 927             }
 928           }
 929           //----------------------------------------------
 930           //---<  END register block in TopSizeArray  >---
 931           //----------------------------------------------
 932         } else {
 933           nBlocks_zomb++;
 934         }
 935 
 936         if (ix_beg == ix_end) {
 937           StatArray[ix_beg].type = cbType;
 938           switch (cbType) {
 939             case nMethod_inuse:
 940               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 941               if (comp_lvl < CompLevel_full_optimization) {
 942                 nBlocks_t1++;
 943                 t1Space   += hb_bytelen;
 944                 StatArray[ix_beg].t1_count++;
 945                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 946                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 947               } else {
 948                 nBlocks_t2++;
 949                 t2Space   += hb_bytelen;
 950                 StatArray[ix_beg].t2_count++;
 951                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 952                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 953               }
 954               StatArray[ix_beg].level     = comp_lvl;
 955               StatArray[ix_beg].compiler  = cType;
 956               break;
 957             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 958             case nMethod_alive:
 959               StatArray[ix_beg].tx_count++;
 960               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
 961               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 962               StatArray[ix_beg].level     = comp_lvl;
 963               StatArray[ix_beg].compiler  = cType;
 964               break;
 965             case nMethod_dead:
 966             case nMethod_unloaded:
 967               StatArray[ix_beg].dead_count++;
 968               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
 969               break;
 970             default:
 971               // must be a stub, if it's not a dead or alive nMethod
 972               nBlocks_stub++;
 973               stubSpace   += hb_bytelen;
 974               StatArray[ix_beg].stub_count++;
 975               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
 976               break;
 977           }
 978         } else {
 979           unsigned int beg_space = (unsigned int)(granule_size - ((char*)h - low_bound - ix_beg*granule_size));
 980           unsigned int end_space = (unsigned int)(hb_bytelen - beg_space - (ix_end-ix_beg-1)*granule_size);
 981           beg_space = beg_space>>log2_seg_size;  // store in units of _segment_size
 982           end_space = end_space>>log2_seg_size;  // store in units of _segment_size
 983           StatArray[ix_beg].type = cbType;
 984           StatArray[ix_end].type = cbType;
 985           switch (cbType) {
 986             case nMethod_inuse:
 987               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 988               if (comp_lvl < CompLevel_full_optimization) {
 989                 nBlocks_t1++;
 990                 t1Space   += hb_bytelen;
 991                 StatArray[ix_beg].t1_count++;
 992                 StatArray[ix_beg].t1_space += (unsigned short)beg_space;
 993                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 994 
 995                 StatArray[ix_end].t1_count++;
 996                 StatArray[ix_end].t1_space += (unsigned short)end_space;
 997                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
 998               } else {
 999                 nBlocks_t2++;
1000                 t2Space   += hb_bytelen;
1001                 StatArray[ix_beg].t2_count++;
1002                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
1003                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
1004 
1005                 StatArray[ix_end].t2_count++;
1006                 StatArray[ix_end].t2_space += (unsigned short)end_space;
1007                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
1008               }
1009               StatArray[ix_beg].level     = comp_lvl;
1010               StatArray[ix_beg].compiler  = cType;
1011               StatArray[ix_end].level     = comp_lvl;
1012               StatArray[ix_end].compiler  = cType;
1013               break;
1014             case nMethod_inconstruction: // let's count "in construction" nmethods here.
1015             case nMethod_alive:
1016               StatArray[ix_beg].tx_count++;
1017               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
1018               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1019 
1020               StatArray[ix_end].tx_count++;
1021               StatArray[ix_end].tx_space += (unsigned short)end_space;
1022               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
1023 
1024               StatArray[ix_beg].level     = comp_lvl;
1025               StatArray[ix_beg].compiler  = cType;
1026               StatArray[ix_end].level     = comp_lvl;
1027               StatArray[ix_end].compiler  = cType;
1028               break;
1029             case nMethod_dead:
1030             case nMethod_unloaded:
1031               StatArray[ix_beg].dead_count++;
1032               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
1033               StatArray[ix_end].dead_count++;
1034               StatArray[ix_end].dead_space += (unsigned short)end_space;
1035               break;
1036             default:
1037               // must be a stub, if it's not a dead or alive nMethod
1038               nBlocks_stub++;
1039               stubSpace   += hb_bytelen;
1040               StatArray[ix_beg].stub_count++;
1041               StatArray[ix_beg].stub_space += (unsigned short)beg_space;
1042               StatArray[ix_end].stub_count++;
1043               StatArray[ix_end].stub_space += (unsigned short)end_space;
1044               break;
1045           }
1046           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
1047             StatArray[ix].type = cbType;
1048             switch (cbType) {
1049               case nMethod_inuse:
1050                 if (comp_lvl < CompLevel_full_optimization) {
1051                   StatArray[ix].t1_count++;
1052                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
1053                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
1054                 } else {
1055                   StatArray[ix].t2_count++;
1056                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
1057                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
1058                 }
1059                 StatArray[ix].level     = comp_lvl;
1060                 StatArray[ix].compiler  = cType;
1061                 break;
1062               case nMethod_inconstruction: // let's count "in construction" nmethods here.
1063               case nMethod_alive:
1064                 StatArray[ix].tx_count++;
1065                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
1066                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
1067                 StatArray[ix].level     = comp_lvl;
1068                 StatArray[ix].compiler  = cType;
1069                 break;
1070               case nMethod_dead:
1071               case nMethod_unloaded:
1072                 StatArray[ix].dead_count++;
1073                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
1074                 break;
1075               default:
1076                 // must be a stub, if it's not a dead or alive nMethod
1077                 StatArray[ix].stub_count++;
1078                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
1079                 break;
1080             }
1081           }
1082         }
1083       }
1084     }
1085     done = true;
1086 
1087     if (!insane) {
1088       // There is a risk for this block (because it contains many print statements) to get
1089       // interspersed with print data from other threads. We take this risk intentionally.
1090       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1091       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1092       ast->print_cr("freeSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_free     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", freeSpace/(size_t)K,     nBlocks_free,     (100.0*freeSpace)/size,     (100.0*freeSpace)/res_size);
1093       ast->print_cr("usedSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_used     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", usedSpace/(size_t)K,     nBlocks_used,     (100.0*usedSpace)/size,     (100.0*usedSpace)/res_size);
1094       ast->print_cr("  Tier1 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t1       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t1Space/(size_t)K,       nBlocks_t1,       (100.0*t1Space)/size,       (100.0*t1Space)/res_size);
1095       ast->print_cr("  Tier2 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t2       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t2Space/(size_t)K,       nBlocks_t2,       (100.0*t2Space)/size,       (100.0*t2Space)/res_size);
1096       ast->print_cr("  Alive Space    = " SIZE_FORMAT_W(8) "k, nBlocks_alive    = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", aliveSpace/(size_t)K,    nBlocks_alive,    (100.0*aliveSpace)/size,    (100.0*aliveSpace)/res_size);
1097       ast->print_cr("    disconnected = " SIZE_FORMAT_W(8) "k, nBlocks_disconn  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", disconnSpace/(size_t)K,  nBlocks_disconn,  (100.0*disconnSpace)/size,  (100.0*disconnSpace)/res_size);
1098       ast->print_cr("    not entrant  = " SIZE_FORMAT_W(8) "k, nBlocks_notentr  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", notentrSpace/(size_t)K,  nBlocks_notentr,  (100.0*notentrSpace)/size,  (100.0*notentrSpace)/res_size);
1099       ast->print_cr("  inconstrSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_inconstr = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", inconstrSpace/(size_t)K, nBlocks_inconstr, (100.0*inconstrSpace)/size, (100.0*inconstrSpace)/res_size);
1100       ast->print_cr("  unloadedSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_unloaded = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", unloadedSpace/(size_t)K, nBlocks_unloaded, (100.0*unloadedSpace)/size, (100.0*unloadedSpace)/res_size);
1101       ast->print_cr("  deadSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_dead     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", deadSpace/(size_t)K,     nBlocks_dead,     (100.0*deadSpace)/size,     (100.0*deadSpace)/res_size);
1102       ast->print_cr("  stubSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_stub     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", stubSpace/(size_t)K,     nBlocks_stub,     (100.0*stubSpace)/size,     (100.0*stubSpace)/res_size);
1103       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1104       ast->cr();
1105       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1106       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1107       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1108       ast->cr();
1109       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1110       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1111       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1112       ast->cr();
1113 
1114       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1115       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1116       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1117       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1118       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1119       if (n_methods > 0) {
1120         avgTemp = hotnessAccumulator/n_methods;
1121         ast->print_cr("min. hotness = %6d", minTemp);
1122         ast->print_cr("avg. hotness = %6d", avgTemp);
1123         ast->print_cr("max. hotness = %6d", maxTemp);
1124       } else {
1125         avgTemp = 0;
1126         ast->print_cr("No hotness data available");
1127       }
1128       BUFFEREDSTREAM_FLUSH("\n")
1129 
1130       // This loop is intentionally printing directly to "out".
1131       // It should not print anything, anyway.
1132       out->print("Verifying collected data...");
1133       size_t granule_segs = granule_size>>log2_seg_size;
1134       for (unsigned int ix = 0; ix < granules; ix++) {
1135         if (StatArray[ix].t1_count   > granule_segs) {
1136           out->print_cr("t1_count[%d]   = %d", ix, StatArray[ix].t1_count);
1137         }
1138         if (StatArray[ix].t2_count   > granule_segs) {
1139           out->print_cr("t2_count[%d]   = %d", ix, StatArray[ix].t2_count);
1140         }
1141         if (StatArray[ix].tx_count   > granule_segs) {
1142           out->print_cr("tx_count[%d]   = %d", ix, StatArray[ix].tx_count);
1143         }
1144         if (StatArray[ix].stub_count > granule_segs) {
1145           out->print_cr("stub_count[%d] = %d", ix, StatArray[ix].stub_count);
1146         }
1147         if (StatArray[ix].dead_count > granule_segs) {
1148           out->print_cr("dead_count[%d] = %d", ix, StatArray[ix].dead_count);
1149         }
1150         if (StatArray[ix].t1_space   > granule_segs) {
1151           out->print_cr("t1_space[%d]   = %d", ix, StatArray[ix].t1_space);
1152         }
1153         if (StatArray[ix].t2_space   > granule_segs) {
1154           out->print_cr("t2_space[%d]   = %d", ix, StatArray[ix].t2_space);
1155         }
1156         if (StatArray[ix].tx_space   > granule_segs) {
1157           out->print_cr("tx_space[%d]   = %d", ix, StatArray[ix].tx_space);
1158         }
1159         if (StatArray[ix].stub_space > granule_segs) {
1160           out->print_cr("stub_space[%d] = %d", ix, StatArray[ix].stub_space);
1161         }
1162         if (StatArray[ix].dead_space > granule_segs) {
1163           out->print_cr("dead_space[%d] = %d", ix, StatArray[ix].dead_space);
1164         }
1165         //   this cast is awful! I need it because NT/Intel reports a signed/unsigned mismatch.
1166         if ((size_t)(StatArray[ix].t1_count+StatArray[ix].t2_count+StatArray[ix].tx_count+StatArray[ix].stub_count+StatArray[ix].dead_count) > granule_segs) {
1167           out->print_cr("t1_count[%d] = %d, t2_count[%d] = %d, tx_count[%d] = %d, stub_count[%d] = %d", ix, StatArray[ix].t1_count, ix, StatArray[ix].t2_count, ix, StatArray[ix].tx_count, ix, StatArray[ix].stub_count);
1168         }
1169         if ((size_t)(StatArray[ix].t1_space+StatArray[ix].t2_space+StatArray[ix].tx_space+StatArray[ix].stub_space+StatArray[ix].dead_space) > granule_segs) {
1170           out->print_cr("t1_space[%d] = %d, t2_space[%d] = %d, tx_space[%d] = %d, stub_space[%d] = %d", ix, StatArray[ix].t1_space, ix, StatArray[ix].t2_space, ix, StatArray[ix].tx_space, ix, StatArray[ix].stub_space);
1171         }
1172       }
1173 
1174       // This loop is intentionally printing directly to "out".
1175       // It should not print anything, anyway.
1176       if (used_topSizeBlocks > 0) {
1177         unsigned int j = 0;
1178         if (TopSizeArray[0].len != currMax) {
1179           out->print_cr("currMax(%d) differs from TopSizeArray[0].len(%d)", currMax, TopSizeArray[0].len);
1180         }
1181         for (unsigned int i = 0; (TopSizeArray[i].index != tsbStopper) && (j++ < alloc_topSizeBlocks); i = TopSizeArray[i].index) {
1182           if (TopSizeArray[i].len < TopSizeArray[TopSizeArray[i].index].len) {
1183             out->print_cr("sort error at index %d: %d !>= %d", i, TopSizeArray[i].len, TopSizeArray[TopSizeArray[i].index].len);
1184           }
1185         }
1186         if (j >= alloc_topSizeBlocks) {
1187           out->print_cr("Possible loop in TopSizeArray chaining!\n  allocBlocks = %d, usedBlocks = %d", alloc_topSizeBlocks, used_topSizeBlocks);
1188           for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1189             out->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1190           }
1191         }
1192       }
1193       out->print_cr("...done\n\n");
1194     } else {
1195       // insane heap state detected. Analysis data incomplete. Just throw it away.
1196       discard_StatArray(out);
1197       discard_TopSizeArray(out);
1198     }
1199   }
1200 
1201 
1202   done        = false;
1203   while (!done && (nBlocks_free > 0)) {
1204 
1205     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (free blocks) for segment ", heapName);
1206     ast->print_cr("   The aggregate step collects information about all free blocks in CodeHeap.\n"
1207                   "   Subsequent print functions create their output based on this snapshot.\n");
1208     ast->print_cr("   Free space in %s is distributed over %d free blocks.", heapName, nBlocks_free);
1209     ast->print_cr("   Each free block takes " SIZE_FORMAT " bytes of C heap for statistics data, that is " SIZE_FORMAT "K in total.", sizeof(FreeBlk), (sizeof(FreeBlk)*nBlocks_free)/K);
1210     BUFFEREDSTREAM_FLUSH("\n")
1211 
1212     //----------------------------------------
1213     //--  Prepare the FreeArray of FreeBlks --
1214     //----------------------------------------
1215 
1216     //---< discard old array if size does not match  >---
1217     if (nBlocks_free != alloc_freeBlocks) {
1218       discard_FreeArray(out);
1219     }
1220 
1221     prepare_FreeArray(out, nBlocks_free, heapName);
1222     if (FreeArray == NULL) {
1223       done = true;
1224       continue;
1225     }
1226 
1227     //----------------------------------------
1228     //--  Collect all FreeBlks in FreeArray --
1229     //----------------------------------------
1230 
1231     unsigned int ix = 0;
1232     FreeBlock* cur  = heap->freelist();
1233 
1234     while (cur != NULL) {
1235       if (ix < alloc_freeBlocks) { // don't index out of bounds if _freelist has more blocks than anticipated
1236         FreeArray[ix].start = cur;
1237         FreeArray[ix].len   = (unsigned int)(cur->length()<<log2_seg_size);
1238         FreeArray[ix].index = ix;
1239       }
1240       cur  = cur->link();
1241       ix++;
1242     }
1243     if (ix != alloc_freeBlocks) {
1244       ast->print_cr("Free block count mismatch. Expected %d free blocks, but found %d.", alloc_freeBlocks, ix);
1245       ast->print_cr("I will update the counter and retry data collection");
1246       BUFFEREDSTREAM_FLUSH("\n")
1247       nBlocks_free = ix;
1248       continue;
1249     }
1250     done = true;
1251   }
1252 
1253   if (!done || (nBlocks_free == 0)) {
1254     if (nBlocks_free == 0) {
1255       printBox(ast, '-', "no free blocks found in ", heapName);
1256     } else if (!done) {
1257       ast->print_cr("Free block count mismatch could not be resolved.");
1258       ast->print_cr("Try to run \"aggregate\" function to update counters");
1259     }
1260     BUFFEREDSTREAM_FLUSH("")
1261 
1262     //---< discard old array and update global values  >---
1263     discard_FreeArray(out);
1264     set_HeapStatGlobals(out, heapName);
1265     return;
1266   }
1267 
1268   //---<  calculate and fill remaining fields  >---
1269   if (FreeArray != NULL) {
1270     // This loop is intentionally printing directly to "out".
1271     // It should not print anything, anyway.
1272     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1273       size_t lenSum = 0;
1274       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1275       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1276         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1277         if ((cb != NULL) && !cb->is_nmethod()) {
1278           FreeArray[ix].stubs_in_gap = true;
1279         }
1280         FreeArray[ix].n_gapBlocks++;
1281         lenSum += h->length()<<log2_seg_size;
1282         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1283           out->print_cr("unsorted occupied CodeHeap block found @ %p, gap interval [%p, %p)", h, (address)FreeArray[ix].start+FreeArray[ix].len, FreeArray[ix+1].start);
1284         }
1285       }
1286       if (lenSum != FreeArray[ix].gap) {
1287         out->print_cr("Length mismatch for gap between FreeBlk[%d] and FreeBlk[%d]. Calculated: %d, accumulated: %d.", ix, ix+1, FreeArray[ix].gap, (unsigned int)lenSum);
1288       }
1289     }
1290   }
1291   set_HeapStatGlobals(out, heapName);
1292 
1293   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   C O M P L E T E   for segment ", heapName);
1294   BUFFEREDSTREAM_FLUSH("\n")
1295 }
1296 
1297 
1298 void CodeHeapState::print_usedSpace(outputStream* out, CodeHeap* heap) {
1299   if (!initialization_complete) {
1300     return;
1301   }
1302 
1303   const char* heapName   = get_heapName(heap);
1304   get_HeapStatGlobals(out, heapName);
1305 
1306   if ((StatArray == NULL) || (TopSizeArray == NULL) || (used_topSizeBlocks == 0)) {
1307     return;
1308   }
1309   BUFFEREDSTREAM_DECL(ast, out)
1310 
1311   {
1312     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1313     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1314                   "      and other identifying information with the block size data.\n"
1315                   "\n"
1316                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1317                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1318                   "      is not continuously held, the displayed name might be wrong or no name\n"
1319                   "      might be found at all. The likelihood for that to happen increases\n"
1320                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1321     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1322   }
1323 
1324   //----------------------------
1325   //--  Print Top Used Blocks --
1326   //----------------------------
1327   {
1328     char*     low_bound = heap->low_boundary();
1329     bool      have_CodeCache_lock = CodeCache_lock->owned_by_self();
1330 
1331     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1332     print_blobType_legend(ast);
1333 
1334     ast->fill_to(51);
1335     ast->print("%4s", "blob");
1336     ast->fill_to(56);
1337     ast->print("%9s", "compiler");
1338     ast->fill_to(66);
1339     ast->print_cr("%6s", "method");
1340     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1341     BUFFEREDSTREAM_FLUSH_LOCKED("")
1342 
1343     //---<  print Top Ten Used Blocks  >---
1344     if (used_topSizeBlocks > 0) {
1345       unsigned int printed_topSizeBlocks = 0;
1346       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1347         printed_topSizeBlocks++;
1348         nmethod*           nm = NULL;
1349         const char* blob_name = "unnamed blob or blob name unavailable";
1350         // heap->find_start() is safe. Only works on _segmap.
1351         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1352         HeapBlock* heapBlock = TopSizeArray[i].start;
1353         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1354         bool    blob_is_safe = blob_access_is_safe(this_blob, NULL);
1355         if (blob_is_safe) {
1356           //---<  access these fields only if we own the CodeCache_lock  >---
1357           if (have_CodeCache_lock) {
1358             blob_name = this_blob->name();
1359             nm        = this_blob->as_nmethod_or_null();
1360           }
1361           //---<  blob address  >---
1362           ast->print(INTPTR_FORMAT, p2i(this_blob));
1363           ast->fill_to(19);
1364           //---<  blob offset from CodeHeap begin  >---
1365           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1366           ast->fill_to(33);
1367         } else {
1368           //---<  block address  >---
1369           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1370           ast->fill_to(19);
1371           //---<  block offset from CodeHeap begin  >---
1372           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1373           ast->fill_to(33);
1374         }
1375 
1376         //---<  print size, name, and signature (for nMethods)  >---
1377         // access nmethod and Method fields only if we own the CodeCache_lock.
1378         // This fact is implicitly transported via nm != NULL.
1379         if (nmethod::access_is_safe(nm)) {
1380           ResourceMark rm;
1381           Method* method = nm->method();
1382           if (nm->is_in_use()) {
1383             blob_name = method->name_and_sig_as_C_string();
1384           }
1385           if (nm->is_not_entrant()) {
1386             blob_name = method->name_and_sig_as_C_string();
1387           }
1388           //---<  nMethod size in hex  >---
1389           unsigned int total_size = nm->total_size();
1390           ast->print(PTR32_FORMAT, total_size);
1391           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
1392           ast->fill_to(51);
1393           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1394           //---<  compiler information  >---
1395           ast->fill_to(56);
1396           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1397           //---<  method temperature  >---
1398           ast->fill_to(67);
1399           ast->print("%5d", nm->hotness_counter());
1400           //---<  name and signature  >---
1401           ast->fill_to(67+6);
1402           if (nm->is_not_installed()) {
1403             ast->print(" not (yet) installed method ");
1404           }
1405           if (nm->is_zombie()) {
1406             ast->print(" zombie method ");
1407           }
1408           ast->print("%s", blob_name);
1409         } else {
1410           //---<  block size in hex  >---
1411           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1412           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1413           //---<  no compiler information  >---
1414           ast->fill_to(56);
1415           //---<  name and signature  >---
1416           ast->fill_to(67+6);
1417           ast->print("%s", blob_name);
1418         }
1419         ast->cr();
1420         BUFFEREDSTREAM_FLUSH_AUTO("")
1421       }
1422       if (used_topSizeBlocks != printed_topSizeBlocks) {
1423         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1424         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1425           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1426           BUFFEREDSTREAM_FLUSH_AUTO("")
1427         }
1428       }
1429       BUFFEREDSTREAM_FLUSH("\n\n")
1430     }
1431   }
1432 
1433   //-----------------------------
1434   //--  Print Usage Histogram  --
1435   //-----------------------------
1436 
1437   if (SizeDistributionArray != NULL) {
1438     unsigned long total_count = 0;
1439     unsigned long total_size  = 0;
1440     const unsigned long pctFactor = 200;
1441 
1442     for (unsigned int i = 0; i < nSizeDistElements; i++) {
1443       total_count += SizeDistributionArray[i].count;
1444       total_size  += SizeDistributionArray[i].lenSum;
1445     }
1446 
1447     if ((total_count > 0) && (total_size > 0)) {
1448       printBox(ast, '-', "Block count histogram for ", heapName);
1449       ast->print_cr("Note: The histogram indicates how many blocks (as a percentage\n"
1450                     "      of all blocks) have a size in the given range.\n"
1451                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1452       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1453       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1454       BUFFEREDSTREAM_FLUSH_LOCKED("")
1455 
1456       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1457       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1458         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1459           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1460                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1461                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1462                     );
1463         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1464           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1465                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1466                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1467                     );
1468         } else {
1469           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1470                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1471                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1472                     );
1473         }
1474         ast->print(" %8d | %8d |",
1475                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1476                    SizeDistributionArray[i].count);
1477 
1478         unsigned int percent = pctFactor*SizeDistributionArray[i].count/total_count;
1479         for (unsigned int j = 1; j <= percent; j++) {
1480           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1481         }
1482         ast->cr();
1483         BUFFEREDSTREAM_FLUSH_AUTO("")
1484       }
1485       ast->print_cr("----------------------------+----------+");
1486       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1487 
1488       printBox(ast, '-', "Contribution per size range to total size for ", heapName);
1489       ast->print_cr("Note: The histogram indicates how much space (as a percentage of all\n"
1490                     "      occupied space) is used by the blocks in the given size range.\n"
1491                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1492       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1493       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1494       BUFFEREDSTREAM_FLUSH_LOCKED("")
1495 
1496       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1497       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1498         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1499           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1500                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1501                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1502                     );
1503         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1504           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1505                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1506                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1507                     );
1508         } else {
1509           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1510                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1511                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1512                     );
1513         }
1514         ast->print(" %8d | %8d |",
1515                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1516                    SizeDistributionArray[i].count);
1517 
1518         unsigned int percent = pctFactor*(unsigned long)SizeDistributionArray[i].lenSum/total_size;
1519         for (unsigned int j = 1; j <= percent; j++) {
1520           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1521         }
1522         ast->cr();
1523         BUFFEREDSTREAM_FLUSH_AUTO("")
1524       }
1525       ast->print_cr("----------------------------+----------+");
1526       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1527     }
1528   }
1529 }
1530 
1531 
1532 void CodeHeapState::print_freeSpace(outputStream* out, CodeHeap* heap) {
1533   if (!initialization_complete) {
1534     return;
1535   }
1536 
1537   const char* heapName   = get_heapName(heap);
1538   get_HeapStatGlobals(out, heapName);
1539 
1540   if ((StatArray == NULL) || (FreeArray == NULL) || (alloc_granules == 0)) {
1541     return;
1542   }
1543   BUFFEREDSTREAM_DECL(ast, out)
1544 
1545   {
1546     printBox(ast, '=', "F R E E   S P A C E   S T A T I S T I C S   for ", heapName);
1547     ast->print_cr("Note: in this context, a gap is the occupied space between two free blocks.\n"
1548                   "      Those gaps are of interest if there is a chance that they become\n"
1549                   "      unoccupied, e.g. by class unloading. Then, the two adjacent free\n"
1550                   "      blocks, together with the now unoccupied space, form a new, large\n"
1551                   "      free block.");
1552     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1553   }
1554 
1555   {
1556     printBox(ast, '-', "List of all Free Blocks in ", heapName);
1557 
1558     unsigned int ix = 0;
1559     for (ix = 0; ix < alloc_freeBlocks-1; ix++) {
1560       ast->print(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT ",", p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1561       ast->fill_to(38);
1562       ast->print("Gap[%4d..%4d]: " HEX32_FORMAT " bytes,", ix, ix+1, FreeArray[ix].gap);
1563       ast->fill_to(71);
1564       ast->print("block count: %6d", FreeArray[ix].n_gapBlocks);
1565       if (FreeArray[ix].stubs_in_gap) {
1566         ast->print(" !! permanent gap, contains stubs and/or blobs !!");
1567       }
1568       ast->cr();
1569       BUFFEREDSTREAM_FLUSH_AUTO("")
1570     }
1571     ast->print_cr(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT, p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1572     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1573   }
1574 
1575 
1576   //-----------------------------------------
1577   //--  Find and Print Top Ten Free Blocks --
1578   //-----------------------------------------
1579 
1580   //---<  find Top Ten Free Blocks  >---
1581   const unsigned int nTop = 10;
1582   unsigned int  currMax10 = 0;
1583   struct FreeBlk* FreeTopTen[nTop];
1584   memset(FreeTopTen, 0, sizeof(FreeTopTen));
1585 
1586   for (unsigned int ix = 0; ix < alloc_freeBlocks; ix++) {
1587     if (FreeArray[ix].len > currMax10) {  // larger than the ten largest found so far
1588       unsigned int currSize = FreeArray[ix].len;
1589 
1590       unsigned int iy;
1591       for (iy = 0; iy < nTop && FreeTopTen[iy] != NULL; iy++) {
1592         if (FreeTopTen[iy]->len < currSize) {
1593           for (unsigned int iz = nTop-1; iz > iy; iz--) { // make room to insert new free block
1594             FreeTopTen[iz] = FreeTopTen[iz-1];
1595           }
1596           FreeTopTen[iy] = &FreeArray[ix];        // insert new free block
1597           if (FreeTopTen[nTop-1] != NULL) {
1598             currMax10 = FreeTopTen[nTop-1]->len;
1599           }
1600           break; // done with this, check next free block
1601         }
1602       }
1603       if (iy >= nTop) {
1604         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1605                       currSize, currMax10);
1606         continue;
1607       }
1608       if (FreeTopTen[iy] == NULL) {
1609         FreeTopTen[iy] = &FreeArray[ix];
1610         if (iy == (nTop-1)) {
1611           currMax10 = currSize;
1612         }
1613       }
1614     }
1615   }
1616   BUFFEREDSTREAM_FLUSH_AUTO("")
1617 
1618   {
1619     printBox(ast, '-', "Top Ten Free Blocks in ", heapName);
1620 
1621     //---<  print Top Ten Free Blocks  >---
1622     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTen[iy] != NULL); iy++) {
1623       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTen[iy]->index, FreeTopTen[iy]->len);
1624       ast->fill_to(39);
1625       if (FreeTopTen[iy]->index == (alloc_freeBlocks-1)) {
1626         ast->print("last free block in list.");
1627       } else {
1628         ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTen[iy]->gap);
1629         ast->fill_to(63);
1630         ast->print("#blocks (in gap) %d", FreeTopTen[iy]->n_gapBlocks);
1631       }
1632       ast->cr();
1633       BUFFEREDSTREAM_FLUSH_AUTO("")
1634     }
1635   }
1636   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1637 
1638 
1639   //--------------------------------------------------------
1640   //--  Find and Print Top Ten Free-Occupied-Free Triples --
1641   //--------------------------------------------------------
1642 
1643   //---<  find and print Top Ten Triples (Free-Occupied-Free)  >---
1644   currMax10 = 0;
1645   struct FreeBlk  *FreeTopTenTriple[nTop];
1646   memset(FreeTopTenTriple, 0, sizeof(FreeTopTenTriple));
1647 
1648   for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1649     // If there are stubs in the gap, this gap will never become completely free.
1650     // The triple will thus never merge to one free block.
1651     unsigned int lenTriple  = FreeArray[ix].len + (FreeArray[ix].stubs_in_gap ? 0 : FreeArray[ix].gap + FreeArray[ix+1].len);
1652     FreeArray[ix].len = lenTriple;
1653     if (lenTriple > currMax10) {  // larger than the ten largest found so far
1654 
1655       unsigned int iy;
1656       for (iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1657         if (FreeTopTenTriple[iy]->len < lenTriple) {
1658           for (unsigned int iz = nTop-1; iz > iy; iz--) {
1659             FreeTopTenTriple[iz] = FreeTopTenTriple[iz-1];
1660           }
1661           FreeTopTenTriple[iy] = &FreeArray[ix];
1662           if (FreeTopTenTriple[nTop-1] != NULL) {
1663             currMax10 = FreeTopTenTriple[nTop-1]->len;
1664           }
1665           break;
1666         }
1667       }
1668       if (iy == nTop) {
1669         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1670                       lenTriple, currMax10);
1671         continue;
1672       }
1673       if (FreeTopTenTriple[iy] == NULL) {
1674         FreeTopTenTriple[iy] = &FreeArray[ix];
1675         if (iy == (nTop-1)) {
1676           currMax10 = lenTriple;
1677         }
1678       }
1679     }
1680   }
1681   BUFFEREDSTREAM_FLUSH_AUTO("")
1682 
1683   {
1684     printBox(ast, '-', "Top Ten Free-Occupied-Free Triples in ", heapName);
1685     ast->print_cr("  Use this information to judge how likely it is that a large(r) free block\n"
1686                   "  might get created by code cache sweeping.\n"
1687                   "  If all the occupied blocks can be swept, the three free blocks will be\n"
1688                   "  merged into one (much larger) free block. That would reduce free space\n"
1689                   "  fragmentation.\n");
1690 
1691     //---<  print Top Ten Free-Occupied-Free Triples  >---
1692     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1693       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTenTriple[iy]->index, FreeTopTenTriple[iy]->len);
1694       ast->fill_to(39);
1695       ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTenTriple[iy]->gap);
1696       ast->fill_to(63);
1697       ast->print("#blocks (in gap) %d", FreeTopTenTriple[iy]->n_gapBlocks);
1698       ast->cr();
1699       BUFFEREDSTREAM_FLUSH_AUTO("")
1700     }
1701   }
1702   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1703 }
1704 
1705 
1706 void CodeHeapState::print_count(outputStream* out, CodeHeap* heap) {
1707   if (!initialization_complete) {
1708     return;
1709   }
1710 
1711   const char* heapName   = get_heapName(heap);
1712   get_HeapStatGlobals(out, heapName);
1713 
1714   if ((StatArray == NULL) || (alloc_granules == 0)) {
1715     return;
1716   }
1717   BUFFEREDSTREAM_DECL(ast, out)
1718 
1719   unsigned int granules_per_line = 32;
1720   char*        low_bound         = heap->low_boundary();
1721 
1722   {
1723     printBox(ast, '=', "B L O C K   C O U N T S   for ", heapName);
1724     ast->print_cr("  Each granule contains an individual number of heap blocks. Large blocks\n"
1725                   "  may span multiple granules and are counted for each granule they touch.\n");
1726     if (segment_granules) {
1727       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1728                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1729                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1730                     "  Occupied granules show their BlobType character, see legend.\n");
1731       print_blobType_legend(ast);
1732     }
1733     BUFFEREDSTREAM_FLUSH_LOCKED("")
1734   }
1735 
1736   {
1737     if (segment_granules) {
1738       printBox(ast, '-', "Total (all types) count for granule size == segment size", NULL);
1739 
1740       granules_per_line = 128;
1741       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1742         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1743         print_blobType_single(ast, StatArray[ix].type);
1744       }
1745     } else {
1746       printBox(ast, '-', "Total (all tiers) count, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1747 
1748       granules_per_line = 128;
1749       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1750         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1751         unsigned int count = StatArray[ix].t1_count   + StatArray[ix].t2_count   + StatArray[ix].tx_count
1752                            + StatArray[ix].stub_count + StatArray[ix].dead_count;
1753         print_count_single(ast, count);
1754       }
1755     }
1756     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1757   }
1758 
1759   {
1760     if (nBlocks_t1 > 0) {
1761       printBox(ast, '-', "Tier1 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1762 
1763       granules_per_line = 128;
1764       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1765         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1766         if (segment_granules && StatArray[ix].t1_count > 0) {
1767           print_blobType_single(ast, StatArray[ix].type);
1768         } else {
1769           print_count_single(ast, StatArray[ix].t1_count);
1770         }
1771       }
1772       ast->print("|");
1773     } else {
1774       ast->print("No Tier1 nMethods found in CodeHeap.");
1775     }
1776     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1777   }
1778 
1779   {
1780     if (nBlocks_t2 > 0) {
1781       printBox(ast, '-', "Tier2 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1782 
1783       granules_per_line = 128;
1784       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1785         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1786         if (segment_granules && StatArray[ix].t2_count > 0) {
1787           print_blobType_single(ast, StatArray[ix].type);
1788         } else {
1789           print_count_single(ast, StatArray[ix].t2_count);
1790         }
1791       }
1792       ast->print("|");
1793     } else {
1794       ast->print("No Tier2 nMethods found in CodeHeap.");
1795     }
1796     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1797   }
1798 
1799   {
1800     if (nBlocks_alive > 0) {
1801       printBox(ast, '-', "not_used/not_entrant/not_installed nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1802 
1803       granules_per_line = 128;
1804       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1805         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1806         if (segment_granules && StatArray[ix].tx_count > 0) {
1807           print_blobType_single(ast, StatArray[ix].type);
1808         } else {
1809           print_count_single(ast, StatArray[ix].tx_count);
1810         }
1811       }
1812       ast->print("|");
1813     } else {
1814       ast->print("No not_used/not_entrant nMethods found in CodeHeap.");
1815     }
1816     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1817   }
1818 
1819   {
1820     if (nBlocks_stub > 0) {
1821       printBox(ast, '-', "Stub & Blob count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1822 
1823       granules_per_line = 128;
1824       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1825         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1826         if (segment_granules && StatArray[ix].stub_count > 0) {
1827           print_blobType_single(ast, StatArray[ix].type);
1828         } else {
1829           print_count_single(ast, StatArray[ix].stub_count);
1830         }
1831       }
1832       ast->print("|");
1833     } else {
1834       ast->print("No Stubs and Blobs found in CodeHeap.");
1835     }
1836     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1837   }
1838 
1839   {
1840     if (nBlocks_dead > 0) {
1841       printBox(ast, '-', "Dead nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1842 
1843       granules_per_line = 128;
1844       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1845         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1846         if (segment_granules && StatArray[ix].dead_count > 0) {
1847           print_blobType_single(ast, StatArray[ix].type);
1848         } else {
1849           print_count_single(ast, StatArray[ix].dead_count);
1850         }
1851       }
1852       ast->print("|");
1853     } else {
1854       ast->print("No dead nMethods found in CodeHeap.");
1855     }
1856     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1857   }
1858 
1859   {
1860     if (!segment_granules) { // Prevent totally redundant printouts
1861       printBox(ast, '-', "Count by tier (combined, no dead blocks): <#t1>:<#t2>:<#s>, 0x0..0xf. '*' indicates >= 16 blocks", NULL);
1862 
1863       granules_per_line = 24;
1864       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1865         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1866 
1867         print_count_single(ast, StatArray[ix].t1_count);
1868         ast->print(":");
1869         print_count_single(ast, StatArray[ix].t2_count);
1870         ast->print(":");
1871         if (segment_granules && StatArray[ix].stub_count > 0) {
1872           print_blobType_single(ast, StatArray[ix].type);
1873         } else {
1874           print_count_single(ast, StatArray[ix].stub_count);
1875         }
1876         ast->print(" ");
1877       }
1878       BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1879     }
1880   }
1881 }
1882 
1883 
1884 void CodeHeapState::print_space(outputStream* out, CodeHeap* heap) {
1885   if (!initialization_complete) {
1886     return;
1887   }
1888 
1889   const char* heapName   = get_heapName(heap);
1890   get_HeapStatGlobals(out, heapName);
1891 
1892   if ((StatArray == NULL) || (alloc_granules == 0)) {
1893     return;
1894   }
1895   BUFFEREDSTREAM_DECL(ast, out)
1896 
1897   unsigned int granules_per_line = 32;
1898   char*        low_bound         = heap->low_boundary();
1899 
1900   {
1901     printBox(ast, '=', "S P A C E   U S A G E  &  F R A G M E N T A T I O N   for ", heapName);
1902     ast->print_cr("  The heap space covered by one granule is occupied to a various extend.\n"
1903                   "  The granule occupancy is displayed by one decimal digit per granule.\n");
1904     if (segment_granules) {
1905       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1906                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1907                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1908                     "  Occupied granules show their BlobType character, see legend.\n");
1909       print_blobType_legend(ast);
1910     } else {
1911       ast->print_cr("  These digits represent a fill percentage range (see legend).\n");
1912       print_space_legend(ast);
1913     }
1914     BUFFEREDSTREAM_FLUSH_LOCKED("")
1915   }
1916 
1917   {
1918     if (segment_granules) {
1919       printBox(ast, '-', "Total (all types) space consumption for granule size == segment size", NULL);
1920 
1921       granules_per_line = 128;
1922       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1923         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1924         print_blobType_single(ast, StatArray[ix].type);
1925       }
1926     } else {
1927       printBox(ast, '-', "Total (all types) space consumption. ' ' indicates empty, '*' indicates full.", NULL);
1928 
1929       granules_per_line = 128;
1930       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1931         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1932         unsigned int space    = StatArray[ix].t1_space   + StatArray[ix].t2_space  + StatArray[ix].tx_space
1933                               + StatArray[ix].stub_space + StatArray[ix].dead_space;
1934         print_space_single(ast, space);
1935       }
1936     }
1937     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1938   }
1939 
1940   {
1941     if (nBlocks_t1 > 0) {
1942       printBox(ast, '-', "Tier1 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1943 
1944       granules_per_line = 128;
1945       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1946         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1947         if (segment_granules && StatArray[ix].t1_space > 0) {
1948           print_blobType_single(ast, StatArray[ix].type);
1949         } else {
1950           print_space_single(ast, StatArray[ix].t1_space);
1951         }
1952       }
1953       ast->print("|");
1954     } else {
1955       ast->print("No Tier1 nMethods found in CodeHeap.");
1956     }
1957     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1958   }
1959 
1960   {
1961     if (nBlocks_t2 > 0) {
1962       printBox(ast, '-', "Tier2 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1963 
1964       granules_per_line = 128;
1965       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1966         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1967         if (segment_granules && StatArray[ix].t2_space > 0) {
1968           print_blobType_single(ast, StatArray[ix].type);
1969         } else {
1970           print_space_single(ast, StatArray[ix].t2_space);
1971         }
1972       }
1973       ast->print("|");
1974     } else {
1975       ast->print("No Tier2 nMethods found in CodeHeap.");
1976     }
1977     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1978   }
1979 
1980   {
1981     if (nBlocks_alive > 0) {
1982       printBox(ast, '-', "not_used/not_entrant/not_installed space consumption. ' ' indicates empty, '*' indicates full", NULL);
1983 
1984       granules_per_line = 128;
1985       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1986         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1987         if (segment_granules && StatArray[ix].tx_space > 0) {
1988           print_blobType_single(ast, StatArray[ix].type);
1989         } else {
1990           print_space_single(ast, StatArray[ix].tx_space);
1991         }
1992       }
1993       ast->print("|");
1994     } else {
1995       ast->print("No Tier2 nMethods found in CodeHeap.");
1996     }
1997     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1998   }
1999 
2000   {
2001     if (nBlocks_stub > 0) {
2002       printBox(ast, '-', "Stub and Blob space consumption. ' ' indicates empty, '*' indicates full", NULL);
2003 
2004       granules_per_line = 128;
2005       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2006         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2007         if (segment_granules && StatArray[ix].stub_space > 0) {
2008           print_blobType_single(ast, StatArray[ix].type);
2009         } else {
2010           print_space_single(ast, StatArray[ix].stub_space);
2011         }
2012       }
2013       ast->print("|");
2014     } else {
2015       ast->print("No Stubs and Blobs found in CodeHeap.");
2016     }
2017     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2018   }
2019 
2020   {
2021     if (nBlocks_dead > 0) {
2022       printBox(ast, '-', "Dead space consumption. ' ' indicates empty, '*' indicates full", NULL);
2023 
2024       granules_per_line = 128;
2025       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2026         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2027         print_space_single(ast, StatArray[ix].dead_space);
2028       }
2029       ast->print("|");
2030     } else {
2031       ast->print("No dead nMethods found in CodeHeap.");
2032     }
2033     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2034   }
2035 
2036   {
2037     if (!segment_granules) { // Prevent totally redundant printouts
2038       printBox(ast, '-', "Space consumption by tier (combined): <t1%>:<t2%>:<s%>. ' ' indicates empty, '*' indicates full", NULL);
2039 
2040       granules_per_line = 24;
2041       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2042         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2043 
2044         if (segment_granules && StatArray[ix].t1_space > 0) {
2045           print_blobType_single(ast, StatArray[ix].type);
2046         } else {
2047           print_space_single(ast, StatArray[ix].t1_space);
2048         }
2049         ast->print(":");
2050         if (segment_granules && StatArray[ix].t2_space > 0) {
2051           print_blobType_single(ast, StatArray[ix].type);
2052         } else {
2053           print_space_single(ast, StatArray[ix].t2_space);
2054         }
2055         ast->print(":");
2056         if (segment_granules && StatArray[ix].stub_space > 0) {
2057           print_blobType_single(ast, StatArray[ix].type);
2058         } else {
2059           print_space_single(ast, StatArray[ix].stub_space);
2060         }
2061         ast->print(" ");
2062       }
2063       ast->print("|");
2064       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2065     }
2066   }
2067 }
2068 
2069 void CodeHeapState::print_age(outputStream* out, CodeHeap* heap) {
2070   if (!initialization_complete) {
2071     return;
2072   }
2073 
2074   const char* heapName   = get_heapName(heap);
2075   get_HeapStatGlobals(out, heapName);
2076 
2077   if ((StatArray == NULL) || (alloc_granules == 0)) {
2078     return;
2079   }
2080   BUFFEREDSTREAM_DECL(ast, out)
2081 
2082   unsigned int granules_per_line = 32;
2083   char*        low_bound         = heap->low_boundary();
2084 
2085   {
2086     printBox(ast, '=', "M E T H O D   A G E   by CompileID for ", heapName);
2087     ast->print_cr("  The age of a compiled method in the CodeHeap is not available as a\n"
2088                   "  time stamp. Instead, a relative age is deducted from the method's compilation ID.\n"
2089                   "  Age information is available for tier1 and tier2 methods only. There is no\n"
2090                   "  age information for stubs and blobs, because they have no compilation ID assigned.\n"
2091                   "  Information for the youngest method (highest ID) in the granule is printed.\n"
2092                   "  Refer to the legend to learn how method age is mapped to the displayed digit.");
2093     print_age_legend(ast);
2094     BUFFEREDSTREAM_FLUSH_LOCKED("")
2095   }
2096 
2097   {
2098     printBox(ast, '-', "Age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2099 
2100     granules_per_line = 128;
2101     for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2102       print_line_delim(out, ast, low_bound, ix, granules_per_line);
2103       unsigned int age1      = StatArray[ix].t1_age;
2104       unsigned int age2      = StatArray[ix].t2_age;
2105       unsigned int agex      = StatArray[ix].tx_age;
2106       unsigned int age       = age1 > age2 ? age1 : age2;
2107       age       = age > agex ? age : agex;
2108       print_age_single(ast, age);
2109     }
2110     ast->print("|");
2111     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2112   }
2113 
2114   {
2115     if (nBlocks_t1 > 0) {
2116       printBox(ast, '-', "Tier1 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2117 
2118       granules_per_line = 128;
2119       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2120         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2121         print_age_single(ast, StatArray[ix].t1_age);
2122       }
2123       ast->print("|");
2124     } else {
2125       ast->print("No Tier1 nMethods found in CodeHeap.");
2126     }
2127     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2128   }
2129 
2130   {
2131     if (nBlocks_t2 > 0) {
2132       printBox(ast, '-', "Tier2 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2133 
2134       granules_per_line = 128;
2135       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2136         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2137         print_age_single(ast, StatArray[ix].t2_age);
2138       }
2139       ast->print("|");
2140     } else {
2141       ast->print("No Tier2 nMethods found in CodeHeap.");
2142     }
2143     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2144   }
2145 
2146   {
2147     if (nBlocks_alive > 0) {
2148       printBox(ast, '-', "not_used/not_entrant/not_installed age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2149 
2150       granules_per_line = 128;
2151       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2152         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2153         print_age_single(ast, StatArray[ix].tx_age);
2154       }
2155       ast->print("|");
2156     } else {
2157       ast->print("No Tier2 nMethods found in CodeHeap.");
2158     }
2159     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2160   }
2161 
2162   {
2163     if (!segment_granules) { // Prevent totally redundant printouts
2164       printBox(ast, '-', "age distribution by tier <a1>:<a2>. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2165 
2166       granules_per_line = 32;
2167       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2168         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2169         print_age_single(ast, StatArray[ix].t1_age);
2170         ast->print(":");
2171         print_age_single(ast, StatArray[ix].t2_age);
2172         ast->print(" ");
2173       }
2174       ast->print("|");
2175       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2176     }
2177   }
2178 }
2179 
2180 
2181 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2182   if (!initialization_complete) {
2183     return;
2184   }
2185 
2186   const char* heapName   = get_heapName(heap);
2187   get_HeapStatGlobals(out, heapName);
2188 
2189   if ((StatArray == NULL) || (alloc_granules == 0)) {
2190     return;
2191   }
2192   BUFFEREDSTREAM_DECL(ast, out)
2193 
2194   unsigned int granules_per_line   = 128;
2195   char*        low_bound           = heap->low_boundary();
2196   CodeBlob*    last_blob           = NULL;
2197   bool         name_in_addr_range  = true;
2198   bool         have_CodeCache_lock = CodeCache_lock->owned_by_self();
2199 
2200   //---<  print at least 128K per block (i.e. between headers)  >---
2201   if (granules_per_line*granule_size < 128*K) {
2202     granules_per_line = (unsigned int)((128*K)/granule_size);
2203   }
2204 
2205   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2206   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2207                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2208                 "  is not continuously held, the displayed name might be wrong or no name\n"
2209                 "  might be found at all. The likelihood for that to happen increases\n"
2210                 "  over time passed between aggregtion and print steps.\n");
2211   BUFFEREDSTREAM_FLUSH_LOCKED("")
2212 
2213   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2214     //---<  print a new blob on a new line  >---
2215     if (ix%granules_per_line == 0) {
2216       if (!name_in_addr_range) {
2217         ast->print_cr("No methods, blobs, or stubs found in this address range");
2218       }
2219       name_in_addr_range = false;
2220 
2221       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2222       ast->cr();
2223       ast->print_cr("--------------------------------------------------------------------");
2224       ast->print_cr("Address range [" INTPTR_FORMAT "," INTPTR_FORMAT "), " SIZE_FORMAT "k", p2i(low_bound+ix*granule_size), p2i(low_bound + end_ix*granule_size), (end_ix - ix)*granule_size/(size_t)K);
2225       ast->print_cr("--------------------------------------------------------------------");
2226       BUFFEREDSTREAM_FLUSH_AUTO("")
2227     }
2228     // Only check granule if it contains at least one blob.
2229     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2230                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2231     if (nBlobs > 0 ) {
2232     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2233       // heap->find_start() is safe. Only works on _segmap.
2234       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2235       char*     this_seg  = low_bound + ix*granule_size + is;
2236       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2237       bool   blob_is_safe = blob_access_is_safe(this_blob, NULL);
2238       // blob could have been flushed, freed, and merged.
2239       // this_blob < last_blob is an indicator for that.
2240       if (blob_is_safe && (this_blob > last_blob)) {
2241         last_blob          = this_blob;
2242 
2243         //---<  get type and name  >---
2244         blobType       cbType = noType;
2245         if (segment_granules) {
2246           cbType = (blobType)StatArray[ix].type;
2247         } else {
2248           //---<  access these fields only if we own the CodeCache_lock  >---
2249           if (have_CodeCache_lock) {
2250             cbType = get_cbType(this_blob);
2251           }
2252         }
2253 
2254         //---<  access these fields only if we own the CodeCache_lock  >---
2255         const char* blob_name = "<unavailable>";
2256         nmethod*           nm = NULL;
2257         if (have_CodeCache_lock) {
2258           blob_name = this_blob->name();
2259           nm        = this_blob->as_nmethod_or_null();
2260           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack
2261           if ((blob_name == NULL) || !os::is_readable_pointer(blob_name)) {
2262             blob_name = "<unavailable>";
2263           }
2264         }
2265 
2266         //---<  print table header for new print range  >---
2267         if (!name_in_addr_range) {
2268           name_in_addr_range = true;
2269           ast->fill_to(51);
2270           ast->print("%9s", "compiler");
2271           ast->fill_to(61);
2272           ast->print_cr("%6s", "method");
2273           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2274           BUFFEREDSTREAM_FLUSH_AUTO("")
2275         }
2276 
2277         //---<  print line prefix (address and offset from CodeHeap start)  >---
2278         ast->print(INTPTR_FORMAT, p2i(this_blob));
2279         ast->fill_to(19);
2280         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2281         ast->fill_to(33);
2282 
2283         // access nmethod and Method fields only if we own the CodeCache_lock.
2284         // This fact is implicitly transported via nm != NULL.
2285         if (nmethod::access_is_safe(nm)) {
2286           Method* method = nm->method();
2287           ResourceMark rm;
2288           //---<  collect all data to locals as quickly as possible  >---
2289           unsigned int total_size = nm->total_size();
2290           int          hotness    = nm->hotness_counter();
2291           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2292           //---<  nMethod size in hex  >---
2293           ast->print(PTR32_FORMAT, total_size);
2294           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2295           //---<  compiler information  >---
2296           ast->fill_to(51);
2297           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2298           //---<  method temperature  >---
2299           ast->fill_to(62);
2300           ast->print("%5d", hotness);
2301           //---<  name and signature  >---
2302           ast->fill_to(62+6);
2303           ast->print("%s", blobTypeName[cbType]);
2304           ast->fill_to(82+6);
2305           if (cbType == nMethod_dead) {
2306             ast->print("%14s", " zombie method");
2307           }
2308 
2309           if (get_name) {
2310             Symbol* methName  = method->name();
2311             const char*   methNameS = (methName == NULL) ? NULL : methName->as_C_string();
2312             methNameS = (methNameS == NULL) ? "<method name unavailable>" : methNameS;
2313             Symbol* methSig   = method->signature();
2314             const char*   methSigS  = (methSig  == NULL) ? NULL : methSig->as_C_string();
2315             methSigS  = (methSigS  == NULL) ? "<method signature unavailable>" : methSigS;
2316             ast->print("%s", methNameS);
2317             ast->print("%s", methSigS);
2318           } else {
2319             ast->print("%s", blob_name);
2320           }
2321         } else if (blob_is_safe) {
2322           ast->fill_to(62+6);
2323           ast->print("%s", blobTypeName[cbType]);
2324           ast->fill_to(82+6);
2325           ast->print("%s", blob_name);
2326         } else {
2327           ast->fill_to(62+6);
2328           ast->print("<stale blob>");
2329         }
2330         ast->cr();
2331         BUFFEREDSTREAM_FLUSH_AUTO("")
2332       } else if (!blob_is_safe && (this_blob != last_blob) && (this_blob != NULL)) {
2333         last_blob          = this_blob;
2334       }
2335     }
2336     } // nBlobs > 0
2337   }
2338   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
2339 }
2340 
2341 
2342 void CodeHeapState::printBox(outputStream* ast, const char border, const char* text1, const char* text2) {
2343   unsigned int lineLen = 1 + 2 + 2 + 1;
2344   char edge, frame;
2345 
2346   if (text1 != NULL) {
2347     lineLen += (unsigned int)strlen(text1); // text1 is much shorter than MAX_INT chars.
2348   }
2349   if (text2 != NULL) {
2350     lineLen += (unsigned int)strlen(text2); // text2 is much shorter than MAX_INT chars.
2351   }
2352   if (border == '-') {
2353     edge  = '+';
2354     frame = '|';
2355   } else {
2356     edge  = border;
2357     frame = border;
2358   }
2359 
2360   ast->print("%c", edge);
2361   for (unsigned int i = 0; i < lineLen-2; i++) {
2362     ast->print("%c", border);
2363   }
2364   ast->print_cr("%c", edge);
2365 
2366   ast->print("%c  ", frame);
2367   if (text1 != NULL) {
2368     ast->print("%s", text1);
2369   }
2370   if (text2 != NULL) {
2371     ast->print("%s", text2);
2372   }
2373   ast->print_cr("  %c", frame);
2374 
2375   ast->print("%c", edge);
2376   for (unsigned int i = 0; i < lineLen-2; i++) {
2377     ast->print("%c", border);
2378   }
2379   ast->print_cr("%c", edge);
2380 }
2381 
2382 void CodeHeapState::print_blobType_legend(outputStream* out) {
2383   out->cr();
2384   printBox(out, '-', "Block types used in the following CodeHeap dump", NULL);
2385   for (int type = noType; type < lastType; type += 1) {
2386     out->print_cr("  %c - %s", blobTypeChar[type], blobTypeName[type]);
2387   }
2388   out->print_cr("  -----------------------------------------------------");
2389   out->cr();
2390 }
2391 
2392 void CodeHeapState::print_space_legend(outputStream* out) {
2393   unsigned int indicator = 0;
2394   unsigned int age_range = 256;
2395   unsigned int range_beg = latest_compilation_id;
2396   out->cr();
2397   printBox(out, '-', "Space ranges, based on granule occupancy", NULL);
2398   out->print_cr("    -   0%% == occupancy");
2399   for (int i=0; i<=9; i++) {
2400     out->print_cr("  %d - %3d%% < occupancy < %3d%%", i, 10*i, 10*(i+1));
2401   }
2402   out->print_cr("  * - 100%% == occupancy");
2403   out->print_cr("  ----------------------------------------------");
2404   out->cr();
2405 }
2406 
2407 void CodeHeapState::print_age_legend(outputStream* out) {
2408   unsigned int indicator = 0;
2409   unsigned int age_range = 256;
2410   unsigned int range_beg = latest_compilation_id;
2411   out->cr();
2412   printBox(out, '-', "Age ranges, based on compilation id", NULL);
2413   while (age_range > 0) {
2414     out->print_cr("  %d - %6d to %6d", indicator, range_beg, latest_compilation_id - latest_compilation_id/age_range);
2415     range_beg = latest_compilation_id - latest_compilation_id/age_range;
2416     age_range /= 2;
2417     indicator += 1;
2418   }
2419   out->print_cr("  -----------------------------------------");
2420   out->cr();
2421 }
2422 
2423 void CodeHeapState::print_blobType_single(outputStream* out, u2 /* blobType */ type) {
2424   out->print("%c", blobTypeChar[type]);
2425 }
2426 
2427 void CodeHeapState::print_count_single(outputStream* out, unsigned short count) {
2428   if (count >= 16)    out->print("*");
2429   else if (count > 0) out->print("%1.1x", count);
2430   else                out->print(" ");
2431 }
2432 
2433 void CodeHeapState::print_space_single(outputStream* out, unsigned short space) {
2434   size_t  space_in_bytes = ((unsigned int)space)<<log2_seg_size;
2435   char    fraction       = (space == 0) ? ' ' : (space_in_bytes >= granule_size-1) ? '*' : char('0'+10*space_in_bytes/granule_size);
2436   out->print("%c", fraction);
2437 }
2438 
2439 void CodeHeapState::print_age_single(outputStream* out, unsigned int age) {
2440   unsigned int indicator = 0;
2441   unsigned int age_range = 256;
2442   if (age > 0) {
2443     while ((age_range > 0) && (latest_compilation_id-age > latest_compilation_id/age_range)) {
2444       age_range /= 2;
2445       indicator += 1;
2446     }
2447     out->print("%c", char('0'+indicator));
2448   } else {
2449     out->print(" ");
2450   }
2451 }
2452 
2453 void CodeHeapState::print_line_delim(outputStream* out, outputStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2454   if (ix % gpl == 0) {
2455     if (ix > 0) {
2456       ast->print("|");
2457     }
2458     ast->cr();
2459     assert(out == ast, "must use the same stream!");
2460 
2461     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2462     ast->fill_to(19);
2463     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2464   }
2465 }
2466 
2467 void CodeHeapState::print_line_delim(outputStream* out, bufferedStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2468   assert(out != ast, "must not use the same stream!");
2469   if (ix % gpl == 0) {
2470     if (ix > 0) {
2471       ast->print("|");
2472     }
2473     ast->cr();
2474 
2475     // can't use BUFFEREDSTREAM_FLUSH_IF("", 512) here.
2476     // can't use this expression. bufferedStream::capacity() does not exist.
2477     // if ((ast->capacity() - ast->size()) < 512) {
2478     // Assume instead that default bufferedStream capacity (4K) was used.
2479     if (ast->size() > 3*K) {
2480       ttyLocker ttyl;
2481       out->print("%s", ast->as_string());
2482       ast->reset();
2483     }
2484 
2485     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2486     ast->fill_to(19);
2487     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2488   }
2489 }
2490 
2491 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2492   if ((cb != NULL) && os::is_readable_pointer(cb)) {
2493     if (cb->is_runtime_stub())                return runtimeStub;
2494     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2495     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2496     if (cb->is_exception_stub())              return exceptionStub;
2497     if (cb->is_safepoint_stub())              return safepointStub;
2498     if (cb->is_adapter_blob())                return adapterBlob;
2499     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2500     if (cb->is_buffer_blob())                 return bufferBlob;
2501 
2502     //---<  access these fields only if we own the CodeCache_lock  >---
2503     // Should be ensured by caller. aggregate() amd print_names() do that.
2504     if (CodeCache_lock->owned_by_self()) {
2505       nmethod*  nm = cb->as_nmethod_or_null();
2506       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
2507         if (nm->is_not_installed()) return nMethod_inconstruction;
2508         if (nm->is_zombie())        return nMethod_dead;
2509         if (nm->is_unloaded())      return nMethod_unloaded;
2510         if (nm->is_in_use())        return nMethod_inuse;
2511         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2512         if (nm->is_alive())         return nMethod_alive;
2513         return nMethod_dead;
2514       }
2515     }
2516   }
2517   return noType;
2518 }
2519 
2520 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob, CodeBlob* prev_blob) {
2521   return (this_blob != NULL) && // a blob must have been found, obviously
2522          ((this_blob == prev_blob) || (prev_blob == NULL)) &&  // when re-checking, the same blob must have been found
2523          (this_blob->header_size() >= 0) &&
2524          (this_blob->relocation_size() >= 0) &&
2525          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2526          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin())) &&
2527          os::is_readable_pointer((address)(this_blob->relocation_begin())) &&
2528          os::is_readable_pointer(this_blob->content_begin());
2529 }