cfg.c 28.9 KB
Newer Older
1
/* Control flow graph manipulation code for GNU compiler.
2
   Copyright (C) 1987-2013 Free Software Foundation, Inc.
3 4 5 6 7

This file is part of GCC.

GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
8
Software Foundation; either version 3, or (at your option) any later
9 10 11 12 13 14 15 16
version.

GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
17 18
along with GCC; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  */
19

20
/* This file contains low level functions to manipulate the CFG and
21
   analyze it.  All other modules should not transform the data structure
22 23 24
   directly and use abstraction instead.  The file is supposed to be
   ordered bottom-up and should not contain any code dependent on a
   particular intermediate language (RTL or trees).
25 26 27 28

   Available functionality:
     - Initialization/deallocation
	 init_flow, clear_edges
29 30
     - Low level basic block manipulation
	 alloc_block, expunge_block
31
     - Edge manipulation
32
	 make_edge, make_single_succ_edge, cached_make_edge, remove_edge
33 34
	 - Low level edge redirection (without updating instruction chain)
	     redirect_edge_succ, redirect_edge_succ_nodup, redirect_edge_pred
35
     - Dumping and debugging
36 37 38
	 dump_flow_info, debug_flow_info, dump_edge_info
     - Allocation of AUX fields for basic blocks
	 alloc_aux_for_blocks, free_aux_for_blocks, alloc_aux_for_block
39
     - clear_bb_flags
40 41 42 43
     - Consistency checking
	 verify_flow_info
     - Dumping and debugging
	 print_rtl_with_bb, dump_bb, debug_bb, debug_bb_n
44 45 46

   TODO: Document these "Available functionality" functions in the files
   that implement them.
47 48 49 50
 */

#include "config.h"
#include "system.h"
51
#include "coretypes.h"
52
#include "obstack.h"
53
#include "ggc.h"
54
#include "hash-table.h"
55
#include "alloc-pool.h"
56
#include "tree.h"
57
#include "basic-block.h"
58
#include "df.h"
59
#include "cfgloop.h" /* FIXME: For struct loop.  */
60
#include "dumpfile.h"
61 62


63 64
#define RDIV(X,Y) (((X) + (Y) / 2) / (Y))

65
/* Called once at initialization time.  */
66 67

void
Diego Novillo committed
68
init_flow (struct function *the_fun)
69
{
Diego Novillo committed
70
  if (!the_fun->cfg)
71
    the_fun->cfg = ggc_alloc_cleared_control_flow_graph ();
Diego Novillo committed
72 73
  n_edges_for_function (the_fun) = 0;
  ENTRY_BLOCK_PTR_FOR_FUNCTION (the_fun)
74
    = ggc_alloc_cleared_basic_block_def ();
Diego Novillo committed
75 76
  ENTRY_BLOCK_PTR_FOR_FUNCTION (the_fun)->index = ENTRY_BLOCK;
  EXIT_BLOCK_PTR_FOR_FUNCTION (the_fun)
77
    = ggc_alloc_cleared_basic_block_def ();
Diego Novillo committed
78
  EXIT_BLOCK_PTR_FOR_FUNCTION (the_fun)->index = EXIT_BLOCK;
H.J. Lu committed
79
  ENTRY_BLOCK_PTR_FOR_FUNCTION (the_fun)->next_bb
Diego Novillo committed
80
    = EXIT_BLOCK_PTR_FOR_FUNCTION (the_fun);
H.J. Lu committed
81
  EXIT_BLOCK_PTR_FOR_FUNCTION (the_fun)->prev_bb
Diego Novillo committed
82
    = ENTRY_BLOCK_PTR_FOR_FUNCTION (the_fun);
83 84
}

85
/* Helper function for remove_edge and clear_edges.  Frees edge structure
86
   without actually removing it from the pred/succ arrays.  */
87 88

static void
89
free_edge (edge e)
90 91
{
  n_edges--;
92
  ggc_free (e);
93 94
}

95 96 97
/* Free the memory associated with the edge structures.  */

void
98
clear_edges (void)
99
{
100
  basic_block bb;
101
  edge e;
102
  edge_iterator ei;
103

104
  FOR_EACH_BB (bb)
105
    {
106 107
      FOR_EACH_EDGE (e, ei, bb->succs)
	free_edge (e);
108 109
      vec_safe_truncate (bb->succs, 0);
      vec_safe_truncate (bb->preds, 0);
110
    }
111

112 113
  FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
    free_edge (e);
114 115
  vec_safe_truncate (EXIT_BLOCK_PTR->preds, 0);
  vec_safe_truncate (ENTRY_BLOCK_PTR->succs, 0);
116

117
  gcc_assert (!n_edges);
118 119
}

120
/* Allocate memory for basic_block.  */
121

122
basic_block
123
alloc_block (void)
124 125
{
  basic_block bb;
126
  bb = ggc_alloc_cleared_basic_block_def ();
127
  return bb;
128 129
}

130 131
/* Link block B to chain after AFTER.  */
void
132
link_block (basic_block b, basic_block after)
133 134 135 136 137 138
{
  b->next_bb = after->next_bb;
  b->prev_bb = after;
  after->next_bb = b;
  b->next_bb->prev_bb = b;
}
139

