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 (ix_end   >= granules  ) {
 620         insane = true; ast->print_cr("Sanity check: end index (%d) out of bounds (" SIZE_FORMAT ")", ix_end, granules);
 621       }
 622       if (size     != heap->capacity()) {
 623         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);
 624       }
 625       if (ix_beg   >  ix_end    ) {
 626         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 627       }
 628       if (insane) {
 629         STRINGSTREAM_FLUSH("")
 630         continue;
 631       }
 632 
 633       if (h->free()) {
 634         nBlocks_free++;
 635         freeSpace    += hb_bytelen;
 636         if (hb_bytelen > maxFreeSize) {
 637           maxFreeSize   = hb_bytelen;
 638           maxFreeBlock  = h;
 639         }
 640       } else {
 641         update_SizeDistArray(out, hb_len);
 642         nBlocks_used++;
 643         usedSpace    += hb_bytelen;
 644         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 645         if (cb != NULL) {
 646           cbType = get_cbType(cb);
 647           if (cb->is_nmethod()) {
 648             compile_id = ((nmethod*)cb)->compile_id();
 649             comp_lvl   = (CompLevel)((nmethod*)cb)->comp_level();
 650             if (((nmethod*)cb)->is_compiled_by_c1()) {
 651               cType = c1;
 652             }
 653             if (((nmethod*)cb)->is_compiled_by_c2()) {
 654               cType = c2;
 655             }
 656             if (((nmethod*)cb)->is_compiled_by_jvmci()) {
 657               cType = jvmci;
 658             }
 659             switch (cbType) {
 660               case nMethod_inuse: { // only for executable methods!!!
 661                 // space for these cbs is accounted for later.
 662                 int temperature = ((nmethod*)cb)->hotness_counter();
 663                 hotnessAccumulator += temperature;
 664                 n_methods++;
 665                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 666                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 667                 break;
 668               }
 669               case nMethod_notused:
 670                 nBlocks_alive++;
 671                 nBlocks_disconn++;
 672                 aliveSpace     += hb_bytelen;
 673                 disconnSpace   += hb_bytelen;
 674                 break;
 675               case nMethod_notentrant:  // equivalent to nMethod_alive
 676                 nBlocks_alive++;
 677                 nBlocks_notentr++;
 678                 aliveSpace     += hb_bytelen;
 679                 notentrSpace   += hb_bytelen;
 680                 break;
 681               case nMethod_unloaded:
 682                 nBlocks_unloaded++;
 683                 unloadedSpace  += hb_bytelen;
 684                 break;
 685               case nMethod_dead:
 686                 nBlocks_dead++;
 687                 deadSpace      += hb_bytelen;
 688                 break;
 689               default:
 690                 break;
 691             }
 692           }
 693 
 694           //------------------------------------------
 695           //---<  register block in TopSizeArray  >---
 696           //------------------------------------------
 697           if (alloc_topSizeBlocks > 0) {
 698             if (used_topSizeBlocks == 0) {
 699               TopSizeArray[0].start    = h;
 700               TopSizeArray[0].len      = hb_len;
 701               TopSizeArray[0].index    = tsbStopper;
 702               TopSizeArray[0].compiler = cType;
 703               TopSizeArray[0].level    = comp_lvl;
 704               TopSizeArray[0].type     = cbType;
 705               currMax    = hb_len;
 706               currMin    = hb_len;
 707               currMin_ix = 0;
 708               used_topSizeBlocks++;
 709             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 710             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 711               //---<  all blocks in list are larger, but there is room left in array  >---
 712               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 713               TopSizeArray[used_topSizeBlocks].start    = h;
 714               TopSizeArray[used_topSizeBlocks].len      = hb_len;
 715               TopSizeArray[used_topSizeBlocks].index    = tsbStopper;
 716               TopSizeArray[used_topSizeBlocks].compiler = cType;
 717               TopSizeArray[used_topSizeBlocks].level    = comp_lvl;
 718               TopSizeArray[used_topSizeBlocks].type     = cbType;
 719               currMin    = hb_len;
 720               currMin_ix = used_topSizeBlocks;
 721               used_topSizeBlocks++;
 722             } else {
 723               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 724               //   We don't need to search the list if we know beforehand that the current block size is
 725               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 726               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 727                 if (currMax < hb_len) {
 728                   currMax = hb_len;
 729                 }
 730                 unsigned int i;
 731                 unsigned int prev_i  = tsbStopper;
 732                 unsigned int limit_i =  0;
 733                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 734                   if (limit_i++ >= alloc_topSizeBlocks) {
 735                     insane = true; break; // emergency exit
 736                   }
 737                   if (i >= used_topSizeBlocks)  {
 738                     insane = true; break; // emergency exit
 739                   }
 740                   total_iterations++;
 741                   if (TopSizeArray[i].len < hb_len) {
 742                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 743                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 744                       // old entry gets moved to the next free element of the array.
 745                       // That's necessary to keep the entry for the largest block at index 0.
 746                       // This move might cause the current minimum to be moved to another place
 747                       if (i == currMin_ix) {
 748                         assert(TopSizeArray[i].len == currMin, "sort error");
 749                         currMin_ix = used_topSizeBlocks;
 750                       }
 751                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 752                       TopSizeArray[i].start    = h;
 753                       TopSizeArray[i].len      = hb_len;
 754                       TopSizeArray[i].index    = used_topSizeBlocks;
 755                       TopSizeArray[i].compiler = cType;
 756                       TopSizeArray[i].level    = comp_lvl;
 757                       TopSizeArray[i].type     = cbType;
 758                       used_topSizeBlocks++;
 759                     } else { // no room for new entries, current block replaces entry for smallest block
 760                       //---<  Find last entry (entry for smallest remembered block)  >---
 761                       unsigned int      j  = i;
 762                       unsigned int prev_j  = tsbStopper;
 763                       unsigned int limit_j = 0;
 764                       while (TopSizeArray[j].index != tsbStopper) {
 765                         if (limit_j++ >= alloc_topSizeBlocks) {
 766                           insane = true; break; // emergency exit
 767                         }
 768                         if (j >= used_topSizeBlocks)  {
 769                           insane = true; break; // emergency exit
 770                         }
 771                         total_iterations++;
 772                         prev_j = j;
 773                         j      = TopSizeArray[j].index;
 774                       }
 775                       if (!insane) {
 776                         if (prev_j == tsbStopper) {
 777                           //---<  Above while loop did not iterate, we already are the min entry  >---
 778                           //---<  We have to just replace the smallest entry                      >---
 779                           currMin    = hb_len;
 780                           currMin_ix = j;
 781                           TopSizeArray[j].start    = h;
 782                           TopSizeArray[j].len      = hb_len;
 783                           TopSizeArray[j].index    = tsbStopper; // already set!!
 784                           TopSizeArray[j].compiler = cType;
 785                           TopSizeArray[j].level    = comp_lvl;
 786                           TopSizeArray[j].type     = cbType;
 787                         } else {
 788                           //---<  second-smallest entry is now smallest  >---
 789                           TopSizeArray[prev_j].index = tsbStopper;
 790                           currMin    = TopSizeArray[prev_j].len;
 791                           currMin_ix = prev_j;
 792                           //---<  smallest entry gets overwritten  >---
 793                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 794                           TopSizeArray[i].start    = h;
 795                           TopSizeArray[i].len      = hb_len;
 796                           TopSizeArray[i].index    = j;
 797                           TopSizeArray[i].compiler = cType;
 798                           TopSizeArray[i].level    = comp_lvl;
 799                           TopSizeArray[i].type     = cbType;
 800                         }
 801                       } // insane
 802                     }
 803                     break;
 804                   }
 805                   prev_i = i;
 806                 }
 807                 if (insane) {
 808                   // Note: regular analysis could probably continue by resetting "insane" flag.
 809                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 810                   discard_TopSizeArray(out);
 811                 }
 812               }
 813             }
 814           }
 815           //----------------------------------------------
 816           //---<  END register block in TopSizeArray  >---
 817           //----------------------------------------------
 818         } else {
 819           nBlocks_zomb++;
 820         }
 821 
 822         if (ix_beg == ix_end) {
 823           StatArray[ix_beg].type = cbType;
 824           switch (cbType) {
 825             case nMethod_inuse:
 826               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 827               if (comp_lvl < CompLevel_full_optimization) {
 828                 nBlocks_t1++;
 829                 t1Space   += hb_bytelen;
 830                 StatArray[ix_beg].t1_count++;
 831                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 832                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 833               } else {
 834                 nBlocks_t2++;
 835                 t2Space   += hb_bytelen;
 836                 StatArray[ix_beg].t2_count++;
 837                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 838                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 839               }
 840               StatArray[ix_beg].level     = comp_lvl;
 841               StatArray[ix_beg].compiler  = cType;
 842               break;
 843             case nMethod_alive:
 844               StatArray[ix_beg].tx_count++;
 845               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
 846               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 847               StatArray[ix_beg].level     = comp_lvl;
 848               StatArray[ix_beg].compiler  = cType;
 849               break;
 850             case nMethod_dead:
 851             case nMethod_unloaded:
 852               StatArray[ix_beg].dead_count++;
 853               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
 854               break;
 855             default:
 856               // must be a stub, if it's not a dead or alive nMethod
 857               nBlocks_stub++;
 858               stubSpace   += hb_bytelen;
 859               StatArray[ix_beg].stub_count++;
 860               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
 861               break;
 862           }
 863         } else {
 864           unsigned int beg_space = (unsigned int)(granule_size - ((char*)h - low_bound - ix_beg*granule_size));
 865           unsigned int end_space = (unsigned int)(hb_bytelen - beg_space - (ix_end-ix_beg-1)*granule_size);
 866           beg_space = beg_space>>log2_seg_size;  // store in units of _segment_size
 867           end_space = end_space>>log2_seg_size;  // store in units of _segment_size
 868           StatArray[ix_beg].type = cbType;
 869           StatArray[ix_end].type = cbType;
 870           switch (cbType) {
 871             case nMethod_inuse:
 872               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 873               if (comp_lvl < CompLevel_full_optimization) {
 874                 nBlocks_t1++;
 875                 t1Space   += hb_bytelen;
 876                 StatArray[ix_beg].t1_count++;
 877                 StatArray[ix_beg].t1_space += (unsigned short)beg_space;
 878                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 879 
 880                 StatArray[ix_end].t1_count++;
 881                 StatArray[ix_end].t1_space += (unsigned short)end_space;
 882                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
 883               } else {
 884                 nBlocks_t2++;
 885                 t2Space   += hb_bytelen;
 886                 StatArray[ix_beg].t2_count++;
 887                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
 888                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 889 
 890                 StatArray[ix_end].t2_count++;
 891                 StatArray[ix_end].t2_space += (unsigned short)end_space;
 892                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
 893               }
 894               StatArray[ix_beg].level     = comp_lvl;
 895               StatArray[ix_beg].compiler  = cType;
 896               StatArray[ix_end].level     = comp_lvl;
 897               StatArray[ix_end].compiler  = cType;
 898               break;
 899             case nMethod_alive:
 900               StatArray[ix_beg].tx_count++;
 901               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
 902               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 903 
 904               StatArray[ix_end].tx_count++;
 905               StatArray[ix_end].tx_space += (unsigned short)end_space;
 906               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
 907 
 908               StatArray[ix_beg].level     = comp_lvl;
 909               StatArray[ix_beg].compiler  = cType;
 910               StatArray[ix_end].level     = comp_lvl;
 911               StatArray[ix_end].compiler  = cType;
 912               break;
 913             case nMethod_dead:
 914             case nMethod_unloaded:
 915               StatArray[ix_beg].dead_count++;
 916               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
 917               StatArray[ix_end].dead_count++;
 918               StatArray[ix_end].dead_space += (unsigned short)end_space;
 919               break;
 920             default:
 921               // must be a stub, if it's not a dead or alive nMethod
 922               nBlocks_stub++;
 923               stubSpace   += hb_bytelen;
 924               StatArray[ix_beg].stub_count++;
 925               StatArray[ix_beg].stub_space += (unsigned short)beg_space;
 926               StatArray[ix_end].stub_count++;
 927               StatArray[ix_end].stub_space += (unsigned short)end_space;
 928               break;
 929           }
 930           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
 931             StatArray[ix].type = cbType;
 932             switch (cbType) {
 933               case nMethod_inuse:
 934                 if (comp_lvl < CompLevel_full_optimization) {
 935                   StatArray[ix].t1_count++;
 936                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
 937                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
 938                 } else {
 939                   StatArray[ix].t2_count++;
 940                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
 941                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
 942                 }
 943                 StatArray[ix].level     = comp_lvl;
 944                 StatArray[ix].compiler  = cType;
 945                 break;
 946               case nMethod_alive:
 947                 StatArray[ix].tx_count++;
 948                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
 949                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
 950                 StatArray[ix].level     = comp_lvl;
 951                 StatArray[ix].compiler  = cType;
 952                 break;
 953               case nMethod_dead:
 954               case nMethod_unloaded:
 955                 StatArray[ix].dead_count++;
 956                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
 957                 break;
 958               default:
 959                 // must be a stub, if it's not a dead or alive nMethod
 960                 StatArray[ix].stub_count++;
 961                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
 962                 break;
 963             }
 964           }
 965         }
 966       }
 967     }
 968     if (n_methods > 0) {
 969       avgTemp = hotnessAccumulator/n_methods;
 970     } else {
 971       avgTemp = 0;
 972     }
 973     done = true;
 974 
 975     if (!insane) {
 976       // There is a risk for this block (because it contains many print statements) to get
 977       // interspersed with print data from other threads. We take this risk intentionally.
 978       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
 979       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
 980       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);
 981       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);
 982       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);
 983       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);
 984       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);
 985       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);
 986       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);
 987       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);
 988       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);
 989       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);
 990       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
 991       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
 992       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
 993       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
 994       ast->cr();
 995 
 996       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
 997       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
 998       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
 999       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1000       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1001       ast->print_cr("min. hotness = %6d", minTemp);
