77fab52b6c65226898b5f7f306eed8881f946f44
[ghc-hetmet.git] / rts / Profiling.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2000
4  *
5  * Support for profiling
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #ifdef PROFILING
10
11 #include "PosixSource.h"
12 #include "Rts.h"
13 #include "RtsUtils.h"
14 #include "RtsFlags.h"
15 #include "Profiling.h"
16 #include "Proftimer.h"
17 #include "Timer.h"
18 #include "ProfHeap.h"
19 #include "Arena.h"
20 #include "RetainerProfile.h"
21 #include "LdvProfile.h"
22
23 #include <string.h>
24
25 #ifdef DEBUG
26 #include "Trace.h"
27 #endif
28
29 /*
30  * Profiling allocation arena.
31  */
32 Arena *prof_arena;
33
34 /*
35  * Global variables used to assign unique IDs to cc's, ccs's, and 
36  * closure_cats
37  */
38
39 unsigned int CC_ID;
40 unsigned int CCS_ID;
41 unsigned int HP_ID;
42
43 /* figures for the profiling report.
44  */
45 static ullong total_alloc;
46 static lnat   total_prof_ticks;
47
48 /* Globals for opening the profiling log file(s)
49  */
50 static char *prof_filename; /* prof report file name = <program>.prof */
51 FILE *prof_file;
52
53 static char *hp_filename;       /* heap profile (hp2ps style) log file */
54 FILE *hp_file;
55
56 /* The Current Cost Centre Stack (for attributing costs)
57  */
58 CostCentreStack *CCCS;
59
60 /* Linked lists to keep track of cc's and ccs's that haven't
61  * been declared in the log file yet
62  */
63 CostCentre *CC_LIST;
64 CostCentreStack *CCS_LIST;
65
66 /*
67  * Built-in cost centres and cost-centre stacks:
68  *
69  *    MAIN   is the root of the cost-centre stack tree.  If there are
70  *           no _scc_s in the program, all costs will be attributed
71  *           to MAIN.
72  *
73  *    SYSTEM is the RTS in general (scheduler, etc.).  All costs for
74  *           RTS operations apart from garbage collection are attributed
75  *           to SYSTEM.
76  *
77  *    GC     is the storage manager / garbage collector.
78  *
79  *    OVERHEAD gets all costs generated by the profiling system
80  *           itself.  These are costs that would not be incurred
81  *           during non-profiled execution of the program.
82  *
83  *    SUBSUMED is the one-and-only CCS placed on top-level functions. 
84  *           It indicates that all costs are to be attributed to the
85  *           enclosing cost centre stack.  SUBSUMED never accumulates
86  *           any costs.  The is_caf flag is set on the subsumed cost
87  *           centre.
88  *
89  *    DONT_CARE is a placeholder cost-centre we assign to static
90  *           constructors.  It should *never* accumulate any costs.
91  */
92
93 CC_DECLARE(CC_MAIN,      "MAIN",        "MAIN",      CC_IS_BORING, );
94 CC_DECLARE(CC_SYSTEM,    "SYSTEM",      "MAIN",      CC_IS_BORING, );
95 CC_DECLARE(CC_GC,        "GC",          "GC",        CC_IS_BORING, );
96 CC_DECLARE(CC_OVERHEAD,  "OVERHEAD_of", "PROFILING", CC_IS_CAF,    );
97 CC_DECLARE(CC_SUBSUMED,  "SUBSUMED",    "MAIN",      CC_IS_CAF,    );
98 CC_DECLARE(CC_DONT_CARE, "DONT_CARE",   "MAIN",      CC_IS_BORING, );
99
100 CCS_DECLARE(CCS_MAIN,       CC_MAIN,       );
101 CCS_DECLARE(CCS_SYSTEM,     CC_SYSTEM,     );
102 CCS_DECLARE(CCS_GC,         CC_GC,         );
103 CCS_DECLARE(CCS_OVERHEAD,   CC_OVERHEAD,   );
104 CCS_DECLARE(CCS_SUBSUMED,   CC_SUBSUMED,   );
105 CCS_DECLARE(CCS_DONT_CARE,  CC_DONT_CARE, );
106
107 /* 
108  * Uniques for the XML log-file format
109  */
110 #define CC_UQ         1
111 #define CCS_UQ        2
112 #define TC_UQ         3
113 #define HEAP_OBJ_UQ   4
114 #define TIME_UPD_UQ   5
115 #define HEAP_UPD_UQ   6
116
117 /* 
118  * Static Functions
119  */
120
121 static  CostCentreStack * ActualPush_     ( CostCentreStack *ccs, CostCentre *cc, 
122                                             CostCentreStack *new_ccs );
123 static  rtsBool           ccs_to_ignore   ( CostCentreStack *ccs );
124 static  void              count_ticks     ( CostCentreStack *ccs );
125 static  void              inherit_costs   ( CostCentreStack *ccs );
126 static  void              reportCCS       ( CostCentreStack *ccs, nat indent );
127 static  void              DecCCS          ( CostCentreStack *ccs );
128 static  void              DecBackEdge     ( CostCentreStack *ccs, 
129                                             CostCentreStack *oldccs );
130 static  CostCentreStack * CheckLoop       ( CostCentreStack *ccs, CostCentre *cc );
131 static  CostCentreStack * pruneCCSTree    ( CostCentreStack *ccs );
132 static  CostCentreStack * ActualPush      ( CostCentreStack *, CostCentre * );
133 static  CostCentreStack * IsInIndexTable  ( IndexTable *, CostCentre * );
134 static  IndexTable *      AddToIndexTable ( IndexTable *, CostCentreStack *, 
135                                             CostCentre *, unsigned int );
136 static  void              ccsSetSelected  ( CostCentreStack *ccs );
137
138 static  void              initTimeProfiling   ( void );
139 static  void              initProfilingLogFile( void );
140
141 static  void              reportCCS_XML       ( CostCentreStack *ccs );
142
143 /* -----------------------------------------------------------------------------
144    Initialise the profiling environment
145    -------------------------------------------------------------------------- */
146
147 void
148 initProfiling1 (void)
149 {
150   // initialise our arena
151   prof_arena = newArena();
152
153   /* for the benefit of allocate()... */
154   CCCS = CCS_SYSTEM;
155   
156   /* Initialize counters for IDs */
157   CC_ID  = 1;
158   CCS_ID = 1;
159   HP_ID  = 1;
160   
161   /* Initialize Declaration lists to NULL */
162   CC_LIST  = NULL;
163   CCS_LIST = NULL;
164
165   /* Register all the cost centres / stacks in the program 
166    * CC_MAIN gets link = 0, all others have non-zero link.
167    */
168   REGISTER_CC(CC_MAIN);
169   REGISTER_CC(CC_SYSTEM);
170   REGISTER_CC(CC_GC);
171   REGISTER_CC(CC_OVERHEAD);
172   REGISTER_CC(CC_SUBSUMED);
173   REGISTER_CC(CC_DONT_CARE);
174   REGISTER_CCS(CCS_MAIN);
175   REGISTER_CCS(CCS_SYSTEM);
176   REGISTER_CCS(CCS_GC);
177   REGISTER_CCS(CCS_OVERHEAD);
178   REGISTER_CCS(CCS_SUBSUMED);
179   REGISTER_CCS(CCS_DONT_CARE);
180
181   CCCS = CCS_OVERHEAD;
182
183   /* cost centres are registered by the per-module 
184    * initialisation code now... 
185    */
186 }
187
188 void
189 freeProfiling1 (void)
190 {
191     arenaFree(prof_arena);
192 }
193
194 void
195 initProfiling2 (void)
196 {
197   CostCentreStack *ccs, *next;
198
199   CCCS = CCS_SYSTEM;
200
201   /* Set up the log file, and dump the header and cost centre
202    * information into it.  */
203   initProfilingLogFile();
204
205   /* find all the "special" cost centre stacks, and make them children
206    * of CCS_MAIN.
207    */
208   ASSERT(CCS_MAIN->prevStack == 0);
209   CCS_MAIN->root = CC_MAIN;
210   ccsSetSelected(CCS_MAIN);
211   DecCCS(CCS_MAIN);
212
213   for (ccs = CCS_LIST; ccs != CCS_MAIN; ) {
214     next = ccs->prevStack;
215     ccs->prevStack = 0;
216     ActualPush_(CCS_MAIN,ccs->cc,ccs);
217     ccs->root = ccs->cc;
218     ccs = next;
219   }
220   
221   if (RtsFlags.CcFlags.doCostCentres) {
222     initTimeProfiling();
223   }
224
225   if (RtsFlags.ProfFlags.doHeapProfile) {
226     initHeapProfiling();
227   }
228 }
229
230 // Decide whether closures with this CCS should contribute to the heap
231 // profile.
232 static void 
233 ccsSetSelected( CostCentreStack *ccs )
234 {
235     if (RtsFlags.ProfFlags.modSelector) {
236         if (! strMatchesSelector( ccs->cc->module,
237                                   RtsFlags.ProfFlags.modSelector ) ) {
238             ccs->selected = 0;
239             return;
240         }
241     }
242     if (RtsFlags.ProfFlags.ccSelector) {
243         if (! strMatchesSelector( ccs->cc->label,
244                                   RtsFlags.ProfFlags.ccSelector ) ) {
245             ccs->selected = 0;
246             return;
247         }
248     }
249     if (RtsFlags.ProfFlags.ccsSelector) {
250         CostCentreStack *c;
251         for (c = ccs; c != NULL; c = c->prevStack) {
252             if ( strMatchesSelector( c->cc->label,
253                                      RtsFlags.ProfFlags.ccsSelector )) {
254                 break; 
255             }
256         }
257         if (c == NULL) {
258             ccs->selected = 0;
259             return;
260         }
261     }
262
263     ccs->selected = 1;
264     return;
265 }
266
267
268 static void
269 initProfilingLogFile(void)
270 {
271     if (RtsFlags.CcFlags.doCostCentres == 0 && 
272         RtsFlags.ProfFlags.doHeapProfile != HEAP_BY_RETAINER)
273     {
274         /* No need for the <prog>.prof file */
275         prof_filename = NULL;
276         prof_file = NULL;
277     }
278     else
279     {
280         /* Initialise the log file name */
281         prof_filename = arenaAlloc(prof_arena, strlen(prog_name) + 6);
282         sprintf(prof_filename, "%s.prof", prog_name);
283
284         /* open the log file */
285         if ((prof_file = fopen(prof_filename, "w")) == NULL) {
286             debugBelch("Can't open profiling report file %s\n", prof_filename);
287             RtsFlags.CcFlags.doCostCentres = 0;
288             // The following line was added by Sung; retainer/LDV profiling may need
289             // two output files, i.e., <program>.prof/hp.
290             if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_RETAINER)
291                 RtsFlags.ProfFlags.doHeapProfile = 0;
292             return;
293         }
294
295         if (RtsFlags.CcFlags.doCostCentres == COST_CENTRES_XML) {
296             /* dump the time, and the profiling interval */
297             fprintf(prof_file, "\"%s\"\n", time_str());
298             fprintf(prof_file, "\"%d ms\"\n", RtsFlags.MiscFlags.tickInterval);
299             
300             /* declare all the cost centres */
301             {
302                 CostCentre *cc;
303                 for (cc = CC_LIST; cc != NULL; cc = cc->link) {
304                     fprintf(prof_file, "%d %ld \"%s\" \"%s\"\n",
305                             CC_UQ, cc->ccID, cc->label, cc->module);
306                 }
307             }
308         }
309     }
310     
311     if (RtsFlags.ProfFlags.doHeapProfile) {
312         /* Initialise the log file name */
313         hp_filename = arenaAlloc(prof_arena, strlen(prog_name) + 6);
314         sprintf(hp_filename, "%s.hp", prog_name);
315         
316         /* open the log file */
317         if ((hp_file = fopen(hp_filename, "w")) == NULL) {
318             debugBelch("Can't open profiling report file %s\n", 
319                     hp_filename);
320             RtsFlags.ProfFlags.doHeapProfile = 0;
321             return;
322         }
323     }
324 }
325
326 void
327 initTimeProfiling(void)
328 {
329   /* Start ticking */
330   startProfTimer();
331 };
332
333 void 
334 endProfiling ( void )
335 {
336   if (RtsFlags.CcFlags.doCostCentres) {
337     stopProfTimer();
338   }
339   if (RtsFlags.ProfFlags.doHeapProfile) {
340     endHeapProfiling();
341   }
342 }
343
344 /* -----------------------------------------------------------------------------
345    Set cost centre stack when entering a function.
346    -------------------------------------------------------------------------- */
347 rtsBool entering_PAP;
348
349 void
350 EnterFunCCS ( CostCentreStack *ccsfn )
351 {
352   /* PAP_entry has already set CCCS for us */
353   if (entering_PAP) {
354     entering_PAP = rtsFalse;
355     return;
356   }
357
358   if (ccsfn->root->is_caf == CC_IS_CAF) {
359     CCCS = AppendCCS(CCCS,ccsfn);
360   } else {
361     CCCS = ccsfn;
362   }
363 }
364
365 /* -----------------------------------------------------------------------------
366    Cost-centre stack manipulation
367    -------------------------------------------------------------------------- */
368
369 #ifdef DEBUG
370 CostCentreStack * _PushCostCentre ( CostCentreStack *ccs, CostCentre *cc );
371 CostCentreStack *
372 PushCostCentre ( CostCentreStack *ccs, CostCentre *cc )
373 #define PushCostCentre _PushCostCentre
374 {
375     IF_DEBUG(prof,
376              traceBegin("pushing %s on ", cc->label);
377              debugCCS(ccs);
378              traceEnd(););
379              
380     return PushCostCentre(ccs,cc);
381 }
382 #endif
383
384 CostCentreStack *
385 PushCostCentre ( CostCentreStack *ccs, CostCentre *cc )
386 {
387   CostCentreStack *temp_ccs;
388   
389   if (ccs == EMPTY_STACK)
390     return ActualPush(ccs,cc);
391   else {
392     if (ccs->cc == cc)
393       return ccs;
394     else {
395       /* check if we've already memoized this stack */
396       temp_ccs = IsInIndexTable(ccs->indexTable,cc);
397       
398       if (temp_ccs != EMPTY_STACK)
399         return temp_ccs;
400       else {
401         temp_ccs = CheckLoop(ccs,cc);
402         if (temp_ccs != NULL) {
403           /* we have recursed to an older CCS.  Mark this in
404            * the index table, and emit a "back edge" into the
405            * log file.
406            */
407           ccs->indexTable = AddToIndexTable(ccs->indexTable,temp_ccs,cc,1);
408           DecBackEdge(temp_ccs,ccs);
409           return temp_ccs;
410         } else {
411           return ActualPush(ccs,cc);
412         }
413       }
414     }
415   }
416 }
417
418 static CostCentreStack *
419 CheckLoop ( CostCentreStack *ccs, CostCentre *cc )
420 {
421   while (ccs != EMPTY_STACK) {
422     if (ccs->cc == cc)
423       return ccs;
424     ccs = ccs->prevStack;
425   }
426   return NULL;
427 }
428
429 /* Append ccs1 to ccs2 (ignoring any CAF cost centre at the root of ccs1 */
430
431 #ifdef DEBUG
432 CostCentreStack *_AppendCCS ( CostCentreStack *ccs1, CostCentreStack *ccs2 );
433 CostCentreStack *
434 AppendCCS ( CostCentreStack *ccs1, CostCentreStack *ccs2 )
435 #define AppendCCS _AppendCCS
436 {
437   IF_DEBUG(prof, 
438            if (ccs1 != ccs2) {
439              debugBelch("Appending ");
440              debugCCS(ccs1);
441              debugBelch(" to ");
442              debugCCS(ccs2);
443              debugBelch("\n");});
444   return AppendCCS(ccs1,ccs2);
445 }
446 #endif
447
448 CostCentreStack *
449 AppendCCS ( CostCentreStack *ccs1, CostCentreStack *ccs2 )
450 {
451   CostCentreStack *ccs = NULL;
452
453   if (ccs1 == ccs2) {
454     return ccs1;
455   }
456
457   if (ccs2->cc->is_caf == CC_IS_CAF) {
458     return ccs1;
459   }
460   
461   if (ccs2->prevStack != NULL) {
462     ccs = AppendCCS(ccs1, ccs2->prevStack);
463   }
464
465   return PushCostCentre(ccs,ccs2->cc);
466 }
467
468 static CostCentreStack *
469 ActualPush ( CostCentreStack *ccs, CostCentre *cc )
470 {
471   CostCentreStack *new_ccs;
472   
473   /* allocate space for a new CostCentreStack */
474   new_ccs = (CostCentreStack *) arenaAlloc(prof_arena, sizeof(CostCentreStack));
475   
476   return ActualPush_(ccs, cc, new_ccs);
477 }
478
479 static CostCentreStack *
480 ActualPush_ ( CostCentreStack *ccs, CostCentre *cc, CostCentreStack *new_ccs )
481 {
482   /* assign values to each member of the structure */
483   new_ccs->ccsID = CCS_ID++;
484   new_ccs->cc = cc;
485   new_ccs->prevStack = ccs;
486   
487   new_ccs->indexTable = EMPTY_TABLE;
488   
489   /* Initialise the various _scc_ counters to zero
490    */
491   new_ccs->scc_count        = 0;
492   
493   /* Initialize all other stats here.  There should be a quick way
494    * that's easily used elsewhere too 
495    */
496   new_ccs->time_ticks = 0;
497   new_ccs->mem_alloc = 0;
498   new_ccs->inherited_ticks = 0;
499   new_ccs->inherited_alloc = 0;
500   
501   new_ccs->root = ccs->root;
502
503   // Set the selected field.
504   ccsSetSelected(new_ccs);
505
506   /* update the memoization table for the parent stack */
507   if (ccs != EMPTY_STACK)
508     ccs->indexTable = AddToIndexTable(ccs->indexTable, new_ccs, cc, 
509                                       0/*not a back edge*/);
510   
511   /* make sure this CC is declared at the next heap/time sample */
512   DecCCS(new_ccs);
513   
514   /* return a pointer to the new stack */
515   return new_ccs;
516 }
517
518
519 static CostCentreStack *
520 IsInIndexTable(IndexTable *it, CostCentre *cc)
521 {
522   while (it!=EMPTY_TABLE)
523     {
524       if (it->cc==cc)
525         return it->ccs;
526       else
527         it = it->next;
528     }
529   
530   /* otherwise we never found it so return EMPTY_TABLE */
531   return EMPTY_TABLE;
532 }
533
534
535 static IndexTable *
536 AddToIndexTable(IndexTable *it, CostCentreStack *new_ccs, 
537                 CostCentre *cc, unsigned int back_edge)
538 {
539   IndexTable *new_it;
540   
541   new_it = arenaAlloc(prof_arena, sizeof(IndexTable));
542   
543   new_it->cc = cc;
544   new_it->ccs = new_ccs;
545   new_it->next = it;
546   new_it->back_edge = back_edge;
547   return new_it;
548 }
549
550
551 static void
552 DecCCS(CostCentreStack *ccs)
553 {
554   if (prof_file && RtsFlags.CcFlags.doCostCentres == COST_CENTRES_XML) {
555     if (ccs->prevStack == EMPTY_STACK)
556       fprintf(prof_file, "%d %ld 1 %ld\n", CCS_UQ, 
557               ccs->ccsID, ccs->cc->ccID);
558     else
559       fprintf(prof_file, "%d %ld 2 %ld %ld\n", CCS_UQ, 
560               ccs->ccsID, ccs->cc->ccID, ccs->prevStack->ccsID);
561   }
562 }
563
564 static void
565 DecBackEdge( CostCentreStack *ccs, CostCentreStack *oldccs )
566 {
567   if (prof_file && RtsFlags.CcFlags.doCostCentres == COST_CENTRES_XML) {
568     if (ccs->prevStack == EMPTY_STACK)
569       fprintf(prof_file, "%d %ld 1 %ld\n", CCS_UQ, 
570               ccs->ccsID, ccs->cc->ccID);
571     else
572       fprintf(prof_file, "%d %ld 2 %ld %ld\n", CCS_UQ, 
573               ccs->ccsID, ccs->cc->ccID, oldccs->ccsID);
574   }
575 }
576
577 /* -----------------------------------------------------------------------------
578    Generating a time & allocation profiling report.
579    -------------------------------------------------------------------------- */
580
581 /* We omit certain system-related CCs and CCSs from the default
582  * reports, so as not to cause confusion.
583  */
584 static rtsBool
585 cc_to_ignore (CostCentre *cc)
586 {
587     if (    cc == CC_OVERHEAD 
588          || cc == CC_DONT_CARE
589          || cc == CC_GC 
590          || cc == CC_SYSTEM) {
591         return rtsTrue;
592     } else {
593         return rtsFalse;
594     }
595 }
596
597 static rtsBool
598 ccs_to_ignore (CostCentreStack *ccs)
599 {
600     if (    ccs == CCS_OVERHEAD 
601          || ccs == CCS_DONT_CARE
602          || ccs == CCS_GC 
603          || ccs == CCS_SYSTEM) {
604         return rtsTrue;
605     } else {
606         return rtsFalse;
607     }
608 }
609
610 /* -----------------------------------------------------------------------------
611    Generating the aggregated per-cost-centre time/alloc report.
612    -------------------------------------------------------------------------- */
613
614 static CostCentre *sorted_cc_list;
615
616 static void
617 aggregate_cc_costs( CostCentreStack *ccs )
618 {
619   IndexTable *i;
620
621   ccs->cc->mem_alloc += ccs->mem_alloc;
622   ccs->cc->time_ticks += ccs->time_ticks;
623
624   for (i = ccs->indexTable; i != 0; i = i->next) {
625     if (!i->back_edge) {
626       aggregate_cc_costs(i->ccs);
627     }
628   }
629 }
630
631 static void
632 insert_cc_in_sorted_list( CostCentre *new_cc )
633 {
634   CostCentre **prev, *cc;
635
636   prev = &sorted_cc_list;
637   for (cc = sorted_cc_list; cc != NULL; cc = cc->link) {
638     if (new_cc->time_ticks > cc->time_ticks) {
639       new_cc->link = cc;
640       *prev = new_cc;
641       return;
642     } else {
643       prev = &(cc->link);
644     }
645   }
646   new_cc->link = NULL;
647   *prev = new_cc;
648 }
649
650 static void
651 report_per_cc_costs( void )
652 {
653   CostCentre *cc, *next;
654
655   aggregate_cc_costs(CCS_MAIN);
656   sorted_cc_list = NULL;
657
658   for (cc = CC_LIST; cc != NULL; cc = next) {
659     next = cc->link;
660     if (cc->time_ticks > total_prof_ticks/100
661         || cc->mem_alloc > total_alloc/100
662         || RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_ALL) {
663       insert_cc_in_sorted_list(cc);
664     }
665   }
666   
667   fprintf(prof_file, "%-30s %-20s", "COST CENTRE", "MODULE");  
668   fprintf(prof_file, "%6s %6s", "%time", "%alloc");
669   if (RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_VERBOSE) {
670     fprintf(prof_file, "  %5s %9s", "ticks", "bytes");
671   }
672   fprintf(prof_file, "\n\n");
673
674   for (cc = sorted_cc_list; cc != NULL; cc = cc->link) {
675       if (cc_to_ignore(cc)) {
676           continue;
677       }
678       fprintf(prof_file, "%-30s %-20s", cc->label, cc->module);
679       fprintf(prof_file, "%6.1f %6.1f",
680               total_prof_ticks == 0 ? 0.0 : (cc->time_ticks / (StgFloat) total_prof_ticks * 100),
681               total_alloc == 0 ? 0.0 : (cc->mem_alloc / (StgFloat)
682                                         total_alloc * 100)
683           );
684       
685       if (RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_VERBOSE) {
686         fprintf(prof_file, "  %5" FMT_Word64 " %9" FMT_Word64,
687                 (StgWord64)(cc->time_ticks), cc->mem_alloc);
688       }
689       fprintf(prof_file, "\n");
690   }
691
692   fprintf(prof_file,"\n\n");
693 }
694
695 /* -----------------------------------------------------------------------------
696    Generate the cost-centre-stack time/alloc report
697    -------------------------------------------------------------------------- */
698
699 static void 
700 fprint_header( void )
701 {
702   fprintf(prof_file, "%-24s %-10s                                                            individual    inherited\n", "", "");
703
704   fprintf(prof_file, "%-24s %-50s", "COST CENTRE", "MODULE");  
705   fprintf(prof_file, "%6s %10s  %5s %5s   %5s %5s", "no.", "entries", "%time", "%alloc", "%time", "%alloc");
706
707   if (RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_VERBOSE) {
708     fprintf(prof_file, "  %5s %9s", "ticks", "bytes");
709 #if defined(PROFILING_DETAIL_COUNTS)
710     fprintf(prof_file, "  %8s %8s %8s %8s %8s %8s %8s",
711             "closures", "thunks", "funcs", "PAPs", "subfuns", "subcafs", "cafssub");
712 #endif
713   }
714
715   fprintf(prof_file, "\n\n");
716 }
717
718 void
719 reportCCSProfiling( void )
720 {
721     nat count;
722     char temp[128]; /* sigh: magic constant */
723
724     stopProfTimer();
725
726     total_prof_ticks = 0;
727     total_alloc = 0;
728     count_ticks(CCS_MAIN);
729     
730     switch (RtsFlags.CcFlags.doCostCentres) {
731     case 0:
732       return;
733     case COST_CENTRES_XML:
734       gen_XML_logfile();
735       return;
736     default:
737       break;
738     }
739
740     fprintf(prof_file, "\t%s Time and Allocation Profiling Report  (%s)\n", 
741             time_str(), "Final");
742
743     fprintf(prof_file, "\n\t  ");
744     fprintf(prof_file, " %s", prog_name);
745     fprintf(prof_file, " +RTS");
746     for (count = 0; rts_argv[count]; count++)
747         fprintf(prof_file, " %s", rts_argv[count]);
748     fprintf(prof_file, " -RTS");
749     for (count = 1; prog_argv[count]; count++)
750         fprintf(prof_file, " %s", prog_argv[count]);
751     fprintf(prof_file, "\n\n");
752
753     fprintf(prof_file, "\ttotal time  = %11.2f secs   (%lu ticks @ %d ms)\n",
754             (double) total_prof_ticks *
755         (double) RtsFlags.MiscFlags.tickInterval / 1000,
756             (unsigned long) total_prof_ticks,
757         (int) RtsFlags.MiscFlags.tickInterval);
758
759     fprintf(prof_file, "\ttotal alloc = %11s bytes",
760             ullong_format_string(total_alloc * sizeof(W_),
761                                  temp, rtsTrue/*commas*/));
762
763 #if defined(PROFILING_DETAIL_COUNTS)
764     fprintf(prof_file, "  (%lu closures)", total_allocs);
765 #endif
766     fprintf(prof_file, "  (excludes profiling overheads)\n\n");
767
768     report_per_cc_costs();
769
770     inherit_costs(CCS_MAIN);
771
772     fprint_header();
773     reportCCS(pruneCCSTree(CCS_MAIN), 0);
774 }
775
776 static void 
777 reportCCS(CostCentreStack *ccs, nat indent)
778 {
779   CostCentre *cc;
780   IndexTable *i;
781
782   cc = ccs->cc;
783   
784   /* Only print cost centres with non 0 data ! */
785   
786   if ( RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_ALL ||
787        ! ccs_to_ignore(ccs))
788         /* force printing of *all* cost centres if -P -P */ 
789     {
790
791     fprintf(prof_file, "%-*s%-*s %-50s", 
792             indent, "", 24-indent, cc->label, cc->module);
793
794     fprintf(prof_file, "%6ld %11.0f %5.1f  %5.1f   %5.1f  %5.1f",
795             ccs->ccsID, (double) ccs->scc_count, 
796             total_prof_ticks == 0 ? 0.0 : ((double)ccs->time_ticks / (double)total_prof_ticks * 100.0),
797             total_alloc == 0 ? 0.0 : ((double)ccs->mem_alloc / (double)total_alloc * 100.0),
798             total_prof_ticks == 0 ? 0.0 : ((double)ccs->inherited_ticks / (double)total_prof_ticks * 100.0),
799             total_alloc == 0 ? 0.0 : ((double)ccs->inherited_alloc / (double)total_alloc * 100.0)
800             );
801
802     if (RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_VERBOSE) {
803       fprintf(prof_file, "  %5" FMT_Word64 " %9" FMT_Word64, 
804               (StgWord64)(ccs->time_ticks), ccs->mem_alloc*sizeof(W_));
805 #if defined(PROFILING_DETAIL_COUNTS)
806       fprintf(prof_file, "  %8ld %8ld %8ld %8ld %8ld %8ld %8ld",
807               ccs->mem_allocs, ccs->thunk_count,
808               ccs->function_count, ccs->pap_count,
809               ccs->subsumed_fun_count,  ccs->subsumed_caf_count,
810               ccs->caffun_subsumed);
811 #endif
812     }
813     fprintf(prof_file, "\n");
814   }
815
816   for (i = ccs->indexTable; i != 0; i = i->next) {
817     if (!i->back_edge) {
818       reportCCS(i->ccs, indent+1);
819     }
820   }
821 }
822
823
824 /* Traverse the cost centre stack tree and accumulate
825  * ticks/allocations.
826  */
827 static void
828 count_ticks(CostCentreStack *ccs)
829 {
830   IndexTable *i;
831   
832   if (!ccs_to_ignore(ccs)) {
833     total_alloc += ccs->mem_alloc;
834     total_prof_ticks += ccs->time_ticks;
835   }
836   for (i = ccs->indexTable; i != NULL; i = i->next)
837     if (!i->back_edge) {
838       count_ticks(i->ccs);
839     }
840 }
841
842 /* Traverse the cost centre stack tree and inherit ticks & allocs.
843  */
844 static void
845 inherit_costs(CostCentreStack *ccs)
846 {
847   IndexTable *i;
848
849   if (ccs_to_ignore(ccs)) { return; }
850
851   ccs->inherited_ticks += ccs->time_ticks;
852   ccs->inherited_alloc += ccs->mem_alloc;
853
854   for (i = ccs->indexTable; i != NULL; i = i->next)
855       if (!i->back_edge) {
856           inherit_costs(i->ccs);
857           ccs->inherited_ticks += i->ccs->inherited_ticks;
858           ccs->inherited_alloc += i->ccs->inherited_alloc;
859       }
860   
861   return;
862 }
863
864 static CostCentreStack *
865 pruneCCSTree( CostCentreStack *ccs )
866 {
867   CostCentreStack *ccs1;
868   IndexTable *i, **prev;
869   
870   prev = &ccs->indexTable;
871   for (i = ccs->indexTable; i != 0; i = i->next) {
872     if (i->back_edge) { continue; }
873
874     ccs1 = pruneCCSTree(i->ccs);
875     if (ccs1 == NULL) {
876       *prev = i->next;
877     } else {
878       prev = &(i->next);
879     }
880   }
881
882   if ( (RtsFlags.CcFlags.doCostCentres >= COST_CENTRES_ALL
883         /* force printing of *all* cost centres if -P -P */ )
884        
885        || ( ccs->indexTable != 0 )
886        || ( ccs->scc_count || ccs->time_ticks || ccs->mem_alloc )
887       ) {
888       return ccs;
889   } else {
890       return NULL;
891   }
892 }
893
894 /* -----------------------------------------------------------------------------
895    Generate the XML time/allocation profile
896    -------------------------------------------------------------------------- */
897
898 void
899 gen_XML_logfile( void )
900 {
901   fprintf(prof_file, "%d %lu", TIME_UPD_UQ, total_prof_ticks);
902
903   reportCCS_XML(pruneCCSTree(CCS_MAIN));
904
905   fprintf(prof_file, " 0\n");
906 }
907
908 static void 
909 reportCCS_XML(CostCentreStack *ccs)
910 {
911   CostCentre *cc;
912   IndexTable *i;
913
914   if (ccs_to_ignore(ccs)) { return; }
915
916   cc = ccs->cc;
917   
918   fprintf(prof_file, " 1 %ld %" FMT_Word64 " %" FMT_Word64 " %" FMT_Word64, 
919           ccs->ccsID, ccs->scc_count, (StgWord64)(ccs->time_ticks), ccs->mem_alloc);
920
921   for (i = ccs->indexTable; i != 0; i = i->next) {
922     if (!i->back_edge) {
923       reportCCS_XML(i->ccs);
924     }
925   }
926 }
927
928 void
929 fprintCCS( FILE *f, CostCentreStack *ccs )
930 {
931   fprintf(f,"<");
932   for (; ccs && ccs != CCS_MAIN; ccs = ccs->prevStack ) {
933       fprintf(f,"%s.%s", ccs->cc->module, ccs->cc->label);
934       if (ccs->prevStack && ccs->prevStack != CCS_MAIN) {
935           fprintf(f,",");
936       }
937   }
938   fprintf(f,">");
939 }
940
941 /* For calling from .cmm code, where we can't reliably refer to stderr */
942 void
943 fprintCCS_stderr( CostCentreStack *ccs )
944 {
945     fprintCCS(stderr, ccs);
946 }
947
948 #ifdef DEBUG
949 void
950 debugCCS( CostCentreStack *ccs )
951 {
952   debugBelch("<");
953   for (; ccs && ccs != CCS_MAIN; ccs = ccs->prevStack ) {
954       debugBelch("%s.%s", ccs->cc->module, ccs->cc->label);
955       if (ccs->prevStack && ccs->prevStack != CCS_MAIN) {
956           debugBelch(",");
957       }
958   }
959   debugBelch(">");
960 }
961 #endif /* DEBUG */
962
963 #endif /* PROFILING */