140 141
/* Unlink block B from chain.  */
void
142
unlink_block (basic_block b)
143 144 145
{
  b->next_bb->prev_bb = b->prev_bb;
  b->prev_bb->next_bb = b->next_bb;
146 147
  b->prev_bb = NULL;
  b->next_bb = NULL;
148
}
149

150 151
/* Sequentially order blocks and compact the arrays.  */
void
152
compact_blocks (void)
153 154
{
  int i;
155

156 157
  SET_BASIC_BLOCK (ENTRY_BLOCK, ENTRY_BLOCK_PTR);
  SET_BASIC_BLOCK (EXIT_BLOCK, EXIT_BLOCK_PTR);
H.J. Lu committed
158

159 160
  if (df)
    df_compact_blocks ();
H.J. Lu committed
161
  else
162
    {
163
      basic_block bb;
H.J. Lu committed
164

165 166 167 168 169 170 171 172
      i = NUM_FIXED_BLOCKS;
      FOR_EACH_BB (bb)
	{
	  SET_BASIC_BLOCK (i, bb);
	  bb->index = i;
	  i++;
	}
      gcc_assert (i == n_basic_blocks);
173

174 175 176
      for (; i < last_basic_block; i++)
	SET_BASIC_BLOCK (i, NULL);
    }
177 178 179 180
  last_basic_block = n_basic_blocks;
}

/* Remove block B from the basic block array.  */
181

182
void
183
expunge_block (basic_block b)
184
{
185
  unlink_block (b);
186
  SET_BASIC_BLOCK (b->index, NULL);
187
  n_basic_blocks--;
188 189 190 191 192
  /* We should be able to ggc_free here, but we are not.
     The dead SSA_NAMES are left pointing to dead statements that are pointing
     to dead basic blocks making garbage collector to die.
     We should be able to release all dead SSA_NAMES and at the same time we should
     clear out BB pointer of dead statements consistently.  */
193
}
194

195 196 197 198 199
/* Connect E to E->src.  */

static inline void
connect_src (edge e)
{
200
  vec_safe_push (e->src->succs, e);
201
  df_mark_solutions_dirty ();
202 203 204 205 206 207 208 209
}

/* Connect E to E->dest.  */

static inline void
connect_dest (edge e)
{
  basic_block dest = e->dest;
210
  vec_safe_push (dest->preds, e);
211
  e->dest_idx = EDGE_COUNT (dest->preds) - 1;
212
  df_mark_solutions_dirty ();
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
}

/* Disconnect edge E from E->src.  */

static inline void
disconnect_src (edge e)
{
  basic_block src = e->src;
  edge_iterator ei;
  edge tmp;

  for (ei = ei_start (src->succs); (tmp = ei_safe_edge (ei)); )
    {
      if (tmp == e)
	{
228
	  src->succs->unordered_remove (ei.index);
229
	  df_mark_solutions_dirty ();
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	  return;
	}
      else
	ei_next (&ei);
    }

  gcc_unreachable ();
}

/* Disconnect edge E from E->dest.  */

static inline void
disconnect_dest (edge e)
{
  basic_block dest = e->dest;
  unsigned int dest_idx = e->dest_idx;

247
  dest->preds->unordered_remove (dest_idx);
248 249 250 251 252

  /* If we removed an edge in the middle of the edge vector, we need
     to update dest_idx of the edge that moved into the "hole".  */
  if (dest_idx < EDGE_COUNT (dest->preds))
    EDGE_PRED (dest, dest_idx)->dest_idx = dest_idx;
253
  df_mark_solutions_dirty ();
254 255
}

256 257 258 259 260
/* Create an edge connecting SRC and DEST with flags FLAGS.  Return newly
   created edge.  Use this only if you are sure that this edge can't
   possibly already exist.  */

edge
261
unchecked_make_edge (basic_block src, basic_block dst, int flags)
262 263
{
  edge e;
264
  e = ggc_alloc_cleared_edge_def ();
265 266 267 268 269
  n_edges++;

  e->src = src;
  e->dest = dst;
  e->flags = flags;
270 271 272

  connect_src (e);
  connect_dest (e);
273

274
  execute_on_growing_pred (e);
275 276 277
  return e;
}

278
/* Create an edge connecting SRC and DST with FLAGS optionally using
279
   edge cache CACHE.  Return the new edge, NULL if already exist.  */
280

281
edge
282
cached_make_edge (sbitmap edge_cache, basic_block src, basic_block dst, int flags)
283
{
284 285 286 287
  if (edge_cache == NULL
      || src == ENTRY_BLOCK_PTR
      || dst == EXIT_BLOCK_PTR)
    return make_edge (src, dst, flags);
288

289
  /* Does the requested edge already exist?  */
290
  if (! bitmap_bit_p (edge_cache, dst->index))
291
    {
292 293
      /* The edge does not exist.  Create one and update the
	 cache.  */
294
      bitmap_set_bit (edge_cache, dst->index);
295
      return unchecked_make_edge (src, dst, flags);
296
    }
297

298 299 300 301 302 303 304
  /* At this point, we know that the requested edge exists.  Adjust
     flags if necessary.  */
  if (flags)
    {
      edge e = find_edge (src, dst);
      e->flags |= flags;
    }
305

306
  return NULL;
307 308 309 310 311 312
}

