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