1002       ast->print_cr("avg. hotness = %6d", avgTemp);
1003       ast->print_cr("max. hotness = %6d", maxTemp);
1004       STRINGSTREAM_FLUSH("\n")
1005 
1006       // This loop is intentionally printing directly to "out".
1007       out->print("Verifying collected data...");
1008       size_t granule_segs = granule_size>>log2_seg_size;
1009       for (unsigned int ix = 0; ix < granules; ix++) {
1010         if (StatArray[ix].t1_count   > granule_segs) {
1011           out->print_cr("t1_count[%d]   = %d", ix, StatArray[ix].t1_count);
1012         }
1013         if (StatArray[ix].t2_count   > granule_segs) {
1014           out->print_cr("t2_count[%d]   = %d", ix, StatArray[ix].t2_count);
1015         }
1016         if (StatArray[ix].stub_count > granule_segs) {
1017           out->print_cr("stub_count[%d] = %d", ix, StatArray[ix].stub_count);
1018         }
1019         if (StatArray[ix].dead_count > granule_segs) {
1020           out->print_cr("dead_count[%d] = %d", ix, StatArray[ix].dead_count);
1021         }
1022         if (StatArray[ix].t1_space   > granule_segs) {
1023           out->print_cr("t1_space[%d]   = %d", ix, StatArray[ix].t1_space);
1024         }
1025         if (StatArray[ix].t2_space   > granule_segs) {
1026           out->print_cr("t2_space[%d]   = %d", ix, StatArray[ix].t2_space);
1027         }
1028         if (StatArray[ix].stub_space > granule_segs) {
1029           out->print_cr("stub_space[%d] = %d", ix, StatArray[ix].stub_space);
1030         }
1031         if (StatArray[ix].dead_space > granule_segs) {
1032           out->print_cr("dead_space[%d] = %d", ix, StatArray[ix].dead_space);
1033         }
1034         //   this cast is awful! I need it because NT/Intel reports a signed/unsigned mismatch.
1035         if ((size_t)(StatArray[ix].t1_count+StatArray[ix].t2_count+StatArray[ix].stub_count+StatArray[ix].dead_count) > granule_segs) {
1036           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);
1037         }
1038         if ((size_t)(StatArray[ix].t1_space+StatArray[ix].t2_space+StatArray[ix].stub_space+StatArray[ix].dead_space) > granule_segs) {
1039           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);
1040         }
1041       }
1042 
1043       // This loop is intentionally printing directly to "out".
1044       if (used_topSizeBlocks > 0) {
1045         unsigned int j = 0;
1046         if (TopSizeArray[0].len != currMax) {
1047           out->print_cr("currMax(%d) differs from TopSizeArray[0].len(%d)", currMax, TopSizeArray[0].len);
1048         }
1049         for (unsigned int i = 0; (TopSizeArray[i].index != tsbStopper) && (j++ < alloc_topSizeBlocks); i = TopSizeArray[i].index) {
1050           if (TopSizeArray[i].len < TopSizeArray[TopSizeArray[i].index].len) {
1051             out->print_cr("sort error at index %d: %d !>= %d", i, TopSizeArray[i].len, TopSizeArray[TopSizeArray[i].index].len);
1052           }
1053         }
1054         if (j >= alloc_topSizeBlocks) {
1055           out->print_cr("Possible loop in TopSizeArray chaining!\n  allocBlocks = %d, usedBlocks = %d", alloc_topSizeBlocks, used_topSizeBlocks);
1056           for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1057             out->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1058           }
1059         }
1060       }
1061       out->print_cr("...done\n\n");
1062     } else {
1063       // insane heap state detected. Analysis data incomplete. Just throw it away.
1064       discard_StatArray(out);
1065       discard_TopSizeArray(out);
1066     }
1067   }
1068 
1069 
1070   done        = false;
1071   while (!done && (nBlocks_free > 0)) {
1072 
1073     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (free blocks) for segment ", heapName);
1074     ast->print_cr("   The aggregate step collects information about all free blocks in CodeHeap.\n"
1075                   "   Subsequent print functions create their output based on this snapshot.\n");
1076     ast->print_cr("   Free space in %s is distributed over %d free blocks.", heapName, nBlocks_free);
1077     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);
1078     STRINGSTREAM_FLUSH("\n")
1079 
1080     //----------------------------------------
1081     //--  Prepare the FreeArray of FreeBlks --
1082     //----------------------------------------
1083 
1084     //---< discard old array if size does not match  >---
1085     if (nBlocks_free != alloc_freeBlocks) {
1086       discard_FreeArray(out);
1087     }
1088 
1089     prepare_FreeArray(out, nBlocks_free, heapName);
1090     if (FreeArray == NULL) {
1091       done = true;
1092       continue;
1093     }
1094 
1095     //----------------------------------------
1096     //--  Collect all FreeBlks in FreeArray --
1097     //----------------------------------------
1098 
1099     unsigned int ix = 0;
1100     FreeBlock* cur  = heap->freelist();
1101 
1102     while (cur != NULL) {
1103       if (ix < alloc_freeBlocks) { // don't index out of bounds if _freelist has more blocks than anticipated
1104         FreeArray[ix].start = cur;
1105         FreeArray[ix].len   = (unsigned int)(cur->length()<<log2_seg_size);
1106         FreeArray[ix].index = ix;
1107       }
1108       cur  = cur->link();
1109       ix++;
1110     }
1111     if (ix != alloc_freeBlocks) {
1112       ast->print_cr("Free block count mismatch. Expected %d free blocks, but found %d.", alloc_freeBlocks, ix);
1113       ast->print_cr("I will update the counter and retry data collection");
1114       STRINGSTREAM_FLUSH("\n")
1115       nBlocks_free = ix;
1116       continue;
1117     }
1118     done = true;
1119   }
1120 
1121   if (!done || (nBlocks_free == 0)) {
1122     if (nBlocks_free == 0) {
1123       printBox(ast, '-', "no free blocks found in", heapName);
1124     } else if (!done) {
1125       ast->print_cr("Free block count mismatch could not be resolved.");
1126       ast->print_cr("Try to run \"aggregate\" function to update counters");
1127     }
1128     STRINGSTREAM_FLUSH("")
1129 
1130     //---< discard old array and update global values  >---
1131     discard_FreeArray(out);
1132     set_HeapStatGlobals(out, heapName);
1133     return;
1134   }
1135 
1136   //---<  calculate and fill remaining fields  >---
1137   if (FreeArray != NULL) {
1138     // This loop is intentionally printing directly to "out".
1139     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1140       size_t lenSum = 0;
1141       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1142       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1143         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1144         if ((cb != NULL) && !cb->is_nmethod()) {
1145           FreeArray[ix].stubs_in_gap = true;
1146         }
1147         FreeArray[ix].n_gapBlocks++;
1148         lenSum += h->length()<<log2_seg_size;
1149         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1150           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);
1151         }
1152       }
1153       if (lenSum != FreeArray[ix].gap) {
1154         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);
1155       }
1156     }
1157   }
1158   set_HeapStatGlobals(out, heapName);
1159 
1160   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);
1161   STRINGSTREAM_FLUSH("\n")
1162 }
1163 
1164 
1165 void CodeHeapState::print_usedSpace(outputStream* out, CodeHeap* heap) {
1166   if (!initialization_complete) {
1167     return;
1168   }
1169 
1170   const char* heapName   = get_heapName(heap);
1171   get_HeapStatGlobals(out, heapName);
1172 
1173   if ((StatArray == NULL) || (TopSizeArray == NULL) || (used_topSizeBlocks == 0)) {
1174     return;
1175   }
1176   STRINGSTREAM_DECL(ast, out)
1177 
1178   {
1179     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1180     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1181                   "      and other identifying information with the block size data.\n"
1182                   "\n"
1183                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1184                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1185                   "      is not continuously held, the displayed name might be wrong or no name\n"
1186                   "      might be found at all. The likelihood for that to happen increases\n"
1187                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1188     STRINGSTREAM_FLUSH_LOCKED("\n")
1189   }
1190 
1191   //----------------------------
1192   //--  Print Top Used Blocks --
1193   //----------------------------
1194   {
1195     char*     low_bound = heap->low_boundary();
1196 
1197     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1198     print_blobType_legend(ast);
1199 
1200     ast->fill_to(51);
1201     ast->print("%4s", "blob");
1202     ast->fill_to(56);
1203     ast->print("%9s", "compiler");
1204     ast->fill_to(66);
1205     ast->print_cr("%6s", "method");
1206     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1207     STRINGSTREAM_FLUSH_LOCKED("")
1208 
1209     //---<  print Top Ten Used Blocks  >---
1210     if (used_topSizeBlocks > 0) {
1211       unsigned int printed_topSizeBlocks = 0;
1212       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1213         printed_topSizeBlocks++;
1214         CodeBlob*   this_blob = (CodeBlob*)(heap->find_start(TopSizeArray[i].start));
1215         nmethod*           nm = NULL;
1216         const char* blob_name = "unnamed blob";
1217         if (this_blob != NULL) {
1218           blob_name = this_blob->name();
1219           nm        = this_blob->as_nmethod_or_null();
1220           //---<  blob address  >---
1221           ast->print("%p", this_blob);
1222           ast->fill_to(19);
1223           //---<  blob offset from CodeHeap begin  >---
1224           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1225           ast->fill_to(33);
1226         } else {
1227           //---<  block address  >---
1228           ast->print("%p", TopSizeArray[i].start);
1229           ast->fill_to(19);
1230           //---<  block offset from CodeHeap begin  >---
1231           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1232           ast->fill_to(33);
1233         }
1234 
1235 
1236         //---<  print size, name, and signature (for nMethods)  >---
1237         if ((nm != NULL) && (nm->method() != NULL)) {
1238           ResourceMark rm;
1239           //---<  nMethod size in hex  >---
1240           unsigned int total_size = nm->total_size();
1241           ast->print(PTR32_FORMAT, total_size);
1242           ast->print("(%4ldK)", total_size/K);
1243           ast->fill_to(51);
1244           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1245           //---<  compiler information  >---
1246           ast->fill_to(56);
1247           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1248           //---<  method temperature  >---
1249           ast->fill_to(67);
1250           ast->print("%5d", nm->hotness_counter());
1251           //---<  name and signature  >---
1252           ast->fill_to(67+6);
1253           if (nm->is_in_use())      {blob_name = nm->method()->name_and_sig_as_C_string(); }
1254           if (nm->is_not_entrant()) {blob_name = nm->method()->name_and_sig_as_C_string(); }
1255           if (nm->is_zombie())      {ast->print("%14s", " zombie method"); }
1256           ast->print("%s", blob_name);
1257         } else {
1258           //---<  block size in hex  >---
1259           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1260           ast->print("(%4ldK)", (TopSizeArray[i].len<<log2_seg_size)/K);
1261           //---<  no compiler information  >---
1262           ast->fill_to(56);
1263           //---<  name and signature  >---
1264           ast->fill_to(67+6);
1265           ast->print("%s", blob_name);
1266         }
1267         STRINGSTREAM_FLUSH_LOCKED("\n")
1268       }
1269       if (used_topSizeBlocks != printed_topSizeBlocks) {
1270         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1271         STRINGSTREAM_FLUSH("")
1272         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1273           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1274           STRINGSTREAM_FLUSH("")
1275         }
1276       }
1277       STRINGSTREAM_FLUSH_LOCKED("\n\n")
1278     }
1279   }
1280 
1281   //-----------------------------
1282   //--  Print Usage Histogram  --
1283   //-----------------------------
1284 
1285   if (SizeDistributionArray != NULL) {
1286     unsigned long total_count = 0;
1287     unsigned long total_size  = 0;
1288     const unsigned long pctFactor = 200;
1289 
1290     for (unsigned int i = 0; i < nSizeDistElements; i++) {
1291       total_count += SizeDistributionArray[i].count;
1292       total_size  += SizeDistributionArray[i].lenSum;
1293     }
1294 
1295     if ((total_count > 0) && (total_size > 0)) {
1296       printBox(ast, '-', "Block count histogram for ", heapName);
1297       ast->print_cr("Note: The histogram indicates how many blocks (as a percentage\n"
1298                     "      of all blocks) have a size in the given range.\n"
1299                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1300       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1301       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1302       STRINGSTREAM_FLUSH_LOCKED("")
1303 
1304       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1305       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1306         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1307           ast->print("[%5d ..%5d ): "
1308                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1309                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1310                     );
1311         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1312           ast->print("[%5ldK..%5ldK): "
1313                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1314                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1315                     );
1316         } else {
1317           ast->print("[%5ldM..%5ldM): "
1318                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1319                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1320                     );
1321         }
1322         ast->print(" %8d | %8d |",
1323                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1324                    SizeDistributionArray[i].count);
1325 
1326         unsigned int percent = pctFactor*SizeDistributionArray[i].count/total_count;
1327         for (unsigned int j = 1; j <= percent; j++) {
1328           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1329         }
1330         ast->cr();
1331       }
1332       ast->print_cr("----------------------------+----------+\n\n");
1333       STRINGSTREAM_FLUSH_LOCKED("\n")
1334 
1335       printBox(ast, '-', "Contribution per size range to total size for ", heapName);
1336       ast->print_cr("Note: The histogram indicates how much space (as a percentage of all\n"
1337                     "      occupied space) is used by the blocks in the given size range.\n"
1338                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1339       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1340       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1341       STRINGSTREAM_FLUSH_LOCKED("")
1342 
1343       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1344       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1345         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1346           ast->print("[%5d ..%5d ): "
1347                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1348                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1349                     );
1350         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1351           ast->print("[%5ldK..%5ldK): "
1352                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1353                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1354                     );
1355         } else {
1356           ast->print("[%5ldM..%5ldM): "
1357                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1358                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1359                     );
1360         }
1361         ast->print(" %8d | %8d |",
1362                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1363                    SizeDistributionArray[i].count);
1364 
1365         unsigned int percent = pctFactor*(unsigned long)SizeDistributionArray[i].lenSum/total_size;
1366         for (unsigned int j = 1; j <= percent; j++) {
1367           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1368         }
1369         ast->cr();
1370       }
1371       ast->print_cr("----------------------------+----------+");
1372       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1373     }
1374   }
1375 }
1376 
1377 
1378 void CodeHeapState::print_freeSpace(outputStream* out, CodeHeap* heap) {
1379   if (!initialization_complete) {
1380     return;
1381   }
1382 
1383   const char* heapName   = get_heapName(heap);
1384   get_HeapStatGlobals(out, heapName);
1385 
1386   if ((StatArray == NULL) || (FreeArray == NULL) || (alloc_granules == 0)) {
1387     return;
1388   }
1389   STRINGSTREAM_DECL(ast, out)
1390 
1391   {
1392     printBox(ast, '=', "F R E E   S P A C E   S T A T I S T I C S   for ", heapName);
1393     ast->print_cr("Note: in this context, a gap is the occupied space between two free blocks.\n"
1394                   "      Those gaps are of interest if there is a chance that they become\n"
1395                   "      unoccupied, e.g. by class unloading. Then, the two adjacent free\n"
1396                   "      blocks, together with the now unoccupied space, form a new, large\n"
1397                   "      free block.");
1398     STRINGSTREAM_FLUSH_LOCKED("\n")
1399   }
1400 
1401   {
1402     printBox(ast, '-', "List of all Free Blocks in ", heapName);
1403     STRINGSTREAM_FLUSH_LOCKED("")
1404 
1405     unsigned int ix = 0;
1406     for (ix = 0; ix < alloc_freeBlocks-1; ix++) {
1407       ast->print("%p: Len[%4d] = " HEX32_FORMAT ",", FreeArray[ix].start, ix, FreeArray[ix].len);
1408       ast->fill_to(38);
1409       ast->print("Gap[%4d..%4d]: " HEX32_FORMAT " bytes,", ix, ix+1, FreeArray[ix].gap);
1410       ast->fill_to(71);
1411       ast->print("block count: %6d", FreeArray[ix].n_gapBlocks);
1412       if (FreeArray[ix].stubs_in_gap) {
1413         ast->print(" !! permanent gap, contains stubs and/or blobs !!");
1414       }
1415       STRINGSTREAM_FLUSH_LOCKED("\n")
1416     }
1417     ast->print_cr("%p: Len[%4d] = " HEX32_FORMAT, FreeArray[ix].start, ix, FreeArray[ix].len);
1418     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1419   }
1420 
1421 
1422   //-----------------------------------------
1423   //--  Find and Print Top Ten Free Blocks --
1424   //-----------------------------------------
1425 
1426   //---<  find Top Ten Free Blocks  >---
1427   const unsigned int nTop = 10;
1428   unsigned int  currMax10 = 0;
1429   struct FreeBlk* FreeTopTen[nTop];
1430   memset(FreeTopTen, 0, sizeof(FreeTopTen));
1431 
1432   for (unsigned int ix = 0; ix < alloc_freeBlocks; ix++) {
1433     if (FreeArray[ix].len > currMax10) {  // larger than the ten largest found so far
1434       unsigned int currSize = FreeArray[ix].len;
1435 
1436       unsigned int iy;
1437       for (iy = 0; iy < nTop && FreeTopTen[iy] != NULL; iy++) {
1438         if (FreeTopTen[iy]->len < currSize) {
1439           for (unsigned int iz = nTop-1; iz > iy; iz--) { // make room to insert new free block
1440             FreeTopTen[iz] = FreeTopTen[iz-1];
1441           }
1442           FreeTopTen[iy] = &FreeArray[ix];        // insert new free block
1443           if (FreeTopTen[nTop-1] != NULL) {
1444             currMax10 = FreeTopTen[nTop-1]->len;
1445           }
1446           break; // done with this, check next free block
1447         }
1448       }
1449       if (iy >= nTop) {
1450         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1451                       currSize, currMax10);
1452         continue;
1453       }
1454       if (FreeTopTen[iy] == NULL) {
1455         FreeTopTen[iy] = &FreeArray[ix];
1456         if (iy == (nTop-1)) {
1457           currMax10 = currSize;
1458         }
1459       }
1460     }
1461   }
1462   STRINGSTREAM_FLUSH_LOCKED("")
1463 
1464   {
1465     printBox(ast, '-', "Top Ten Free Blocks in ", heapName);
1466 
1467     //---<  print Top Ten Free Blocks  >---
1468     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTen[iy] != NULL); iy++) {
1469       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTen[iy]->index, FreeTopTen[iy]->len);
1470       ast->fill_to(39);
1471       if (FreeTopTen[iy]->index == (alloc_freeBlocks-1)) {
1472         ast->print("last free block in list.");
1473       } else {
1474         ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTen[iy]->gap);
1475         ast->fill_to(63);
1476         ast->print("#blocks (in gap) %d", FreeTopTen[iy]->n_gapBlocks);
1477       }
1478       ast->cr();
1479     }
1480     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1481   }
1482 
1483 
1484   //--------------------------------------------------------
1485   //--  Find and Print Top Ten Free-Occupied-Free Triples --
1486   //--------------------------------------------------------
1487 
1488   //---<  find and print Top Ten Triples (Free-Occupied-Free)  >---
1489   currMax10 = 0;
1490   struct FreeBlk  *FreeTopTenTriple[nTop];
1491   memset(FreeTopTenTriple, 0, sizeof(FreeTopTenTriple));
1492 
1493   for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1494     // If there are stubs in the gap, this gap will never become completely free.
1495     // The triple will thus never merge to one free block.
1496     unsigned int lenTriple  = FreeArray[ix].len + (FreeArray[ix].stubs_in_gap ? 0 : FreeArray[ix].gap + FreeArray[ix+1].len);
1497     FreeArray[ix].len = lenTriple;
1498     if (lenTriple > currMax10) {  // larger than the ten largest found so far
1499 
1500       unsigned int iy;
1501       for (iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1502         if (FreeTopTenTriple[iy]->len < lenTriple) {
1503           for (unsigned int iz = nTop-1; iz > iy; iz--) {
1504             FreeTopTenTriple[iz] = FreeTopTenTriple[iz-1];
1505           }
1506           FreeTopTenTriple[iy] = &FreeArray[ix];
1507           if (FreeTopTenTriple[nTop-1] != NULL) {
1508             currMax10 = FreeTopTenTriple[nTop-1]->len;
1509           }
1510           break;
1511         }
1512       }
1513       if (iy == nTop) {
1514         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1515                       lenTriple, currMax10);
1516         continue;
1517       }
1518       if (FreeTopTenTriple[iy] == NULL) {
1519         FreeTopTenTriple[iy] = &FreeArray[ix];
1520         if (iy == (nTop-1)) {
1521           currMax10 = lenTriple;
1522         }
1523       }
1524     }
1525   }
1526   STRINGSTREAM_FLUSH_LOCKED("")
1527 
1528   {
1529     printBox(ast, '-', "Top Ten Free-Occupied-Free Triples in ", heapName);
1530     ast->print_cr("  Use this information to judge how likely it is that a large(r) free block\n"
1531                   "  might get created by code cache sweeping.\n"
1532                   "  If all the occupied blocks can be swept, the three free blocks will be\n"
1533                   "  merged into one (much larger) free block. That would reduce free space\n"
1534                   "  fragmentation.\n");
1535 
1536     //---<  print Top Ten Free-Occupied-Free Triples  >---
1537     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1538       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTenTriple[iy]->index, FreeTopTenTriple[iy]->len);
1539       ast->fill_to(39);
1540       ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTenTriple[iy]->gap);
1541       ast->fill_to(63);
1542       ast->print("#blocks (in gap) %d", FreeTopTenTriple[iy]->n_gapBlocks);
1543       ast->cr();
1544     }
1545     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1546   }
1547 }
1548 
1549 
1550 void CodeHeapState::print_count(outputStream* out, CodeHeap* heap) {
1551   if (!initialization_complete) {
1552     return;
1553   }
1554 
1555   const char* heapName   = get_heapName(heap);
1556   get_HeapStatGlobals(out, heapName);
1557 
1558   if ((StatArray == NULL) || (alloc_granules == 0)) {
1559     return;
1560   }
1561   STRINGSTREAM_DECL(ast, out)
1562 
1563   unsigned int granules_per_line = 32;
1564   char*        low_bound         = heap->low_boundary();
1565 
1566   {
1567     printBox(ast, '=', "B L O C K   C O U N T S   for ", heapName);
1568     ast->print_cr("  Each granule contains an individual number of heap blocks. Large blocks\n"
1569                   "  may span multiple granules and are counted for each granule they touch.\n");
1570     if (segment_granules) {
1571       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1572                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1573                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1574                     "  Occupied granules show their BlobType character, see legend.\n");
1575       print_blobType_legend(ast);
1576     }
1577     STRINGSTREAM_FLUSH_LOCKED("")
1578   }
1579 
1580   {
1581     if (segment_granules) {
1582       printBox(ast, '-', "Total (all types) count for granule size == segment size", NULL);
1583       STRINGSTREAM_FLUSH_LOCKED("")
1584 
1585       granules_per_line = 128;
1586       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1587         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1588         print_blobType_single(ast, StatArray[ix].type);
1589       }
1590     } else {
1591       printBox(ast, '-', "Total (all tiers) count, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1592       STRINGSTREAM_FLUSH_LOCKED("")
1593 
1594       granules_per_line = 128;
1595       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1596         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1597         unsigned int count = StatArray[ix].t1_count   + StatArray[ix].t2_count   + StatArray[ix].tx_count
1598                            + StatArray[ix].stub_count + StatArray[ix].dead_count;
1599         print_count_single(ast, count);
1600       }
1601     }
1602     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1603   }
1604 
1605   {
1606     if (nBlocks_t1 > 0) {
1607       printBox(ast, '-', "Tier1 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1608       STRINGSTREAM_FLUSH_LOCKED("")
1609 
1610       granules_per_line = 128;
1611       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1612         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1613         if (segment_granules && StatArray[ix].t1_count > 0) {
1614           print_blobType_single(ast, StatArray[ix].type);
1615         } else {
1616           print_count_single(ast, StatArray[ix].t1_count);
1617         }
1618       }
1619       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1620     } else {
1621       ast->print("No Tier1 nMethods found in CodeHeap.");
1622       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1623     }
1624   }
1625 
1626   {
1627     if (nBlocks_t2 > 0) {
1628       printBox(ast, '-', "Tier2 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1629       STRINGSTREAM_FLUSH_LOCKED("")
1630 
1631       granules_per_line = 128;
1632       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1633         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1634         if (segment_granules && StatArray[ix].t2_count > 0) {
1635           print_blobType_single(ast, StatArray[ix].type);
1636         } else {
1637           print_count_single(ast, StatArray[ix].t2_count);
1638         }
1639       }
1640       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1641     } else {
1642       ast->print("No Tier2 nMethods found in CodeHeap.");
1643       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1644     }
1645   }
1646 
1647   {
1648     if (nBlocks_alive > 0) {
1649       printBox(ast, '-', "not_used/not_entrant nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1650       STRINGSTREAM_FLUSH_LOCKED("")
1651 
1652       granules_per_line = 128;
1653       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1654         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1655         if (segment_granules && StatArray[ix].tx_count > 0) {
1656           print_blobType_single(ast, StatArray[ix].type);
1657         } else {
1658           print_count_single(ast, StatArray[ix].tx_count);
1659         }
1660       }
1661       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1662     } else {
1663       ast->print("No not_used/not_entrant nMethods found in CodeHeap.");
1664       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1665     }
1666   }
1667 
1668   {
1669     if (nBlocks_stub > 0) {
1670       printBox(ast, '-', "Stub & Blob count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1671       STRINGSTREAM_FLUSH_LOCKED("")
1672 
1673       granules_per_line = 128;
1674       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1675         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1676         if (segment_granules && StatArray[ix].stub_count > 0) {
1677           print_blobType_single(ast, StatArray[ix].type);
1678         } else {
1679           print_count_single(ast, StatArray[ix].stub_count);
1680         }
1681       }
1682       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1683     } else {
1684       ast->print("No Stubs and Blobs found in CodeHeap.");
1685       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1686     }
1687   }
1688 
1689   {
1690     if (nBlocks_dead > 0) {
1691       printBox(ast, '-', "Dead nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1692       STRINGSTREAM_FLUSH_LOCKED("")
1693 
1694       granules_per_line = 128;
1695       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1696         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1697         if (segment_granules && StatArray[ix].dead_count > 0) {
1698           print_blobType_single(ast, StatArray[ix].type);
1699         } else {
1700           print_count_single(ast, StatArray[ix].dead_count);
1701         }
1702       }
1703       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1704     } else {
1705       ast->print("No dead nMethods found in CodeHeap.");
1706       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1707     }
1708   }
1709 
1710   {
1711     if (!segment_granules) { // Prevent totally redundant printouts
1712       printBox(ast, '-', "Count by tier (combined, no dead blocks): <#t1>:<#t2>:<#s>, 0x0..0xf. '*' indicates >= 16 blocks", NULL);
1713       STRINGSTREAM_FLUSH_LOCKED("")
1714 
1715       granules_per_line = 24;
1716       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1717         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1718 
1719         print_count_single(ast, StatArray[ix].t1_count);
1720         ast->print(":");
1721         print_count_single(ast, StatArray[ix].t2_count);
1722         ast->print(":");
1723         if (segment_granules && StatArray[ix].stub_count > 0) {
1724           print_blobType_single(ast, StatArray[ix].type);
1725         } else {
1726           print_count_single(ast, StatArray[ix].stub_count);
1727         }
1728         ast->print(" ");
1729       }
1730       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1731     }
1732   }
1733 }
1734 
1735 
1736 void CodeHeapState::print_space(outputStream* out, CodeHeap* heap) {
1737   if (!initialization_complete) {
1738     return;
1739   }
1740 
1741   const char* heapName   = get_heapName(heap);
1742   get_HeapStatGlobals(out, heapName);
1743 
1744   if ((StatArray == NULL) || (alloc_granules == 0)) {
1745     return;
1746   }
1747   STRINGSTREAM_DECL(ast, out)
1748 
1749   unsigned int granules_per_line = 32;
1750   char*        low_bound         = heap->low_boundary();
1751 
1752   {
1753     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);
1754     ast->print_cr("  The heap space covered by one granule is occupied to a various extend.\n"
1755                   "  The granule occupancy is displayed by one decimal digit per granule.\n");
1756     if (segment_granules) {
1757       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1758                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1759                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1760                     "  Occupied granules show their BlobType character, see legend.\n");
1761       print_blobType_legend(ast);
1762     } else {
1763       ast->print_cr("  These digits represent a fill percentage range (see legend).\n");
1764       print_space_legend(ast);
1765     }
1766     STRINGSTREAM_FLUSH_LOCKED("")
1767   }
1768 
1769   {
1770     if (segment_granules) {
1771       printBox(ast, '-', "Total (all types) space consumption for granule size == segment size", NULL);
1772       STRINGSTREAM_FLUSH_LOCKED("")
1773 
1774       granules_per_line = 128;
1775       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1776         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1777         print_blobType_single(ast, StatArray[ix].type);
1778       }
1779     } else {
1780       printBox(ast, '-', "Total (all types) space consumption. ' ' indicates empty, '*' indicates full.", NULL);
1781       STRINGSTREAM_FLUSH_LOCKED("")
1782 
1783       granules_per_line = 128;
1784       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1785         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1786         unsigned int space    = StatArray[ix].t1_space   + StatArray[ix].t2_space  + StatArray[ix].tx_space
1787                               + StatArray[ix].stub_space + StatArray[ix].dead_space;
1788         print_space_single(ast, space);
1789       }
1790     }
1791     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1792   }
1793 
1794   {
1795     if (nBlocks_t1 > 0) {
1796       printBox(ast, '-', "Tier1 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1797       STRINGSTREAM_FLUSH_LOCKED("")
1798 
1799       granules_per_line = 128;
1800       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1801         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1802         if (segment_granules && StatArray[ix].t1_space > 0) {
1803           print_blobType_single(ast, StatArray[ix].type);
1804         } else {
1805           print_space_single(ast, StatArray[ix].t1_space);
1806         }
1807       }
1808       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1809     } else {
1810       ast->print("No Tier1 nMethods found in CodeHeap.");
1811       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1812     }
1813   }
1814 
1815   {
1816     if (nBlocks_t2 > 0) {
1817       printBox(ast, '-', "Tier2 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1818       STRINGSTREAM_FLUSH_LOCKED("")
1819 
1820       granules_per_line = 128;
1821       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1822         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1823         if (segment_granules && StatArray[ix].t2_space > 0) {
1824           print_blobType_single(ast, StatArray[ix].type);
1825         } else {
1826           print_space_single(ast, StatArray[ix].t2_space);
1827         }
1828       }
1829       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1830     } else {
1831       ast->print("No Tier2 nMethods found in CodeHeap.");
1832       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1833     }
1834   }
1835 
1836   {
1837     if (nBlocks_alive > 0) {
1838       printBox(ast, '-', "not_used/not_entrant space consumption. ' ' indicates empty, '*' indicates full", NULL);
1839 
1840       granules_per_line = 128;
1841       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1842         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1843         if (segment_granules && StatArray[ix].tx_space > 0) {
1844           print_blobType_single(ast, StatArray[ix].type);
1845         } else {
1846           print_space_single(ast, StatArray[ix].tx_space);
1847         }
1848       }
1849       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1850     } else {
1851       ast->print("No Tier2 nMethods found in CodeHeap.");
1852       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1853     }
1854   }
1855 
1856   {
1857     if (nBlocks_stub > 0) {
1858       printBox(ast, '-', "Stub and Blob space consumption. ' ' indicates empty, '*' indicates full", NULL);
1859       STRINGSTREAM_FLUSH_LOCKED("")
1860 
1861       granules_per_line = 128;
1862       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1863         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1864         if (segment_granules && StatArray[ix].stub_space > 0) {
1865           print_blobType_single(ast, StatArray[ix].type);
1866         } else {
1867           print_space_single(ast, StatArray[ix].stub_space);
1868         }
1869       }
1870       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1871     } else {
1872       ast->print("No Stubs and Blobs found in CodeHeap.");
1873       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1874     }
1875   }
1876 
1877   {
1878     if (nBlocks_dead > 0) {
1879       printBox(ast, '-', "Dead space consumption. ' ' indicates empty, '*' indicates full", NULL);
1880       STRINGSTREAM_FLUSH_LOCKED("")
1881 
1882       granules_per_line = 128;
1883       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1884         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1885         print_space_single(ast, StatArray[ix].dead_space);
1886       }
1887       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1888     } else {
1889       ast->print("No dead nMethods found in CodeHeap.");
1890       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1891     }
1892   }
1893 
1894   {
1895     if (!segment_granules) { // Prevent totally redundant printouts
1896       printBox(ast, '-', "Space consumption by tier (combined): <t1%>:<t2%>:<s%>. ' ' indicates empty, '*' indicates full", NULL);
1897       STRINGSTREAM_FLUSH_LOCKED("")
1898 
1899       granules_per_line = 24;
1900       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1901         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1902 
1903         if (segment_granules && StatArray[ix].t1_space > 0) {
1904           print_blobType_single(ast, StatArray[ix].type);
1905         } else {
1906           print_space_single(ast, StatArray[ix].t1_space);
1907         }
1908         ast->print(":");
1909         if (segment_granules && StatArray[ix].t2_space > 0) {
1910           print_blobType_single(ast, StatArray[ix].type);
1911         } else {
1912           print_space_single(ast, StatArray[ix].t2_space);
1913         }
1914         ast->print(":");
1915         if (segment_granules && StatArray[ix].stub_space > 0) {
1916           print_blobType_single(ast, StatArray[ix].type);
1917         } else {
1918           print_space_single(ast, StatArray[ix].stub_space);
1919         }
1920         ast->print(" ");
1921       }
1922       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1923     }
1924   }
1925 }
1926 
1927 void CodeHeapState::print_age(outputStream* out, CodeHeap* heap) {
1928   if (!initialization_complete) {
1929     return;
1930   }
1931 
1932   const char* heapName   = get_heapName(heap);
1933   get_HeapStatGlobals(out, heapName);
1934 
1935   if ((StatArray == NULL) || (alloc_granules == 0)) {
1936     return;
1937   }
1938   STRINGSTREAM_DECL(ast, out)
1939 
1940   unsigned int granules_per_line = 32;
1941   char*        low_bound         = heap->low_boundary();
1942 
1943   {
1944     printBox(ast, '=', "M E T H O D   A G E   by CompileID for ", heapName);
1945     ast->print_cr("  The age of a compiled method in the CodeHeap is not available as a\n"
1946                   "  time stamp. Instead, a relative age is deducted from the method's compilation ID.\n"
1947                   "  Age information is available for tier1 and tier2 methods only. There is no\n"
1948                   "  age information for stubs and blobs, because they have no compilation ID assigned.\n"
1949                   "  Information for the youngest method (highest ID) in the granule is printed.\n"
1950                   "  Refer to the legend to learn how method age is mapped to the displayed digit.");
1951     print_age_legend(ast);
1952     STRINGSTREAM_FLUSH_LOCKED("")
1953   }
1954 
1955   {
1956     printBox(ast, '-', "Age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
1957     STRINGSTREAM_FLUSH_LOCKED("")
1958 
1959     granules_per_line = 128;
1960     for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1961       print_line_delim(out, ast, low_bound, ix, granules_per_line);
1962       unsigned int age1      = StatArray[ix].t1_age;
1963       unsigned int age2      = StatArray[ix].t2_age;
1964       unsigned int agex      = StatArray[ix].tx_age;
1965       unsigned int age       = age1 > age2 ? age1 : age2;
1966       age       = age > agex ? age : agex;
1967       print_age_single(ast, age);
1968     }
1969     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1970   }
1971 
1972   {
1973     if (nBlocks_t1 > 0) {
1974       printBox(ast, '-', "Tier1 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
1975       STRINGSTREAM_FLUSH_LOCKED("")
1976 
1977       granules_per_line = 128;
1978       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1979         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1980         print_age_single(ast, StatArray[ix].t1_age);
1981       }
1982       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1983     } else {
1984       ast->print("No Tier1 nMethods found in CodeHeap.");
1985       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1986     }
1987   }
1988 
1989   {
1990     if (nBlocks_t2 > 0) {
1991       printBox(ast, '-', "Tier2 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
1992       STRINGSTREAM_FLUSH_LOCKED("")
1993 
1994       granules_per_line = 128;
1995       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1996         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1997         print_age_single(ast, StatArray[ix].t2_age);
1998       }
1999       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2000     } else {
2001       ast->print("No Tier2 nMethods found in CodeHeap.");
2002       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
2003     }
2004   }
2005 
2006   {
2007     if (nBlocks_alive > 0) {
2008       printBox(ast, '-', "not_used/not_entrant age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2009       STRINGSTREAM_FLUSH_LOCKED("")
2010 
2011       granules_per_line = 128;
2012       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2013         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2014         print_age_single(ast, StatArray[ix].tx_age);
2015       }
2016       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2017     } else {
2018       ast->print("No Tier2 nMethods found in CodeHeap.");
2019       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
2020     }
2021   }
2022 
2023   {
2024     if (!segment_granules) { // Prevent totally redundant printouts
2025       printBox(ast, '-', "age distribution by tier <a1>:<a2>. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2026       STRINGSTREAM_FLUSH_LOCKED("")
2027 
2028       granules_per_line = 32;
2029       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2030         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2031         print_age_single(ast, StatArray[ix].t1_age);
2032         ast->print(":");
2033         print_age_single(ast, StatArray[ix].t2_age);
2034         ast->print(" ");
2035       }
2036       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2037     }
2038   }
2039 }
2040 
2041 
2042 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2043   if (!initialization_complete) {
2044     return;
2045   }
2046 
2047   const char* heapName   = get_heapName(heap);
2048   get_HeapStatGlobals(out, heapName);
2049 
2050   if ((StatArray == NULL) || (alloc_granules == 0)) {
2051     return;
2052   }
2053   STRINGSTREAM_DECL(ast, out)
2054 
2055   unsigned int granules_per_line  = 128;
2056   char*        low_bound          = heap->low_boundary();
2057   CodeBlob*    last_blob          = NULL;
2058   bool         name_in_addr_range = true;
2059 
2060   //---<  print at least 128K per block  >---
2061   if (granules_per_line*granule_size < 128*K) {
2062     granules_per_line = (unsigned int)((128*K)/granule_size);
2063   }
2064 
2065   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2066   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2067                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2068                 "  is not continuously held, the displayed name might be wrong or no name\n"
2069                 "  might be found at all. The likelihood for that to happen increases\n"
2070                 "  over time passed between analysis and print step.\n");
2071   STRINGSTREAM_FLUSH_LOCKED("")
2072 
2073   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2074     //---<  print a new blob on a new line  >---
2075     if (ix%granules_per_line == 0) {
2076       if (!name_in_addr_range) {
2077         ast->print_cr("No methods, blobs, or stubs found in this address range");
2078       }
2079       name_in_addr_range = false;
2080 
2081       ast->cr();
2082       ast->print_cr("--------------------------------------------------------------------");
2083       ast->print_cr("Address range [%p,%p), " SIZE_FORMAT "k", low_bound+ix*granule_size, low_bound+(ix+granules_per_line)*granule_size, granules_per_line*granule_size/(size_t)K);
2084       ast->print_cr("--------------------------------------------------------------------");
2085       STRINGSTREAM_FLUSH_LOCKED("")
2086     }
2087     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2088       CodeBlob* this_blob = (CodeBlob *)(heap->find_start(low_bound+ix*granule_size+is));
2089       if ((this_blob != NULL) && (this_blob != last_blob)) {
2090         if (!name_in_addr_range) {
2091           name_in_addr_range = true;
2092           ast->fill_to(51);
2093           ast->print("%9s", "compiler");
2094           ast->fill_to(61);
2095           ast->print_cr("%6s", "method");
2096           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2097         }
2098 
2099         //---<  Print blobTypeName as recorded during analysis  >---
2100         ast->print("%p", this_blob);
2101         ast->fill_to(19);
2102         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2103         ast->fill_to(33);
2104 
2105         //---<  print size, name, and signature (for nMethods)  >---
2106         const char *blob_name = this_blob->name();
2107         nmethod*           nm = this_blob->as_nmethod_or_null();
2108         blobType       cbType = noType;
2109         if (segment_granules) {
2110           cbType = (blobType)StatArray[ix].type;
2111         } else {
2112           cbType = get_cbType(this_blob);
2113         }
2114         if ((nm != NULL) && (nm->method() != NULL)) {
2115           ResourceMark rm;
2116           //---<  nMethod size in hex  >---
2117           unsigned int total_size = nm->total_size();
2118           ast->print(PTR32_FORMAT, total_size);
2119           ast->print("(%4ldK)", total_size/K);
2120           //---<  compiler information  >---
2121           ast->fill_to(51);
2122           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2123           //---<  method temperature  >---
2124           ast->fill_to(62);
2125           ast->print("%5d", nm->hotness_counter());
2126           //---<  name and signature  >---
2127           ast->fill_to(62+6);
2128           ast->print("%s", blobTypeName[cbType]);
2129           ast->fill_to(82+6);
2130           if (nm->is_in_use()) {
2131             blob_name = nm->method()->name_and_sig_as_C_string();
2132           }
2133           if (nm->is_not_entrant()) {
2134             blob_name = nm->method()->name_and_sig_as_C_string();
2135           }
2136           if (nm->is_zombie()) {
2137             ast->print("%14s", " zombie method");
2138           }
2139           ast->print("%s", blob_name);
2140         } else {
2141           ast->fill_to(62+6);
2142           ast->print("%s", blobTypeName[cbType]);
2143           ast->fill_to(82+6);
2144           ast->print("%s", blob_name);
2145         }
2146         STRINGSTREAM_FLUSH_LOCKED("\n")
2147         last_blob          = this_blob;
2148       }
2149     }
2150   }
2151   STRINGSTREAM_FLUSH_LOCKED("\n\n")
2152 }
2153 
2154 
2155 void CodeHeapState::printBox(outputStream* ast, const char border, const char* text1, const char* text2) {
2156   unsigned int lineLen = 1 + 2 + 2 + 1;
2157   char edge, frame;
2158 
2159   if (text1 != NULL) {
2160     lineLen += (unsigned int)strlen(text1); // text1 is much shorter than MAX_INT chars.
2161   }
2162   if (text2 != NULL) {
2163     lineLen += (unsigned int)strlen(text2); // text2 is much shorter than MAX_INT chars.
2164   }
2165   if (border == '-') {
2166     edge  = '+';
2167     frame = '|';
2168   } else {
2169     edge  = border;
2170     frame = border;
2171   }
2172 
2173   ast->print("%c", edge);
2174   for (unsigned int i = 0; i < lineLen-2; i++) {
2175     ast->print("%c", border);
2176   }
2177   ast->print_cr("%c", edge);
2178 
2179   ast->print("%c  ", frame);
2180   if (text1 != NULL) {
2181     ast->print("%s", text1);
2182   }
2183   if (text2 != NULL) {
2184     ast->print("%s", text2);
2185   }
2186   ast->print_cr("  %c", frame);
2187 
2188   ast->print("%c", edge);
2189   for (unsigned int i = 0; i < lineLen-2; i++) {
2190     ast->print("%c", border);
2191   }
2192   ast->print_cr("%c", edge);
2193 }
2194 
2195 void CodeHeapState::print_blobType_legend(outputStream* out) {
2196   out->cr();
2197   printBox(out, '-', "Block types used in the following CodeHeap dump", NULL);
2198   for (int type = noType; type < lastType; type += 1) {
2199     out->print_cr("  %c - %s", blobTypeChar[type], blobTypeName[type]);
2200   }
2201   out->print_cr("  -----------------------------------------------------");
2202   out->cr();
2203 }
2204 
2205 void CodeHeapState::print_space_legend(outputStream* out) {
2206   unsigned int indicator = 0;
2207   unsigned int age_range = 256;
2208   unsigned int range_beg = latest_compilation_id;
2209   out->cr();
2210   printBox(out, '-', "Space ranges, based on granule occupancy", NULL);
2211   out->print_cr("    -   0%% == occupancy");
2212   for (int i=0; i<=9; i++) {
2213     out->print_cr("  %d - %3d%% < occupancy < %3d%%", i, 10*i, 10*(i+1));
2214   }
2215   out->print_cr("  * - 100%% == occupancy");
2216   out->print_cr("  ----------------------------------------------");
2217   out->cr();
2218 }
2219 
2220 void CodeHeapState::print_age_legend(outputStream* out) {
2221   unsigned int indicator = 0;
2222   unsigned int age_range = 256;
2223   unsigned int range_beg = latest_compilation_id;
2224   out->cr();
2225   printBox(out, '-', "Age ranges, based on compilation id", NULL);
2226   while (age_range > 0) {
2227     out->print_cr("  %d - %6d to %6d", indicator, range_beg, latest_compilation_id - latest_compilation_id/age_range);
2228     range_beg = latest_compilation_id - latest_compilation_id/age_range;
2229     age_range /= 2;
2230     indicator += 1;
2231   }
2232   out->print_cr("  -----------------------------------------");
2233   out->cr();
2234 }
2235 
2236 void CodeHeapState::print_blobType_single(outputStream* out, u2 /* blobType */ type) {
2237   out->print("%c", blobTypeChar[type]);
2238 }
2239 
2240 void CodeHeapState::print_count_single(outputStream* out, unsigned short count) {
2241   if (count >= 16)    out->print("*");
2242   else if (count > 0) out->print("%1.1x", count);
2243   else                out->print(" ");
2244 }
2245 
2246 void CodeHeapState::print_space_single(outputStream* out, unsigned short space) {
2247   size_t  space_in_bytes = ((unsigned int)space)<<log2_seg_size;
2248   char    fraction       = (space == 0) ? ' ' : (space_in_bytes >= granule_size-1) ? '*' : char('0'+10*space_in_bytes/granule_size);
2249   out->print("%c", fraction);
2250 }
2251 
2252 void CodeHeapState::print_age_single(outputStream* out, unsigned int age) {
2253   unsigned int indicator = 0;
2254   unsigned int age_range = 256;
2255   if (age > 0) {
2256     while ((age_range > 0) && (latest_compilation_id-age > latest_compilation_id/age_range)) {
2257       age_range /= 2;
2258       indicator += 1;
2259     }
2260     out->print("%c", char('0'+indicator));
2261   } else {
2262     out->print(" ");
2263   }
2264 }
2265 
2266 void CodeHeapState::print_line_delim(outputStream* out, outputStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2267   if (ix % gpl == 0) {
2268     if (ix > 0) {
2269       ast->print("|");
2270     }
2271     ast->cr();
2272     assert(out == ast, "must use the same stream!");
2273 
2274     ast->print("%p", low_bound + ix*granule_size);
2275     ast->fill_to(19);
2276     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2277   }
2278 }
2279 
2280 void CodeHeapState::print_line_delim(outputStream* out, bufferedStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2281   assert(out != ast, "must not use the same stream!");
2282   if (ix % gpl == 0) {
2283     if (ix > 0) {
2284       ast->print("|");
2285     }
2286     ast->cr();
2287 
2288     { // can't use STRINGSTREAM_FLUSH_LOCKED("") here.
2289       ttyLocker ttyl;
2290       out->print("%s", ast->as_string());
2291       ast->reset();
2292     }
2293 
2294     ast->print("%p", low_bound + ix*granule_size);
2295     ast->fill_to(19);
2296     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2297   }
2298 }
2299 
2300 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2301   if (cb != NULL ) {
2302     if (cb->is_runtime_stub())                return runtimeStub;
2303     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2304     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2305     if (cb->is_exception_stub())              return exceptionStub;
2306     if (cb->is_safepoint_stub())              return safepointStub;
2307     if (cb->is_adapter_blob())                return adapterBlob;
2308     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2309     if (cb->is_buffer_blob())                 return bufferBlob;
2310 
2311     if (cb->is_nmethod() ) {
2312       if (((nmethod*)cb)->is_in_use())        return nMethod_inuse;
2313       if (((nmethod*)cb)->is_alive() && !(((nmethod*)cb)->is_not_entrant()))   return nMethod_notused;
2314       if (((nmethod*)cb)->is_alive())         return nMethod_alive;
2315       if (((nmethod*)cb)->is_unloaded())      return nMethod_unloaded;
2316       if (((nmethod*)cb)->is_zombie())        return nMethod_dead;
2317       tty->print_cr("unhandled nmethod state");
2318       return nMethod_dead;
2319     }
2320   }
2321   return noType;
2322 }