/* Create an edge connecting SRC and DEST with flags FLAGS.  Return newly
   created edge or NULL if already exist.  */

edge
313
make_edge (basic_block src, basic_block dest, int flags)
314
{
315 316 317 318 319 320 321 322 323 324
  edge e = find_edge (src, dest);

  /* Make sure we don't add duplicate edges.  */
  if (e)
    {
      e->flags |= flags;
      return NULL;
    }

  return unchecked_make_edge (src, dest, flags);
325 326
}

327
/* Create an edge connecting SRC to DEST and set probability by knowing
328 329 330
   that it is the single edge leaving SRC.  */

edge
331
make_single_succ_edge (basic_block src, basic_block dest, int flags)
332 333 334 335 336 337
{
  edge e = make_edge (src, dest, flags);

  e->probability = REG_BR_PROB_BASE;
  e->count = src->count;
  return e;
338 339 340 341 342
}

/* This function will remove an edge from the flow graph.  */

void
343
remove_edge_raw (edge e)
344
{
345
  remove_predictions_associated_with_edge (e);
346 347
  execute_on_shrinking_pred (e);

348 349
  disconnect_src (e);
  disconnect_dest (e);
350

351
  free_edge (e);
352 353 354 355 356
}

/* Redirect an edge's successor from one block to another.  */

void
357
redirect_edge_succ (edge e, basic_block new_succ)
358
{
359 360
  execute_on_shrinking_pred (e);

361
  disconnect_dest (e);
362

363
  e->dest = new_succ;
364 365

  /* Reconnect the edge to the new successor block.  */
366 367
  connect_dest (e);

368
  execute_on_growing_pred (e);
369 370 371 372 373
}

/* Redirect an edge's predecessor from one block to another.  */

void
374
redirect_edge_pred (edge e, basic_block new_pred)
375
{
376
  disconnect_src (e);
377

378
  e->src = new_pred;
379 380

  /* Reconnect the edge to the new predecessor block.  */
381
  connect_src (e);
382
}
383

384
/* Clear all basic block flags that do not have to be preserved.  */
385
void
386
clear_bb_flags (void)
387
{
388 389 390
  basic_block bb;

  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
391
    bb->flags &= BB_FLAGS_TO_PRESERVE;
392
}
393

394 395 396 397 398
/* Check the consistency of profile information.  We can't do that
   in verify_flow_info, as the counts may get invalid for incompletely
   solved graphs, later eliminating of conditionals or roundoff errors.
   It is still practical to have them reported for debugging of simple
   testcases.  */
399 400
static void
check_bb_profile (basic_block bb, FILE * file, int indent, int flags)
401 402 403 404
{
  edge e;
  int sum = 0;
  gcov_type lsum;
405
  edge_iterator ei;
406
  struct function *fun = DECL_STRUCT_FUNCTION (current_function_decl);
407 408 409
  char *s_indent = (char *) alloca ((size_t) indent + 1);
  memset ((void *) s_indent, ' ', (size_t) indent);
  s_indent[indent] = '\0';
410

411
  if (profile_status_for_function (fun) == PROFILE_ABSENT)
412 413
    return;

414
  if (bb != EXIT_BLOCK_PTR_FOR_FUNCTION (fun))
415
    {
416
      FOR_EACH_EDGE (e, ei, bb->succs)
417
	sum += e->probability;
418
      if (EDGE_COUNT (bb->succs) && abs (sum - REG_BR_PROB_BASE) > 100)
419 420
	fprintf (file, "%s%sInvalid sum of outgoing probabilities %.1f%%\n",
		 (flags & TDF_COMMENT) ? ";; " : "", s_indent,
421 422
		 sum * 100.0 / REG_BR_PROB_BASE);
      lsum = 0;
423
      FOR_EACH_EDGE (e, ei, bb->succs)
424
	lsum += e->count;
425 426
      if (EDGE_COUNT (bb->succs)
	  && (lsum - bb->count > 100 || lsum - bb->count < -100))
427 428
	fprintf (file, "%s%sInvalid sum of outgoing counts %i, should be %i\n",
		 (flags & TDF_COMMENT) ? ";; " : "", s_indent,
429 430
		 (int) lsum, (int) bb->count);
    }
431
    if (bb != ENTRY_BLOCK_PTR_FOR_FUNCTION (fun))
432 433
    {
      sum = 0;
434
      FOR_EACH_EDGE (e, ei, bb->preds)
435 436 437
	sum += EDGE_FREQUENCY (e);
      if (abs (sum - bb->frequency) > 100)
	fprintf (file,
438 439
		 "%s%sInvalid sum of incoming frequencies %i, should be %i\n",
		 (flags & TDF_COMMENT) ? ";; " : "", s_indent,
440 441
		 sum, bb->frequency);
      lsum = 0;
442
      FOR_EACH_EDGE (e, ei, bb->preds)
443 444
	lsum += e->count;
      if (lsum - bb->count > 100 || lsum - bb->count < -100)
445 446
	fprintf (file, "%s%sInvalid sum of incoming counts %i, should be %i\n",
		 (flags & TDF_COMMENT) ? ";; " : "", s_indent,
447 448 449 450
		 (int) lsum, (int) bb->count);
    }
}

451
void
452
dump_edge_info (FILE *file, edge e, int flags, int do_succ)
453
{
454
  basic_block side = (do_succ ? e->dest : e->src);
455 456 457 458 459 460
  bool do_details = false;
  
  if ((flags & TDF_DETAILS) != 0
      && (flags & TDF_SLIM) == 0)
    do_details = true;

461 462 463
  /* ENTRY_BLOCK_PTR/EXIT_BLOCK_PTR depend on cfun.
     Compare against ENTRY_BLOCK/EXIT_BLOCK to avoid that dependency.  */
  if (side->index == ENTRY_BLOCK)
464
    fputs (" ENTRY", file);
465
  else if (side->index == EXIT_BLOCK)
466 467
    fputs (" EXIT", file);
  else
468
    fprintf (file, " %d", side->index);
469

470
  if (e->probability && do_details)
471
    fprintf (file, " [%.1f%%] ", e->probability * 100.0 / REG_BR_PROB_BASE);
472

473
  if (e->count && do_details)
474
    {
475
      fputs (" count:", file);
476
      fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
477 478
    }

479
  if (e->flags && do_details)
480
    {
481 482 483 484 485 486 487 488
      static const char * const bitnames[] =
	{
#define DEF_EDGE_FLAG(NAME,IDX) #NAME ,
#include "cfg-flags.def"
	  NULL
#undef DEF_EDGE_FLAG
	};
      bool comma = false;
489
      int i, flags = e->flags;
490

491
      gcc_assert (e->flags <= EDGE_ALL_FLAGS);
492
      fputs (" (", file);
493 494 495 496 497 498 499
      for (i = 0; flags; i++)
	if (flags & (1 << i))
	  {
	    flags &= ~(1 << i);

	    if (comma)
	      fputc (',', file);
500 501
	    fputs (bitnames[i], file);
	    comma = true;
502
	  }
503

504 505 506
      fputc (')', file);
    }
}
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

DEBUG_FUNCTION void
debug (edge_def &ref)
{
  /* FIXME (crowl): Is this desireable?  */
  dump_edge_info (stderr, &ref, 0, false);
  dump_edge_info (stderr, &ref, 0, true);
}

DEBUG_FUNCTION void
debug (edge_def *ptr)
{
  if (ptr)
    debug (*ptr);
  else
    fprintf (stderr, "<nil>\n");
}
524

525
/* Simple routines to easily allocate AUX fields of basic blocks.  */
526

527 528 529 530
static struct obstack block_aux_obstack;
static void *first_block_aux_obj = 0;
static struct obstack edge_aux_obstack;
static void *first_edge_aux_obj = 0;
531

532
/* Allocate a memory block of SIZE as BB->aux.  The obstack must
533
   be first initialized by alloc_aux_for_blocks.  */
534

535
static void
536
alloc_aux_for_block (basic_block bb, int size)
537
{
538
  /* Verify that aux field is clear.  */
539
  gcc_assert (!bb->aux && first_block_aux_obj);
540 541
  bb->aux = obstack_alloc (&block_aux_obstack, size);
  memset (bb->aux, 0, size);
542 543
}

544 545
/* Initialize the block_aux_obstack and if SIZE is nonzero, call
   alloc_aux_for_block for each basic block.  */
546 547

void
548
alloc_aux_for_blocks (int size)
549
{
550
  static int initialized;
551

552
  if (!initialized)
553
    {
554 555
      gcc_obstack_init (&block_aux_obstack);
      initialized = 1;
556
    }
557 558 559
  else
    /* Check whether AUX data are still allocated.  */
    gcc_assert (!first_block_aux_obj);
Mike Stump committed
560

561
  first_block_aux_obj = obstack_alloc (&block_aux_obstack, 0);
562
  if (size)
563
    {
564
      basic_block bb;
565

566
      FOR_ALL_BB (bb)
567
	alloc_aux_for_block (bb, size);
568 569
    }
}
570

571
/* Clear AUX pointers of all blocks.  */
572 573

void
574
clear_aux_for_blocks (void)
575
{
576
  basic_block bb;
577

578
  FOR_ALL_BB (bb)
579
    bb->aux = NULL;
580 581 582 583 584 585
}

/* Free data allocated in block_aux_obstack and clear AUX pointers
   of all blocks.  */

void
586
free_aux_for_blocks (void)
587
{
588
  gcc_assert (first_block_aux_obj);
589
  obstack_free (&block_aux_obstack, first_block_aux_obj);
590
  first_block_aux_obj = NULL;
591 592

  clear_aux_for_blocks ();
593
}
594

595
/* Allocate a memory edge of SIZE as E->aux.  The obstack must
596
   be first initialized by alloc_aux_for_edges.  */
597

598
void
599
alloc_aux_for_edge (edge e, int size)
600 601
{
  /* Verify that aux field is clear.  */
602
  gcc_assert (!e->aux && first_edge_aux_obj);
603 604 605
  e->aux = obstack_alloc (&edge_aux_obstack, size);
  memset (e->aux, 0, size);
}
606

607 608
/* Initialize the edge_aux_obstack and if SIZE is nonzero, call
   alloc_aux_for_edge for each basic edge.  */
609

610
void
611
alloc_aux_for_edges (int size)
612 613
{
  static int initialized;
614

615 616 617 618
  if (!initialized)
    {
      gcc_obstack_init (&edge_aux_obstack);
      initialized = 1;
619
    }
620 621 622
  else
    /* Check whether AUX data are still allocated.  */
    gcc_assert (!first_edge_aux_obj);
623

624
  first_edge_aux_obj = obstack_alloc (&edge_aux_obstack, 0);
625
  if (size)
626
    {
627 628 629
      basic_block bb;

      FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
630
	{
631
	  edge e;
632
	  edge_iterator ei;
633

634
	  FOR_EACH_EDGE (e, ei, bb->succs)
635
	    alloc_aux_for_edge (e, size);
636 637 638 639
	}
    }
}

640
/* Clear AUX pointers of all edges.  */
641 642

void
643
clear_aux_for_edges (void)
644
{
645 646
  basic_block bb;
  edge e;
647

648
  FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
649
    {
650 651
      edge_iterator ei;
      FOR_EACH_EDGE (e, ei, bb->succs)
652
	e->aux = NULL;
653
    }
654 655 656 657 658 659
}

/* Free data allocated in edge_aux_obstack and clear AUX pointers
   of all edges.  */

void
660
free_aux_for_edges (void)
661
{
662
  gcc_assert (first_edge_aux_obj);
663
  obstack_free (&edge_aux_obstack, first_edge_aux_obj);
664
  first_edge_aux_obj = NULL;
665 666

  clear_aux_for_edges ();
667
}
668

669
DEBUG_FUNCTION void
670
debug_bb (basic_block bb)
671
{
672
  dump_bb (stderr, bb, 0, dump_flags);
673 674
}

675
DEBUG_FUNCTION basic_block
676
debug_bb_n (int n)
677 678
{
  basic_block bb = BASIC_BLOCK (n);
679
  debug_bb (bb);
680
  return bb;
681
}
682

683 684 685 686 687 688
/* Dumps cfg related information about basic block BB to OUTF.
   If HEADER is true, dump things that appear before the instructions
   contained in BB.  If FOOTER is true, dump things that appear after.
   Flags are the TDF_* masks as documented in dumpfile.h.
   NB: With TDF_DETAILS, it is assumed that cfun is available, so
   that maybe_hot_bb_p and probably_never_executed_bb_p don't ICE.  */
689

690 691 692
void
dump_bb_info (FILE *outf, basic_block bb, int indent, int flags,
	      bool do_header, bool do_footer)
693
{
694
  edge_iterator ei;
695
  edge e;
696 697
  static const char * const bb_bitnames[] =
    {
698 699 700 701
#define DEF_BASIC_BLOCK_FLAG(NAME,IDX) #NAME ,
#include "cfg-flags.def"
      NULL
#undef DEF_BASIC_BLOCK_FLAG
702 703
    };
  const unsigned n_bitnames = sizeof (bb_bitnames) / sizeof (char *);
704
  bool first;
705 706 707
  char *s_indent = (char *) alloca ((size_t) indent + 1);
  memset ((void *) s_indent, ' ', (size_t) indent);
  s_indent[indent] = '\0';
708

709 710 711 712 713 714 715 716
  gcc_assert (bb->flags <= BB_ALL_FLAGS);

  if (do_header)
    {
      unsigned i;

      if (flags & TDF_COMMENT)
	fputs (";; ", outf);
717
      fprintf (outf, "%sbasic block %d, loop depth %d",
718
	       s_indent, bb->index, bb_loop_depth (bb));
719 720
      if (flags & TDF_DETAILS)
	{
721
	  struct function *fun = DECL_STRUCT_FUNCTION (current_function_decl);
722 723
	  fprintf (outf, ", count " HOST_WIDEST_INT_PRINT_DEC,
		   (HOST_WIDEST_INT) bb->count);
724
	  fprintf (outf, ", freq %i", bb->frequency);
725
	  if (maybe_hot_bb_p (fun, bb))
726
	    fputs (", maybe hot", outf);
727
	  if (probably_never_executed_bb_p (fun, bb))
728 729 730
	    fputs (", probably never executed", outf);
	}
      fputc ('\n', outf);
731 732
      if (TDF_DETAILS)
	check_bb_profile (bb, outf, indent, flags);
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

      if (flags & TDF_DETAILS)
	{
	  if (flags & TDF_COMMENT)
	    fputs (";; ", outf);
	  fprintf (outf, "%s prev block ", s_indent);
	  if (bb->prev_bb)
	    fprintf (outf, "%d", bb->prev_bb->index);
	  else
	    fprintf (outf, "(nil)");
	  fprintf (outf, ", next block ");
	  if (bb->next_bb)
	    fprintf (outf, "%d", bb->next_bb->index);
	  else
	    fprintf (outf, "(nil)");

	  fputs (", flags:", outf);
750
	  first = true;
751 752 753 754 755 756 757 758 759 760 761 762
	  for (i = 0; i < n_bitnames; i++)
	    if (bb->flags & (1 << i))
	      {
		if (first)
		  fputs (" (", outf);
		else
		  fputs (", ", outf);
		first = false;
		fputs (bb_bitnames[i], outf);
	      }
	  if (!first)
	    fputc (')', outf);
763
	  fputc ('\n', outf);
764 765 766 767 768
	}

      if (flags & TDF_COMMENT)
	fputs (";; ", outf);
      fprintf (outf, "%s pred:      ", s_indent);
769
      first = true;
770
      FOR_EACH_EDGE (e, ei, bb->preds)
771 772 773 774 775 776 777 778 779 780 781
	{
	  if (! first)
	    {
	      if (flags & TDF_COMMENT)
		fputs (";; ", outf);
	      fprintf (outf, "%s            ", s_indent);
	    }
	  first = false;
	  dump_edge_info (outf, e, flags, 0);
	  fputc ('\n', outf);
	}
782 783
      if (first)
	fputc ('\n', outf);
784 785 786 787 788 789 790
    }

  if (do_footer)
    {
      if (flags & TDF_COMMENT)
	fputs (";; ", outf);
      fprintf (outf, "%s succ:      ", s_indent);
791
      first = true;
792
      FOR_EACH_EDGE (e, ei, bb->succs)
793 794 795 796 797 798 799 800 801 802 803
        {
	  if (! first)
	    {
	      if (flags & TDF_COMMENT)
		fputs (";; ", outf);
	      fprintf (outf, "%s            ", s_indent);
	    }
	  first = false;
	  dump_edge_info (outf, e, flags, 1);
	  fputc ('\n', outf);
	}
804 805
      if (first)
	fputc ('\n', outf);
806
    }
807 808 809 810 811
}

/* Dumps a brief description of cfg to FILE.  */

void
812
brief_dump_cfg (FILE *file, int flags)
813 814 815 816 817
{
  basic_block bb;

  FOR_EACH_BB (bb)
    {
818 819 820
      dump_bb_info (file, bb, 0,
		    flags & (TDF_COMMENT | TDF_DETAILS),
		    true, true);
821 822
    }
}
823 824 825

/* An edge originally destinating BB of FREQUENCY and COUNT has been proved to
   leave the block by TAKEN_EDGE.  Update profile of BB such that edge E can be
Mike Stump committed
826
   redirected to destination of TAKEN_EDGE.
827 828 829

   This function may leave the profile inconsistent in the case TAKEN_EDGE
   frequency or count is believed to be lower than FREQUENCY or COUNT
830
   respectively.  */
831 832 833 834 835 836
void
update_bb_profile_for_threading (basic_block bb, int edge_frequency,
				 gcov_type count, edge taken_edge)
{
  edge c;
  int prob;
837
  edge_iterator ei;
838 839 840

  bb->count -= count;
  if (bb->count < 0)
841 842 843 844 845 846
    {
      if (dump_file)
	fprintf (dump_file, "bb %i count became negative after threading",
		 bb->index);
      bb->count = 0;
    }
847 848 849 850

  /* Compute the probability of TAKEN_EDGE being reached via threaded edge.
     Watch for overflows.  */
  if (bb->frequency)
851
    prob = GCOV_COMPUTE_SCALE (edge_frequency, bb->frequency);
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  else
    prob = 0;
  if (prob > taken_edge->probability)
    {
      if (dump_file)
	fprintf (dump_file, "Jump threading proved probability of edge "
		 "%i->%i too small (it is %i, should be %i).\n",
		 taken_edge->src->index, taken_edge->dest->index,
		 taken_edge->probability, prob);
      prob = taken_edge->probability;
    }

  /* Now rescale the probabilities.  */
  taken_edge->probability -= prob;
  prob = REG_BR_PROB_BASE - prob;
  bb->frequency -= edge_frequency;
  if (bb->frequency < 0)
    bb->frequency = 0;
  if (prob <= 0)
    {
      if (dump_file)
	fprintf (dump_file, "Edge frequencies of bb %i has been reset, "
		 "frequency of block should end up being 0, it is %i\n",
		 bb->index, bb->frequency);
876 877 878 879
      EDGE_SUCC (bb, 0)->probability = REG_BR_PROB_BASE;
      ei = ei_start (bb->succs);
      ei_next (&ei);
      for (; (c = ei_safe_edge (ei)); ei_next (&ei))
880 881
	c->probability = 0;
    }
882 883
  else if (prob != REG_BR_PROB_BASE)
    {
884
      int scale = RDIV (65536 * REG_BR_PROB_BASE, prob);
885 886

      FOR_EACH_EDGE (c, ei, bb->succs)
887
	{
888 889
	  /* Protect from overflow due to additional scaling.  */
	  if (c->probability > prob)
890
	    c->probability = REG_BR_PROB_BASE;
891 892 893 894 895 896
	  else
	    {
	      c->probability = RDIV (c->probability * scale, 65536);
	      if (c->probability > REG_BR_PROB_BASE)
		c->probability = REG_BR_PROB_BASE;
	    }
897
	}
898
    }
899

900
  gcc_assert (bb == taken_edge->src);
901 902
  taken_edge->count -= count;
  if (taken_edge->count < 0)
903 904 905 906 907 908
    {
      if (dump_file)
	fprintf (dump_file, "edge %i->%i count became negative after threading",
		 taken_edge->src->index, taken_edge->dest->index);
      taken_edge->count = 0;
    }
909
}
910 911 912 913 914 915 916 917

/* Multiply all frequencies of basic blocks in array BBS of length NBBS
   by NUM/DEN, in int arithmetic.  May lose some accuracy.  */
void
scale_bbs_frequencies_int (basic_block *bbs, int nbbs, int num, int den)
{
  int i;
  edge e;
918 919
  if (num < 0)
    num = 0;
920 921 922 923 924 925 926 927 928 929 930 931 932

  /* Scale NUM and DEN to avoid overflows.  Frequencies are in order of
     10^4, if we make DEN <= 10^3, we can afford to upscale by 100
     and still safely fit in int during calculations.  */
  if (den > 1000)
    {
      if (num > 1000000)
	return;

      num = RDIV (1000 * num, den);
      den = 1000;
    }
  if (num > 100 * den)
933
    return;
934

935 936 937
  for (i = 0; i < nbbs; i++)
    {
      edge_iterator ei;
938
      bbs[i]->frequency = RDIV (bbs[i]->frequency * num, den);
939 940 941
      /* Make sure the frequencies do not grow over BB_FREQ_MAX.  */
      if (bbs[i]->frequency > BB_FREQ_MAX)
	bbs[i]->frequency = BB_FREQ_MAX;
942 943
      bbs[i]->count = RDIV (bbs[i]->count * num, den);
      FOR_EACH_EDGE (e, ei, bbs[i]->succs)
944
	e->count = RDIV (e->count * num, den);
945 946 947
    }
}

948 949 950 951
/* numbers smaller than this value are safe to multiply without getting
   64bit overflow.  */
#define MAX_SAFE_MULTIPLIER (1 << (sizeof (HOST_WIDEST_INT) * 4 - 1))

952 953 954 955
/* Multiply all frequencies of basic blocks in array BBS of length NBBS
   by NUM/DEN, in gcov_type arithmetic.  More accurate than previous
   function but considerably slower.  */
void
Mike Stump committed
956 957
scale_bbs_frequencies_gcov_type (basic_block *bbs, int nbbs, gcov_type num,
				 gcov_type den)
958 959 960
{
  int i;
  edge e;
961
  gcov_type fraction = RDIV (num * 65536, den);
962

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
  gcc_assert (fraction >= 0);

  if (num < MAX_SAFE_MULTIPLIER)
    for (i = 0; i < nbbs; i++)
      {
	edge_iterator ei;
	bbs[i]->frequency = RDIV (bbs[i]->frequency * num, den);
	if (bbs[i]->count <= MAX_SAFE_MULTIPLIER)
	  bbs[i]->count = RDIV (bbs[i]->count * num, den);
	else
	  bbs[i]->count = RDIV (bbs[i]->count * fraction, 65536);
	FOR_EACH_EDGE (e, ei, bbs[i]->succs)
	  if (bbs[i]->count <= MAX_SAFE_MULTIPLIER)
	    e->count = RDIV (e->count * num, den);
	  else
	    e->count = RDIV (e->count * fraction, 65536);
      }
   else
    for (i = 0; i < nbbs; i++)
      {
	edge_iterator ei;
	if (sizeof (gcov_type) > sizeof (int))
	  bbs[i]->frequency = RDIV (bbs[i]->frequency * num, den);
	else
	  bbs[i]->frequency = RDIV (bbs[i]->frequency * fraction, 65536);
	bbs[i]->count = RDIV (bbs[i]->count * fraction, 65536);
	FOR_EACH_EDGE (e, ei, bbs[i]->succs)
	  e->count = RDIV (e->count * fraction, 65536);
      }
992
}
993

994
/* Helper types for hash tables.  */
995 996 997 998 999 1000 1001 1002 1003

struct htab_bb_copy_original_entry
{
  /* Block we are attaching info to.  */
  int index1;
  /* Index of original or copy (depending on the hashtable) */
  int index2;
};

1004
struct bb_copy_hasher : typed_noop_remove <htab_bb_copy_original_entry>
1005
{
1006 1007 1008 1009 1010
  typedef htab_bb_copy_original_entry value_type;
  typedef htab_bb_copy_original_entry compare_type;
  static inline hashval_t hash (const value_type *);
  static inline bool equal (const value_type *existing,
			    const compare_type * candidate);
1011
};
1012

1013
inline hashval_t
1014
bb_copy_hasher::hash (const value_type *data)
1015
{
1016 1017 1018
  return data->index1;
}

1019
inline bool
1020
bb_copy_hasher::equal (const value_type *data, const compare_type *data2)
1021
{
1022 1023 1024
  return data->index1 == data2->index1;
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
/* Data structures used to maintain mapping between basic blocks and
   copies.  */
static hash_table <bb_copy_hasher> bb_original;
static hash_table <bb_copy_hasher> bb_copy;

/* And between loops and copies.  */
static hash_table <bb_copy_hasher> loop_copy;
static alloc_pool original_copy_bb_pool;


1035 1036
/* Initialize the data structures to maintain mapping between blocks
   and its copies.  */
1037 1038 1039 1040 1041 1042 1043
void
initialize_original_copy_tables (void)
{
  gcc_assert (!original_copy_bb_pool);
  original_copy_bb_pool
    = create_alloc_pool ("original_copy",
			 sizeof (struct htab_bb_copy_original_entry), 10);
1044 1045 1046
  bb_original.create (10);
  bb_copy.create (10);
  loop_copy.create (10);
1047 1048
}

1049 1050
/* Free the data structures to maintain mapping between blocks and
   its copies.  */
1051 1052 1053 1054
void
free_original_copy_tables (void)
{
  gcc_assert (original_copy_bb_pool);
1055 1056 1057
  bb_copy.dispose ();
  bb_original.dispose ();
  loop_copy.dispose ();
1058 1059 1060 1061
  free_alloc_pool (original_copy_bb_pool);
  original_copy_bb_pool = NULL;
}

1062 1063 1064
/* Removes the value associated with OBJ from table TAB.  */

static void
1065
copy_original_table_clear (hash_table <bb_copy_hasher> tab, unsigned obj)
1066
{
1067
  htab_bb_copy_original_entry **slot;
1068 1069 1070 1071 1072 1073
  struct htab_bb_copy_original_entry key, *elt;

  if (!original_copy_bb_pool)
    return;

  key.index1 = obj;
1074
  slot = tab.find_slot (&key, NO_INSERT);
1075 1076 1077
  if (!slot)
    return;

1078 1079
  elt = *slot;
  tab.clear_slot (slot);
1080 1081 1082 1083 1084 1085 1086
  pool_free (original_copy_bb_pool, elt);
}

/* Sets the value associated with OBJ in table TAB to VAL.
   Do nothing when data structures are not initialized.  */

static void
1087 1088
copy_original_table_set (hash_table <bb_copy_hasher> tab,
			 unsigned obj, unsigned val)
1089 1090 1091 1092 1093 1094 1095 1096
{
  struct htab_bb_copy_original_entry **slot;
  struct htab_bb_copy_original_entry key;

  if (!original_copy_bb_pool)
    return;

  key.index1 = obj;
1097
  slot = tab.find_slot (&key, INSERT);
1098 1099
  if (!*slot)
    {
1100 1101
      *slot = (struct htab_bb_copy_original_entry *)
		pool_alloc (original_copy_bb_pool);
1102 1103 1104 1105 1106
      (*slot)->index1 = obj;
    }
  (*slot)->index2 = val;
}

1107 1108
/* Set original for basic block.  Do nothing when data structures are not
   initialized so passes not needing this don't need to care.  */
1109 1110 1111
void
set_bb_original (basic_block bb, basic_block original)
{
1112
  copy_original_table_set (bb_original, bb->index, original->index);
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
}

/* Get the original basic block.  */
basic_block
get_bb_original (basic_block bb)
{
  struct htab_bb_copy_original_entry *entry;
  struct htab_bb_copy_original_entry key;

  gcc_assert (original_copy_bb_pool);

  key.index1 = bb->index;
1125
  entry = bb_original.find (&key);
1126 1127 1128 1129 1130 1131
  if (entry)
    return BASIC_BLOCK (entry->index2);
  else
    return NULL;
}

1132 1133
/* Set copy for basic block.  Do nothing when data structures are not
   initialized so passes not needing this don't need to care.  */
1134 1135 1136
void
set_bb_copy (basic_block bb, basic_block copy)
{
1137
  copy_original_table_set (bb_copy, bb->index, copy->index);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
}

/* Get the copy of basic block.  */
basic_block
get_bb_copy (basic_block bb)
{
  struct htab_bb_copy_original_entry *entry;
  struct htab_bb_copy_original_entry key;

  gcc_assert (original_copy_bb_pool);

  key.index1 = bb->index;
1150
  entry = bb_copy.find (&key);
1151 1152 1153 1154 1155
  if (entry)
    return BASIC_BLOCK (entry->index2);
  else
    return NULL;
}
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

/* Set copy for LOOP to COPY.  Do nothing when data structures are not
   initialized so passes not needing this don't need to care.  */

void
set_loop_copy (struct loop *loop, struct loop *copy)
{
  if (!copy)
    copy_original_table_clear (loop_copy, loop->num);
  else
    copy_original_table_set (loop_copy, loop->num, copy->num);
}

/* Get the copy of LOOP.  */

struct loop *
get_loop_copy (struct loop *loop)
{
  struct htab_bb_copy_original_entry *entry;
  struct htab_bb_copy_original_entry key;

  gcc_assert (original_copy_bb_pool);

  key.index1 = loop->num;
1180
  entry = loop_copy.find (&key);
1181
  if (entry)
1182
    return get_loop (cfun, entry->index2);
1183 1184 1185
  else
    return NULL;
}