ssa.c 61.5 KB
Newer Older
Alex Samuel committed
1
/* Static Single Assignment conversion routines for the GNU compiler.
2 3
   Copyright (C) 2000, 2001, 2002, 2003
   Free Software Foundation, Inc.
Alex Samuel committed
4

5
This file is part of GCC.
Alex Samuel committed
6

7 8 9 10
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
Software Foundation; either version 2, or (at your option) any later
version.
Alex Samuel committed
11

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

17
You should have received a copy of the GNU General Public License
18
along with GCC; see the file COPYING.  If not, write to the Free
19 20
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.  */
Alex Samuel committed
21 22 23 24 25 26 27 28 29 30

/* References:

   Building an Optimizing Compiler
   Robert Morgan
   Butterworth-Heinemann, 1998

   Static Single Assignment Construction
   Preston Briggs, Tim Harvey, Taylor Simpson
   Technical Report, Rice University, 1995
31
   ftp://ftp.cs.rice.edu/public/preston/optimizer/SSA.ps.gz.  */
Alex Samuel committed
32 33 34

#include "config.h"
#include "system.h"
35 36
#include "coretypes.h"
#include "tm.h"
Alex Samuel committed
37 38

#include "rtl.h"
39
#include "expr.h"
40 41 42 43
#include "varray.h"
#include "partition.h"
#include "sbitmap.h"
#include "hashtab.h"
Alex Samuel committed
44 45 46 47 48 49 50 51 52
#include "regs.h"
#include "hard-reg-set.h"
#include "flags.h"
#include "function.h"
#include "real.h"
#include "insn-config.h"
#include "recog.h"
#include "basic-block.h"
#include "output.h"
53
#include "ssa.h"
Alex Samuel committed
54

Kazu Hirata committed
55
/* TODO:
Alex Samuel committed
56

Alex Samuel committed
57 58 59 60 61 62 63
   Handle subregs better, maybe.  For now, if a reg that's set in a
   subreg expression is duplicated going into SSA form, an extra copy
   is inserted first that copies the entire reg into the duplicate, so
   that the other bits are preserved.  This isn't strictly SSA, since
   at least part of the reg is assigned in more than one place (though
   they are adjacent).

Alex Samuel committed
64 65 66 67 68 69 70
   ??? What to do about strict_low_part.  Probably I'll have to split
   them out of their current instructions first thing.

   Actually the best solution may be to have a kind of "mid-level rtl"
   in which the RTL encodes exactly what we want, without exposing a
   lot of niggling processor details.  At some later point we lower
   the representation, calling back into optabs to finish any necessary
Alex Samuel committed
71 72
   expansion.  */

73 74 75 76 77 78 79 80 81 82
/* All pseudo-registers and select hard registers are converted to SSA
   form.  When converting out of SSA, these select hard registers are
   guaranteed to be mapped to their original register number.  Each
   machine's .h file should define CONVERT_HARD_REGISTER_TO_SSA_P
   indicating which hard registers should be converted.

   When converting out of SSA, temporaries for all registers are
   partitioned.  The partition is checked to ensure that all uses of
   the same hard register in the same machine mode are in the same
   class.  */
Alex Samuel committed
83

84
/* If conservative_reg_partition is nonzero, use a conservative
Alex Samuel committed
85 86 87 88
   register partitioning algorithm (which leaves more regs after
   emerging from SSA) instead of the coalescing one.  This is being
   left in for a limited time only, as a debugging tool until the
   coalescing algorithm is validated.  */
89

Alex Samuel committed
90
static int conservative_reg_partition;
Alex Samuel committed
91

Alex Samuel committed
92 93
/* This flag is set when the CFG is in SSA form.  */
int in_ssa_form = 0;
Alex Samuel committed
94

95
/* Element I is the single instruction that sets register I.  */
Alex Samuel committed
96 97 98 99 100 101
varray_type ssa_definition;

/* Element I-PSEUDO is the normal register that originated the ssa
   register in question.  */
varray_type ssa_rename_from;

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
/* Element I is the normal register that originated the ssa
   register in question.

   A hash table stores the (register, rtl) pairs.  These are each
   xmalloc'ed and deleted when the hash table is destroyed.  */
htab_t ssa_rename_from_ht;

/* The running target ssa register for a given pseudo register.
   (Pseudo registers appear in only one mode.)  */
static rtx *ssa_rename_to_pseudo;
/* Similar, but for hard registers.  A hard register can appear in
   many modes, so we store an equivalent pseudo for each of the
   modes.  */
static rtx ssa_rename_to_hard[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];

/* ssa_rename_from maps pseudo registers to the original corresponding
   RTL.  It is implemented as using a hash table.  */

typedef struct {
  unsigned int reg;
  rtx original;
} ssa_rename_from_pair;

struct ssa_rename_from_hash_table_data {
  sbitmap canonical_elements;
  partition reg_partition;
};

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
static rtx gen_sequence (void);
static void ssa_rename_from_initialize (void);
static rtx ssa_rename_from_lookup (int reg);
static unsigned int original_register (unsigned int regno);
static void ssa_rename_from_insert (unsigned int reg, rtx r);
static void ssa_rename_from_free (void);
typedef int (*srf_trav) (int regno, rtx r, sbitmap canonical_elements,
			 partition reg_partition);
static void ssa_rename_from_traverse (htab_trav callback_function,
				      sbitmap canonical_elements, partition reg_partition);
/*static Avoid warning message.  */ void ssa_rename_from_print (void);
static int ssa_rename_from_print_1 (void **slot, void *data);
static hashval_t ssa_rename_from_hash_function (const void * srfp);
static int ssa_rename_from_equal (const void *srfp1, const void *srfp2);
static void ssa_rename_from_delete (void *srfp);

static rtx ssa_rename_to_lookup (rtx reg);
static void ssa_rename_to_insert (rtx reg, rtx r);
Alex Samuel committed
148 149

/* The number of registers that were live on entry to the SSA routines.  */
150
static unsigned int ssa_max_reg_num;
Alex Samuel committed
151 152 153

/* Local function prototypes.  */

154 155
struct rename_context;

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
static inline rtx * phi_alternative (rtx, int);
static void compute_dominance_frontiers_1 (sbitmap *frontiers,
					   dominance_info idom, int bb,
					   sbitmap done);
static void find_evaluations_1 (rtx dest, rtx set, void *data);
static void find_evaluations (sbitmap *evals, int nregs);
static void compute_iterated_dominance_frontiers (sbitmap *idfs,
						  sbitmap *frontiers,
						  sbitmap *evals, int nregs);
static void insert_phi_node (int regno, int b);
static void insert_phi_nodes (sbitmap *idfs, sbitmap *evals, int nregs);
static void create_delayed_rename (struct rename_context *, rtx *);
static void apply_delayed_renames (struct rename_context *);
static int rename_insn_1 (rtx *ptr, void *data);
static void rename_block (int b, dominance_info dom);
static void rename_registers (int nregs, dominance_info idom);

static inline int ephi_add_node (rtx reg, rtx *nodes, int *n_nodes);
static int * ephi_forward (int t, sbitmap visited, sbitmap *succ, int *tstack);
static void ephi_backward (int t, sbitmap visited, sbitmap *pred, rtx *nodes);
static void ephi_create (int t, sbitmap visited, sbitmap *pred,
			 sbitmap *succ, rtx *nodes);
static void eliminate_phi (edge e, partition reg_partition);
static int make_regs_equivalent_over_bad_edges (int bb,
						partition reg_partition);
Alex Samuel committed
181 182 183

/* These are used only in the conservative register partitioning
   algorithms.  */
Kazu Hirata committed
184
static int make_equivalent_phi_alternatives_equivalent
185 186 187 188
  (int bb, partition reg_partition);
static partition compute_conservative_reg_partition (void);
static int record_canonical_element_1 (void **srfp, void *data);
static int check_hard_regs_in_partition (partition reg_partition);
Alex Samuel committed
189 190

/* These are used in the register coalescing algorithm.  */
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
static int coalesce_if_unconflicting (partition p, conflict_graph conflicts,
				      int reg1, int reg2);
static int coalesce_regs_in_copies (basic_block bb, partition p,
				    conflict_graph conflicts);
static int coalesce_reg_in_phi (rtx, int dest_regno, int src_regno,
				void *data);
static int coalesce_regs_in_successor_phi_nodes (basic_block bb,
						 partition p,
						 conflict_graph conflicts);
static partition compute_coalesced_reg_partition (void);
static int mark_reg_in_phi (rtx *ptr, void *data);
static void mark_phi_and_copy_regs (regset phi_set);

static int rename_equivalent_regs_in_insn (rtx *ptr, void *data);
static void rename_equivalent_regs (partition reg_partition);
Alex Samuel committed
206

207
/* Deal with hard registers.  */
208
static int conflicting_hard_regs_p (int reg1, int reg2);
209 210 211 212 213 214

/* ssa_rename_to maps registers and machine modes to SSA pseudo registers.  */

/* Find the register associated with REG in the indicated mode.  */

static rtx
215
ssa_rename_to_lookup (rtx reg)
216 217 218 219 220 221 222 223 224 225
{
  if (!HARD_REGISTER_P (reg))
    return ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER];
  else
    return ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)];
}

/* Store a new value mapping REG to R in ssa_rename_to.  */

static void
226
ssa_rename_to_insert (rtx reg, rtx r)
227 228 229 230 231 232 233 234 235
{
  if (!HARD_REGISTER_P (reg))
    ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER] = r;
  else
    ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)] = r;
}

/* Prepare ssa_rename_from for use.  */

236
static void
237
ssa_rename_from_initialize (void)
238 239 240 241 242 243 244 245 246 247 248
{
  /* We use an arbitrary initial hash table size of 64.  */
  ssa_rename_from_ht = htab_create (64,
				    &ssa_rename_from_hash_function,
				    &ssa_rename_from_equal,
				    &ssa_rename_from_delete);
}

/* Find the REG entry in ssa_rename_from.  Return NULL_RTX if no entry is
   found.  */

249
static rtx
250
ssa_rename_from_lookup (int reg)
251 252 253 254 255
{
  ssa_rename_from_pair srfp;
  ssa_rename_from_pair *answer;
  srfp.reg = reg;
  srfp.original = NULL_RTX;
256
  answer = htab_find_with_hash (ssa_rename_from_ht, (void *) &srfp, reg);
257 258 259 260 261 262 263
  return (answer == 0 ? NULL_RTX : answer->original);
}

/* Find the number of the original register specified by REGNO.  If
   the register is a pseudo, return the original register's number.
   Otherwise, return this register number REGNO.  */

264
static unsigned int
265
original_register (unsigned int regno)
266 267 268 269 270 271 272
{
  rtx original_rtx = ssa_rename_from_lookup (regno);
  return original_rtx != NULL_RTX ? REGNO (original_rtx) : regno;
}

/* Add mapping from R to REG to ssa_rename_from even if already present.  */

273
static void
274
ssa_rename_from_insert (unsigned int reg, rtx r)
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
{
  void **slot;
  ssa_rename_from_pair *srfp = xmalloc (sizeof (ssa_rename_from_pair));
  srfp->reg = reg;
  srfp->original = r;
  slot = htab_find_slot_with_hash (ssa_rename_from_ht, (const void *) srfp,
				   reg, INSERT);
  if (*slot != 0)
    free ((void *) *slot);
  *slot = srfp;
}

/* Apply the CALLBACK_FUNCTION to each element in ssa_rename_from.
   CANONICAL_ELEMENTS and REG_PARTITION pass data needed by the only
   current use of this function.  */

291
static void
292 293
ssa_rename_from_traverse (htab_trav callback_function,
			  sbitmap canonical_elements, partition reg_partition)
294 295 296 297 298 299 300 301 302
{
  struct ssa_rename_from_hash_table_data srfhd;
  srfhd.canonical_elements = canonical_elements;
  srfhd.reg_partition = reg_partition;
  htab_traverse (ssa_rename_from_ht, callback_function, (void *) &srfhd);
}

/* Destroy ssa_rename_from.  */

303
static void
304
ssa_rename_from_free (void)
305 306 307 308 309 310
{
  htab_delete (ssa_rename_from_ht);
}

/* Print the contents of ssa_rename_from.  */

311 312
/* static  Avoid erroneous error message.  */
void
313
ssa_rename_from_print (void)
314 315 316 317 318 319
{
  printf ("ssa_rename_from's hash table contents:\n");
  htab_traverse (ssa_rename_from_ht, &ssa_rename_from_print_1, NULL);
}

/* Print the contents of the hash table entry SLOT, passing the unused
320
   attribute DATA.  Used as a callback function with htab_traverse ().  */
321 322

static int
323
ssa_rename_from_print_1 (void **slot, void *data ATTRIBUTE_UNUSED)
324 325 326 327 328 329 330 331 332 333
{
  ssa_rename_from_pair * p = *slot;
  printf ("ssa_rename_from maps pseudo %i to original %i.\n",
	  p->reg, REGNO (p->original));
  return 1;
}

/* Given a hash entry SRFP, yield a hash value.  */

static hashval_t
334
ssa_rename_from_hash_function (const void *srfp)
335
{
Kaveh R. Ghazi committed
336
  return ((const ssa_rename_from_pair *) srfp)->reg;
337 338 339 340 341
}

/* Test whether two hash table entries SRFP1 and SRFP2 are equal.  */

static int
342
ssa_rename_from_equal (const void *srfp1, const void *srfp2)
343 344 345 346 347 348 349 350
{
  return ssa_rename_from_hash_function (srfp1) ==
    ssa_rename_from_hash_function (srfp2);
}

/* Delete the hash table entry SRFP.  */

static void
351
ssa_rename_from_delete (void *srfp)
352 353 354
{
  free (srfp);
}
Alex Samuel committed
355 356 357 358 359

/* Given the SET of a PHI node, return the address of the alternative
   for predecessor block C.  */

static inline rtx *
360
phi_alternative (rtx set, int c)
Alex Samuel committed
361 362 363 364 365 366 367 368 369 370 371 372
{
  rtvec phi_vec = XVEC (SET_SRC (set), 0);
  int v;

  for (v = GET_NUM_ELEM (phi_vec) - 2; v >= 0; v -= 2)
    if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
      return &RTVEC_ELT (phi_vec, v);

  return NULL;
}

/* Given the SET of a phi node, remove the alternative for predecessor
373
   block C.  Return nonzero on success, or zero if no alternative is
Alex Samuel committed
374 375
   found for C.  */

376
int
377
remove_phi_alternative (rtx set, basic_block block)
Alex Samuel committed
378 379 380
{
  rtvec phi_vec = XVEC (SET_SRC (set), 0);
  int num_elem = GET_NUM_ELEM (phi_vec);
381
  int v, c;
Alex Samuel committed
382

383
  c = block->index;
Alex Samuel committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  for (v = num_elem - 2; v >= 0; v -= 2)
    if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
      {
	if (v < num_elem - 2)
	  {
	    RTVEC_ELT (phi_vec, v) = RTVEC_ELT (phi_vec, num_elem - 2);
	    RTVEC_ELT (phi_vec, v + 1) = RTVEC_ELT (phi_vec, num_elem - 1);
	  }
	PUT_NUM_ELEM (phi_vec, num_elem - 2);
	return 1;
      }

  return 0;
}

/* For all registers, find all blocks in which they are set.

   This is the transform of what would be local kill information that
   we ought to be getting from flow.  */

static sbitmap *fe_evals;
static int fe_current_bb;

static void
408 409
find_evaluations_1 (rtx dest, rtx set ATTRIBUTE_UNUSED,
		    void *data ATTRIBUTE_UNUSED)
Alex Samuel committed
410 411
{
  if (GET_CODE (dest) == REG
412 413
      && CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
    SET_BIT (fe_evals[REGNO (dest)], fe_current_bb);
Alex Samuel committed
414 415 416
}

static void
417
find_evaluations (sbitmap *evals, int nregs)
Alex Samuel committed
418
{
419
  basic_block bb;
Alex Samuel committed
420 421 422 423

  sbitmap_vector_zero (evals, nregs);
  fe_evals = evals;

424
  FOR_EACH_BB_REVERSE (bb)
Alex Samuel committed
425 426 427
    {
      rtx p, last;

428 429 430
      fe_current_bb = bb->index;
      p = bb->head;
      last = bb->end;
Alex Samuel committed
431 432
      while (1)
	{
433
	  if (INSN_P (p))
Alex Samuel committed
434 435 436 437 438 439 440 441 442 443
	    note_stores (PATTERN (p), find_evaluations_1, NULL);

	  if (p == last)
	    break;
	  p = NEXT_INSN (p);
	}
    }
}

/* Computing the Dominance Frontier:
Kazu Hirata committed
444

445
   As described in Morgan, section 3.5, this may be done simply by
Alex Samuel committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
   walking the dominator tree bottom-up, computing the frontier for
   the children before the parent.  When considering a block B,
   there are two cases:

   (1) A flow graph edge leaving B that does not lead to a child
   of B in the dominator tree must be a block that is either equal
   to B or not dominated by B.  Such blocks belong in the frontier
   of B.

   (2) Consider a block X in the frontier of one of the children C
   of B.  If X is not equal to B and is not dominated by B, it
   is in the frontier of B.
*/

static void
461 462
compute_dominance_frontiers_1 (sbitmap *frontiers, dominance_info idom,
			       int bb, sbitmap done)
Alex Samuel committed
463 464 465
{
  basic_block b = BASIC_BLOCK (bb);
  edge e;
466
  basic_block c;
Alex Samuel committed
467 468 469 470 471 472 473

  SET_BIT (done, bb);
  sbitmap_zero (frontiers[bb]);

  /* Do the frontier of the children first.  Not all children in the
     dominator tree (blocks dominated by this one) are children in the
     CFG, so check all blocks.  */
474
  FOR_EACH_BB (c)
475 476
    if (get_immediate_dominator (idom, c)->index == bb
	&& ! TEST_BIT (done, c->index))
477
      compute_dominance_frontiers_1 (frontiers, idom, c->index, done);
Alex Samuel committed
478 479 480 481 482 483

  /* Find blocks conforming to rule (1) above.  */
  for (e = b->succ; e; e = e->succ_next)
    {
      if (e->dest == EXIT_BLOCK_PTR)
	continue;
484
      if (get_immediate_dominator (idom, e->dest)->index != bb)
485
	SET_BIT (frontiers[bb], e->dest->index);
Alex Samuel committed
486 487 488
    }

  /* Find blocks conforming to rule (2).  */
489
  FOR_EACH_BB (c)
490
    if (get_immediate_dominator (idom, c)->index == bb)
Alex Samuel committed
491 492
      {
	int x;
493
	EXECUTE_IF_SET_IN_SBITMAP (frontiers[c->index], 0, x,
Alex Samuel committed
494
	  {
495
	    if (get_immediate_dominator (idom, BASIC_BLOCK (x))->index != bb)
Alex Samuel committed
496 497 498 499 500
	      SET_BIT (frontiers[bb], x);
	  });
      }
}

501
void
502
compute_dominance_frontiers (sbitmap *frontiers, dominance_info idom)
Alex Samuel committed
503
{
504
  sbitmap done = sbitmap_alloc (last_basic_block);
Alex Samuel committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
  sbitmap_zero (done);

  compute_dominance_frontiers_1 (frontiers, idom, 0, done);

  sbitmap_free (done);
}

/* Computing the Iterated Dominance Frontier:

   This is the set of merge points for a given register.

   This is not particularly intuitive.  See section 7.1 of Morgan, in
   particular figures 7.3 and 7.4 and the immediately surrounding text.
*/

static void
521 522
compute_iterated_dominance_frontiers (sbitmap *idfs, sbitmap *frontiers,
				      sbitmap *evals, int nregs)
Alex Samuel committed
523 524 525 526
{
  sbitmap worklist;
  int reg, passes = 0;

527
  worklist = sbitmap_alloc (last_basic_block);
Alex Samuel committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

  for (reg = 0; reg < nregs; ++reg)
    {
      sbitmap idf = idfs[reg];
      int b, changed;

      /* Start the iterative process by considering those blocks that
	 evaluate REG.  We'll add their dominance frontiers to the
	 IDF, and then consider the blocks we just added.  */
      sbitmap_copy (worklist, evals[reg]);

      /* Morgan's algorithm is incorrect here.  Blocks that evaluate
	 REG aren't necessarily in REG's IDF.  Start with an empty IDF.  */
      sbitmap_zero (idf);

      /* Iterate until the worklist is empty.  */
      do
	{
	  changed = 0;
	  passes++;
	  EXECUTE_IF_SET_IN_SBITMAP (worklist, 0, b,
	    {
	      RESET_BIT (worklist, b);
	      /* For each block on the worklist, add to the IDF all
		 blocks on its dominance frontier that aren't already
		 on the IDF.  Every block that's added is also added
		 to the worklist.  */
	      sbitmap_union_of_diff (worklist, worklist, frontiers[b], idf);
	      sbitmap_a_or_b (idf, idf, frontiers[b]);
	      changed = 1;
	    });
	}
      while (changed);
    }

  sbitmap_free (worklist);

  if (rtl_dump_file)
    {
Kazu Hirata committed
567 568 569
      fprintf (rtl_dump_file,
	       "Iterated dominance frontier: %d passes on %d regs.\n",
	       passes, nregs);
Alex Samuel committed
570 571 572 573 574 575
    }
}

/* Insert the phi nodes.  */

static void
576
insert_phi_node (int regno, int bb)
Alex Samuel committed
577 578 579 580 581 582
{
  basic_block b = BASIC_BLOCK (bb);
  edge e;
  int npred, i;
  rtvec vec;
  rtx phi, reg;
583 584
  rtx insn;
  int end_p;
Alex Samuel committed
585 586 587 588 589 590 591 592 593 594 595

  /* Find out how many predecessors there are.  */
  for (e = b->pred, npred = 0; e; e = e->pred_next)
    if (e->src != ENTRY_BLOCK_PTR)
      npred++;

  /* If this block has no "interesting" preds, then there is nothing to
     do.  Consider a block that only has the entry block as a pred.  */
  if (npred == 0)
    return;

596 597
  /* This is the register to which the phi function will be assigned.  */
  reg = regno_reg_rtx[regno];
Alex Samuel committed
598 599 600 601 602 603 604 605

  /* Construct the arguments to the PHI node.  The use of pc_rtx is just
     a placeholder; we'll insert the proper value in rename_registers.  */
  vec = rtvec_alloc (npred * 2);
  for (e = b->pred, i = 0; e ; e = e->pred_next, i += 2)
    if (e->src != ENTRY_BLOCK_PTR)
      {
	RTVEC_ELT (vec, i + 0) = pc_rtx;
606
	RTVEC_ELT (vec, i + 1) = GEN_INT (e->src->index);
Alex Samuel committed
607 608 609 610 611
      }

  phi = gen_rtx_PHI (VOIDmode, vec);
  phi = gen_rtx_SET (VOIDmode, reg, phi);

612 613 614 615 616
  insn = first_insn_after_basic_block_note (b);
  end_p = PREV_INSN (insn) == b->end;
  emit_insn_before (phi, insn);
  if (end_p)
    b->end = PREV_INSN (insn);
Alex Samuel committed
617 618 619
}

static void
620
insert_phi_nodes (sbitmap *idfs, sbitmap *evals ATTRIBUTE_UNUSED, int nregs)
Alex Samuel committed
621 622 623 624
{
  int reg;

  for (reg = 0; reg < nregs; ++reg)
625
    if (CONVERT_REGISTER_TO_SSA_P (reg))
Alex Samuel committed
626 627 628 629
    {
      int b;
      EXECUTE_IF_SET_IN_SBITMAP (idfs[reg], 0, b,
	{
630
	  if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start, reg))
Alex Samuel committed
631 632 633 634 635
	    insert_phi_node (reg, b);
	});
    }
}

Kazu Hirata committed
636
/* Rename the registers to conform to SSA.
Alex Samuel committed
637 638

   This is essentially the algorithm presented in Figure 7.8 of Morgan,
639
   with a few changes to reduce pattern search time in favor of a bit
Alex Samuel committed
640 641 642 643 644 645 646
   more memory usage.  */

/* One of these is created for each set.  It will live in a list local
   to its basic block for the duration of that block's processing.  */
struct rename_set_data
{
  struct rename_set_data *next;
647
  /* This is the SET_DEST of the (first) SET that sets the REG.  */
Alex Samuel committed
648
  rtx *reg_loc;
649 650 651 652
  /* This is what used to be at *REG_LOC.  */
  rtx old_reg;
  /* This is the REG that will replace OLD_REG.  It's set only
     when the rename data is moved onto the DONE_RENAMES queue.  */
Alex Samuel committed
653
  rtx new_reg;
654 655
  /* This is what to restore ssa_rename_to_lookup (old_reg) to.  It is
     usually the previous contents of ssa_rename_to_lookup (old_reg).  */
Alex Samuel committed
656
  rtx prev_reg;
657
  /* This is the insn that contains all the SETs of the REG.  */
Alex Samuel committed
658 659 660 661 662 663 664
  rtx set_insn;
};

/* This struct is used to pass information to callback functions while
   renaming registers.  */
struct rename_context
{
665 666
  struct rename_set_data *new_renames;
  struct rename_set_data *done_renames;
Alex Samuel committed
667
  rtx current_insn;
Alex Samuel committed
668 669
};

670 671
/* Queue the rename of *REG_LOC.  */
static void
672
create_delayed_rename (struct rename_context *c, rtx *reg_loc)
673 674
{
  struct rename_set_data *r;
675
  r = xmalloc (sizeof(*r));
Kazu Hirata committed
676

677
  if (GET_CODE (*reg_loc) != REG
678
      || !CONVERT_REGISTER_TO_SSA_P (REGNO (*reg_loc)))
Kazu Hirata committed
679
    abort ();
680 681 682

  r->reg_loc = reg_loc;
  r->old_reg = *reg_loc;
683
  r->prev_reg = ssa_rename_to_lookup(r->old_reg);
684 685 686 687
  r->set_insn = c->current_insn;
  r->next = c->new_renames;
  c->new_renames = r;
}
Alex Samuel committed
688 689 690

/* This is part of a rather ugly hack to allow the pre-ssa regno to be
   reused.  If, during processing, a register has not yet been touched,
691
   ssa_rename_to[regno][machno] will be NULL.  Now, in the course of pushing
Kazu Hirata committed
692
   and popping values from ssa_rename_to, when we would ordinarily
Alex Samuel committed
693 694 695 696 697
   pop NULL back in, we pop RENAME_NO_RTX.  We treat this exactly the
   same as NULL, except that it signals that the original regno has
   already been reused.  */
#define RENAME_NO_RTX  pc_rtx

698 699 700 701
/* Move all the entries from NEW_RENAMES onto DONE_RENAMES by
   applying all the renames on NEW_RENAMES.  */

static void
702
apply_delayed_renames (struct rename_context *c)
703 704 705
{
  struct rename_set_data *r;
  struct rename_set_data *last_r = NULL;
706

707 708 709
  for (r = c->new_renames; r != NULL; r = r->next)
    {
      int new_regno;
Kazu Hirata committed
710

711 712
      /* Failure here means that someone has a PARALLEL that sets
	 a register twice (bad!).  */
713
      if (ssa_rename_to_lookup (r->old_reg) != r->prev_reg)
Kazu Hirata committed
714
	abort ();
715 716 717
      /* Failure here means we have changed REG_LOC before applying
	 the rename.  */
      /* For the first set we come across, reuse the original regno.  */
718
      if (r->prev_reg == NULL_RTX && !HARD_REGISTER_P (r->old_reg))
719 720
	{
	  r->new_reg = r->old_reg;
721
	  /* We want to restore RENAME_NO_RTX rather than NULL_RTX.  */
722 723 724 725 726
	  r->prev_reg = RENAME_NO_RTX;
	}
      else
	r->new_reg = gen_reg_rtx (GET_MODE (r->old_reg));
      new_regno = REGNO (r->new_reg);
727
      ssa_rename_to_insert (r->old_reg, r->new_reg);
728 729 730 731

      if (new_regno >= (int) ssa_definition->num_elements)
	{
	  int new_limit = new_regno * 5 / 4;
Kaveh R. Ghazi committed
732
	  VARRAY_GROW (ssa_definition, new_limit);
733 734 735
	}

      VARRAY_RTX (ssa_definition, new_regno) = r->set_insn;
736
      ssa_rename_from_insert (new_regno, r->old_reg);
737 738 739 740 741 742 743 744 745 746
      last_r = r;
    }
  if (last_r != NULL)
    {
      last_r->next = c->done_renames;
      c->done_renames = c->new_renames;
      c->new_renames = NULL;
    }
}

Kazu Hirata committed
747
/* Part one of the first step of rename_block, called through for_each_rtx.
Alex Samuel committed
748 749 750
   Mark pseudos that are set for later update.  Transform uses of pseudos.  */

static int
751
rename_insn_1 (rtx *ptr, void *data)
Alex Samuel committed
752 753
{
  rtx x = *ptr;
Alex Samuel committed
754
  struct rename_context *context = data;
Alex Samuel committed
755 756 757 758 759 760 761 762 763 764 765

  if (x == NULL_RTX)
    return 0;

  switch (GET_CODE (x))
    {
    case SET:
      {
	rtx *destp = &SET_DEST (x);
	rtx dest = SET_DEST (x);

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
	/* An assignment to a paradoxical SUBREG does not read from
	   the destination operand, and thus does not need to be
	   wrapped into a SEQUENCE when translating into SSA form.
	   We merely strip off the SUBREG and proceed normally for
	   this case.  */
	if (GET_CODE (dest) == SUBREG
	    && (GET_MODE_SIZE (GET_MODE (dest))
		> GET_MODE_SIZE (GET_MODE (SUBREG_REG (dest))))
	    && GET_CODE (SUBREG_REG (dest)) == REG
	    && CONVERT_REGISTER_TO_SSA_P (REGNO (SUBREG_REG (dest))))
	  {
	    destp = &XEXP (dest, 0);
	    dest = XEXP (dest, 0);
	  }

781 782 783 784 785 786 787
	/* Some SETs also use the REG specified in their LHS.
	   These can be detected by the presence of
	   STRICT_LOW_PART, SUBREG, SIGN_EXTRACT, and ZERO_EXTRACT
	   in the LHS.  Handle these by changing
	   (set (subreg (reg foo)) ...)
	   into
	   (sequence [(set (reg foo_1) (reg foo))
Kazu Hirata committed
788
	              (set (subreg (reg foo_1)) ...)])
789

790 791 792 793 794
	   FIXME: Much of the time this is too much.  For some constructs
	   we know that the output register is strictly an output
	   (paradoxical SUBREGs and some libcalls for example).

	   For those cases we are better off not making the false
795 796 797 798 799
	   dependency.  */
	if (GET_CODE (dest) == STRICT_LOW_PART
	    || GET_CODE (dest) == SUBREG
	    || GET_CODE (dest) == SIGN_EXTRACT
	    || GET_CODE (dest) == ZERO_EXTRACT)
Alex Samuel committed
800
	  {
801 802
	    rtx i, reg;
	    reg = dest;
Kazu Hirata committed
803

804 805 806 807 808
	    while (GET_CODE (reg) == STRICT_LOW_PART
		   || GET_CODE (reg) == SUBREG
		   || GET_CODE (reg) == SIGN_EXTRACT
		   || GET_CODE (reg) == ZERO_EXTRACT)
		reg = XEXP (reg, 0);
Kazu Hirata committed
809

810
	    if (GET_CODE (reg) == REG
811
		&& CONVERT_REGISTER_TO_SSA_P (REGNO (reg)))
812 813 814 815 816 817 818 819 820 821 822 823 824
	      {
		/* Generate (set reg reg), and do renaming on it so
		   that it becomes (set reg_1 reg_0), and we will
		   replace reg with reg_1 in the SUBREG.  */

		struct rename_set_data *saved_new_renames;
		saved_new_renames = context->new_renames;
		context->new_renames = NULL;
		i = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
		for_each_rtx (&i, rename_insn_1, data);
		apply_delayed_renames (context);
		context->new_renames = saved_new_renames;
	      }
Alex Samuel committed
825
	  }
826 827
	else if (GET_CODE (dest) == REG
		 && CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
Alex Samuel committed
828 829 830 831 832
	  {
	    /* We found a genuine set of an interesting register.  Tag
	       it so that we can create a new name for it after we finish
	       processing this insn.  */

833
	    create_delayed_rename (context, destp);
Alex Samuel committed
834 835 836 837

	    /* Since we do not wish to (directly) traverse the
	       SET_DEST, recurse through for_each_rtx for the SET_SRC
	       and return.  */
838 839
	    if (GET_CODE (x) == SET)
	      for_each_rtx (&SET_SRC (x), rename_insn_1, data);
Alex Samuel committed
840 841 842 843 844 845 846 847 848
	    return -1;
	  }

	/* Otherwise, this was not an interesting destination.  Continue
	   on, marking uses as normal.  */
	return 0;
      }

    case REG:
849 850
      if (CONVERT_REGISTER_TO_SSA_P (REGNO (x))
	  && REGNO (x) < ssa_max_reg_num)
Alex Samuel committed
851
	{
852
	  rtx new_reg = ssa_rename_to_lookup (x);
Alex Samuel committed
853

854
	  if (new_reg != RENAME_NO_RTX && new_reg != NULL_RTX)
Alex Samuel committed
855
	    {
856 857 858 859 860 861 862 863 864
	      if (GET_MODE (x) != GET_MODE (new_reg))
		abort ();
	      *ptr = new_reg;
	    }
	  else
	    {
	      /* Undefined value used, rename it to a new pseudo register so
		 that it cannot conflict with an existing register.  */
	      *ptr = gen_reg_rtx (GET_MODE (x));
Alex Samuel committed
865 866 867 868
	    }
	}
      return -1;

869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    case CLOBBER:
      /* There is considerable debate on how CLOBBERs ought to be
	 handled in SSA.  For now, we're keeping the CLOBBERs, which
	 means that we don't really have SSA form.  There are a couple
	 of proposals for how to fix this problem, but neither is
	 implemented yet.  */
      {
	rtx dest = XCEXP (x, 0, CLOBBER);
	if (REG_P (dest))
	  {
	    if (CONVERT_REGISTER_TO_SSA_P (REGNO (dest))
		&& REGNO (dest) < ssa_max_reg_num)
	      {
		rtx new_reg = ssa_rename_to_lookup (dest);
		if (new_reg != NULL_RTX && new_reg != RENAME_NO_RTX)
		    XCEXP (x, 0, CLOBBER) = new_reg;
	      }
	    /* Stop traversing.  */
	    return -1;
Kazu Hirata committed
888
	  }
889 890 891 892 893
	else
	  /* Continue traversing.  */
	  return 0;
      }

Alex Samuel committed
894 895 896 897 898 899 900 901 902 903
    case PHI:
      /* Never muck with the phi.  We do that elsewhere, special-like.  */
      return -1;

    default:
      /* Anything else, continue traversing.  */
      return 0;
    }
}

904
static rtx
905
gen_sequence (void)
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
{
  rtx first_insn = get_insns ();
  rtx result;
  rtx tem;
  int i;
  int len;

  /* Count the insns in the chain.  */
  len = 0;
  for (tem = first_insn; tem; tem = NEXT_INSN (tem))
    len++;

  result = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (len));

  for (i = 0, tem = first_insn; tem; tem = NEXT_INSN (tem), i++)
    XVECEXP (result, 0, i) = tem;

  return result;
}

Alex Samuel committed
926
static void
927
rename_block (int bb, dominance_info idom)
Alex Samuel committed
928 929 930 931 932
{
  basic_block b = BASIC_BLOCK (bb);
  edge e;
  rtx insn, next, last;
  struct rename_set_data *set_data = NULL;
933
  basic_block c;
Alex Samuel committed
934 935 936

  /* Step One: Walk the basic block, adding new names for sets and
     replacing uses.  */
Kazu Hirata committed
937

Alex Samuel committed
938 939 940 941 942
  next = b->head;
  last = b->end;
  do
    {
      insn = next;
943
      if (INSN_P (insn))
Alex Samuel committed
944
	{
Alex Samuel committed
945
	  struct rename_context context;
946 947
	  context.done_renames = set_data;
	  context.new_renames = NULL;
Alex Samuel committed
948
	  context.current_insn = insn;
Alex Samuel committed
949

950
	  start_sequence ();
Alex Samuel committed
951 952
	  for_each_rtx (&PATTERN (insn), rename_insn_1, &context);
	  for_each_rtx (&REG_NOTES (insn), rename_insn_1, &context);
953 954 955 956 957 958 959

	  /* Sometimes, we end up with a sequence of insns that
	     SSA needs to treat as a single insn.  Wrap these in a
	     SEQUENCE.  (Any notes now get attached to the SEQUENCE,
	     not to the old version inner insn.)  */
	  if (get_insns () != NULL_RTX)
	    {
960
	      rtx seq;
961
	      int i;
Kazu Hirata committed
962

963
	      emit (PATTERN (insn));
964 965 966 967 968 969
	      seq = gen_sequence ();
	      /* We really want a SEQUENCE of SETs, not a SEQUENCE
		 of INSNs.  */
	      for (i = 0; i < XVECLEN (seq, 0); i++)
		XVECEXP (seq, 0, i) = PATTERN (XVECEXP (seq, 0, i));
	      PATTERN (insn) = seq;
970 971
	    }
	  end_sequence ();
Kazu Hirata committed
972

973 974
	  apply_delayed_renames (&context);
	  set_data = context.done_renames;
Alex Samuel committed
975 976 977 978 979 980 981 982 983 984 985 986 987
	}

      next = NEXT_INSN (insn);
    }
  while (insn != last);

  /* Step Two: Update the phi nodes of this block's successors.  */

  for (e = b->succ; e; e = e->succ_next)
    {
      if (e->dest == EXIT_BLOCK_PTR)
	continue;

988
      insn = first_insn_after_basic_block_note (e->dest);
Alex Samuel committed
989 990 991 992 993 994 995

      while (PHI_NODE_P (insn))
	{
	  rtx phi = PATTERN (insn);
	  rtx reg;

	  /* Find out which of our outgoing registers this node is
996
	     intended to replace.  Note that if this is not the first PHI
Alex Samuel committed
997 998 999 1000
	     node to have been created for this register, we have to
	     jump through rename links to figure out which register
	     we're talking about.  This can easily be recognized by
	     noting that the regno is new to this pass.  */
1001 1002 1003
	  reg = SET_DEST (phi);
	  if (REGNO (reg) >= ssa_max_reg_num)
	    reg = ssa_rename_from_lookup (REGNO (reg));
1004 1005
	  if (reg == NULL_RTX)
	    abort ();
1006
	  reg = ssa_rename_to_lookup (reg);
Alex Samuel committed
1007 1008 1009 1010 1011 1012

	  /* It is possible for the variable to be uninitialized on
	     edges in.  Reduce the arity of the PHI so that we don't
	     consider those edges.  */
	  if (reg == NULL || reg == RENAME_NO_RTX)
	    {
1013
	      if (! remove_phi_alternative (phi, b))
Alex Samuel committed
1014 1015 1016 1017 1018
		abort ();
	    }
	  else
	    {
	      /* When we created the PHI nodes, we did not know what mode
1019 1020
		 the register should be.  Now that we've found an original,
		 we can fill that in.  */
Alex Samuel committed
1021 1022 1023
	      if (GET_MODE (SET_DEST (phi)) == VOIDmode)
		PUT_MODE (SET_DEST (phi), GET_MODE (reg));
	      else if (GET_MODE (SET_DEST (phi)) != GET_MODE (reg))
1024
		abort ();
Alex Samuel committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

	      *phi_alternative (phi, bb) = reg;
	    }

	  insn = NEXT_INSN (insn);
	}
    }

  /* Step Three: Do the same to the children of this block in
     dominator order.  */

1036
  FOR_EACH_BB (c)
1037
    if (get_immediate_dominator (idom, c)->index == bb)
1038
      rename_block (c->index, idom);
Alex Samuel committed
1039

1040 1041
  /* Step Four: Update the sets to refer to their new register,
     and restore ssa_rename_to to its previous state.  */
Alex Samuel committed
1042 1043 1044 1045

  while (set_data)
    {
      struct rename_set_data *next;
Alex Samuel committed
1046 1047
      rtx old_reg = *set_data->reg_loc;

1048
      if (*set_data->reg_loc != set_data->old_reg)
Kazu Hirata committed
1049
	abort ();
Alex Samuel committed
1050
      *set_data->reg_loc = set_data->new_reg;
1051

1052
      ssa_rename_to_insert (old_reg, set_data->prev_reg);
Alex Samuel committed
1053 1054 1055 1056

      next = set_data->next;
      free (set_data);
      set_data = next;
Kazu Hirata committed
1057
    }
Alex Samuel committed
1058 1059 1060
}

static void
1061
rename_registers (int nregs, dominance_info idom)
Alex Samuel committed
1062 1063
{
  VARRAY_RTX_INIT (ssa_definition, nregs * 3, "ssa_definition");
1064
  ssa_rename_from_initialize ();
Alex Samuel committed
1065

1066 1067 1068 1069
  ssa_rename_to_pseudo = alloca (nregs * sizeof(rtx));
  memset (ssa_rename_to_pseudo, 0, nregs * sizeof(rtx));
  memset (ssa_rename_to_hard, 0,
	  FIRST_PSEUDO_REGISTER * NUM_MACHINE_MODES * sizeof (rtx));
Alex Samuel committed
1070 1071 1072

  rename_block (0, idom);

Kazu Hirata committed
1073
  /* ??? Update basic_block_live_at_start, and other flow info
Alex Samuel committed
1074 1075
     as needed.  */

1076
  ssa_rename_to_pseudo = NULL;
Alex Samuel committed
1077 1078 1079 1080 1081
}

/* The main entry point for moving to SSA.  */

void
1082
convert_to_ssa (void)
Alex Samuel committed
1083 1084 1085 1086 1087 1088 1089 1090 1091
{
  /* Element I is the set of blocks that set register I.  */
  sbitmap *evals;

  /* Dominator bitmaps.  */
  sbitmap *dfs;
  sbitmap *idfs;

  /* Element I is the immediate dominator of block I.  */
1092
  dominance_info idom;
Alex Samuel committed
1093 1094 1095

  int nregs;

1096 1097
  basic_block bb;

Alex Samuel committed
1098 1099 1100 1101
  /* Don't do it twice.  */
  if (in_ssa_form)
    abort ();

1102 1103 1104
  /* Need global_live_at_{start,end} up to date.  Do not remove any
     dead code.  We'll let the SSA optimizers do that.  */
  life_analysis (get_insns (), NULL, 0);
Alex Samuel committed
1105

1106
  idom = calculate_dominance_info (CDI_DOMINATORS);
Alex Samuel committed
1107 1108 1109 1110

  if (rtl_dump_file)
    {
      fputs (";; Immediate Dominators:\n", rtl_dump_file);
1111
      FOR_EACH_BB (bb)
1112 1113
	fprintf (rtl_dump_file, ";\t%3d = %3d\n", bb->index,
		 get_immediate_dominator (idom, bb)->index);
Alex Samuel committed
1114 1115 1116 1117 1118
      fflush (rtl_dump_file);
    }

  /* Compute dominance frontiers.  */

1119
  dfs = sbitmap_vector_alloc (last_basic_block, last_basic_block);
Alex Samuel committed
1120 1121 1122 1123 1124
  compute_dominance_frontiers (dfs, idom);

  if (rtl_dump_file)
    {
      dump_sbitmap_vector (rtl_dump_file, ";; Dominance Frontiers:",
1125
			   "; Basic Block", dfs, last_basic_block);
Alex Samuel committed
1126 1127 1128 1129 1130
      fflush (rtl_dump_file);
    }

  /* Compute register evaluations.  */

Kazu Hirata committed
1131
  ssa_max_reg_num = max_reg_num ();
1132
  nregs = ssa_max_reg_num;
1133
  evals = sbitmap_vector_alloc (nregs, last_basic_block);
Alex Samuel committed
1134 1135 1136 1137
  find_evaluations (evals, nregs);

  /* Compute the iterated dominance frontier for each register.  */

1138
  idfs = sbitmap_vector_alloc (nregs, last_basic_block);
Alex Samuel committed
1139 1140 1141 1142 1143
  compute_iterated_dominance_frontiers (idfs, dfs, evals, nregs);

  if (rtl_dump_file)
    {
      dump_sbitmap_vector (rtl_dump_file, ";; Iterated Dominance Frontiers:",
1144
			   "; Register", idfs, nregs);
Alex Samuel committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
      fflush (rtl_dump_file);
    }

  /* Insert the phi nodes.  */

  insert_phi_nodes (idfs, evals, nregs);

  /* Rename the registers to satisfy SSA.  */

  rename_registers (nregs, idom);

  /* All done!  Clean up and go home.  */

  sbitmap_vector_free (dfs);
  sbitmap_vector_free (evals);
  sbitmap_vector_free (idfs);
Alex Samuel committed
1161
  in_ssa_form = 1;
Alex Samuel committed
1162

Alex Samuel committed
1163
  reg_scan (get_insns (), max_reg_num (), 1);
1164
  free_dominance_info (idom);
Alex Samuel committed
1165
}
Alex Samuel committed
1166 1167 1168 1169 1170 1171

/* REG is the representative temporary of its partition.  Add it to the
   set of nodes to be processed, if it hasn't been already.  Return the
   index of this register in the node set.  */

static inline int
1172
ephi_add_node (rtx reg, rtx *nodes, int *n_nodes)
Alex Samuel committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
{
  int i;
  for (i = *n_nodes - 1; i >= 0; --i)
    if (REGNO (reg) == REGNO (nodes[i]))
      return i;

  nodes[i = (*n_nodes)++] = reg;
  return i;
}

/* Part one of the topological sort.  This is a forward (downward) search
   through the graph collecting a stack of nodes to process.  Assuming no
   cycles, the nodes at top of the stack when we are finished will have
1186
   no other dependencies.  */
Alex Samuel committed
1187 1188

static int *
1189
ephi_forward (int t, sbitmap visited, sbitmap *succ, int *tstack)
Alex Samuel committed
1190 1191 1192 1193 1194 1195 1196 1197
{
  int s;

  SET_BIT (visited, t);

  EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
    {
      if (! TEST_BIT (visited, s))
Kazu Hirata committed
1198
	tstack = ephi_forward (s, visited, succ, tstack);
Alex Samuel committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    });

  *tstack++ = t;
  return tstack;
}

/* Part two of the topological sort.  The is a backward search through
   a cycle in the graph, copying the data forward as we go.  */

static void
1209
ephi_backward (int t, sbitmap visited, sbitmap *pred, rtx *nodes)
Alex Samuel committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
{
  int p;

  SET_BIT (visited, t);

  EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
    {
      if (! TEST_BIT (visited, p))
	{
	  ephi_backward (p, visited, pred, nodes);
	  emit_move_insn (nodes[p], nodes[t]);
	}
    });
}

/* Part two of the topological sort.  Create the copy for a register
   and any cycle of which it is a member.  */

static void
1229
ephi_create (int t, sbitmap visited, sbitmap *pred, sbitmap *succ, rtx *nodes)
Alex Samuel committed
1230 1231 1232 1233 1234 1235
{
  rtx reg_u = NULL_RTX;
  int unvisited_predecessors = 0;
  int p;

  /* Iterate through the predecessor list looking for unvisited nodes.
Kazu Hirata committed
1236
     If there are any, we have a cycle, and must deal with that.  At
Alex Samuel committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
     the same time, look for a visited predecessor.  If there is one,
     we won't need to create a temporary.  */

  EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
    {
      if (! TEST_BIT (visited, p))
	unvisited_predecessors = 1;
      else if (!reg_u)
	reg_u = nodes[p];
    });

  if (unvisited_predecessors)
    {
      /* We found a cycle.  Copy out one element of the ring (if necessary),
	 then traverse the ring copying as we go.  */

      if (!reg_u)
	{
	  reg_u = gen_reg_rtx (GET_MODE (nodes[t]));
	  emit_move_insn (reg_u, nodes[t]);
	}

      EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
	{
	  if (! TEST_BIT (visited, p))
	    {
	      ephi_backward (p, visited, pred, nodes);
	      emit_move_insn (nodes[p], reg_u);
	    }
	});
Kazu Hirata committed
1267 1268
    }
  else
Alex Samuel committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    {
      /* No cycle.  Just copy the value from a successor.  */

      int s;
      EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
	{
	  SET_BIT (visited, t);
	  emit_move_insn (nodes[t], nodes[s]);
	  return;
	});
    }
}

/* Convert the edge to normal form.  */

static void
1285
eliminate_phi (edge e, partition reg_partition)
Alex Samuel committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
{
  int n_nodes;
  sbitmap *pred, *succ;
  sbitmap visited;
  rtx *nodes;
  int *stack, *tstack;
  rtx insn;
  int i;

  /* Collect an upper bound on the number of registers needing processing.  */

1297
  insn = first_insn_after_basic_block_note (e->dest);
Alex Samuel committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

  n_nodes = 0;
  while (PHI_NODE_P (insn))
    {
      insn = next_nonnote_insn (insn);
      n_nodes += 2;
    }

  if (n_nodes == 0)
    return;

Kazu Hirata committed
1309
  /* Build the auxiliary graph R(B).
Alex Samuel committed
1310 1311 1312 1313 1314

     The nodes of the graph are the members of the register partition
     present in Phi(B).  There is an edge from FIND(T0)->FIND(T1) for
     each T0 = PHI(...,T1,...), where T1 is for the edge from block C.  */

1315
  nodes = alloca (n_nodes * sizeof(rtx));
Alex Samuel committed
1316 1317 1318 1319 1320
  pred = sbitmap_vector_alloc (n_nodes, n_nodes);
  succ = sbitmap_vector_alloc (n_nodes, n_nodes);
  sbitmap_vector_zero (pred, n_nodes);
  sbitmap_vector_zero (succ, n_nodes);

1321
  insn = first_insn_after_basic_block_note (e->dest);
Alex Samuel committed
1322 1323 1324 1325

  n_nodes = 0;
  for (; PHI_NODE_P (insn); insn = next_nonnote_insn (insn))
    {
1326
      rtx* preg = phi_alternative (PATTERN (insn), e->src->index);
Alex Samuel committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
      rtx tgt = SET_DEST (PATTERN (insn));
      rtx reg;

      /* There may be no phi alternative corresponding to this edge.
	 This indicates that the phi variable is undefined along this
	 edge.  */
      if (preg == NULL)
	continue;
      reg = *preg;

      if (GET_CODE (reg) != REG || GET_CODE (tgt) != REG)
Kazu Hirata committed
1338
	abort ();
Alex Samuel committed
1339

Alex Samuel committed
1340 1341
      reg = regno_reg_rtx[partition_find (reg_partition, REGNO (reg))];
      tgt = regno_reg_rtx[partition_find (reg_partition, REGNO (tgt))];
Kazu Hirata committed
1342
      /* If the two registers are already in the same partition,
Alex Samuel committed
1343
	 nothing will need to be done.  */
Alex Samuel committed
1344
      if (reg != tgt)
Alex Samuel committed
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	{
	  int ireg, itgt;

	  ireg = ephi_add_node (reg, nodes, &n_nodes);
	  itgt = ephi_add_node (tgt, nodes, &n_nodes);

	  SET_BIT (pred[ireg], itgt);
	  SET_BIT (succ[itgt], ireg);
	}
    }

  if (n_nodes == 0)
    goto out;

  /* Begin a topological sort of the graph.  */

  visited = sbitmap_alloc (n_nodes);
  sbitmap_zero (visited);

1364
  tstack = stack = alloca (n_nodes * sizeof (int));
Alex Samuel committed
1365 1366 1367 1368 1369 1370 1371

  for (i = 0; i < n_nodes; ++i)
    if (! TEST_BIT (visited, i))
      tstack = ephi_forward (i, visited, succ, tstack);

  sbitmap_zero (visited);

Kazu Hirata committed
1372
  /* As we find a solution to the tsort, collect the implementation
Alex Samuel committed
1373 1374
     insns in a sequence.  */
  start_sequence ();
Kazu Hirata committed
1375

Alex Samuel committed
1376 1377 1378 1379 1380 1381 1382
  while (tstack != stack)
    {
      i = *--tstack;
      if (! TEST_BIT (visited, i))
	ephi_create (i, visited, pred, succ, nodes);
    }

1383
  insn = get_insns ();
Alex Samuel committed
1384 1385 1386 1387
  end_sequence ();
  insert_insn_on_edge (insn, e);
  if (rtl_dump_file)
    fprintf (rtl_dump_file, "Emitting copy on edge (%d,%d)\n",
1388
	     e->src->index, e->dest->index);
Alex Samuel committed
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

  sbitmap_free (visited);
out:
  sbitmap_vector_free (pred);
  sbitmap_vector_free (succ);
}

/* For basic block B, consider all phi insns which provide an
   alternative corresponding to an incoming abnormal critical edge.
   Place the phi alternative corresponding to that abnormal critical
Kazu Hirata committed
1399
   edge in the same register class as the destination of the set.
Alex Samuel committed
1400 1401 1402

   From Morgan, p. 178:

Kazu Hirata committed
1403 1404 1405 1406
     For each abnormal critical edge (C, B),
     if T0 = phi (T1, ..., Ti, ..., Tm) is a phi node in B,
     and C is the ith predecessor of B,
     then T0 and Ti must be equivalent.
Alex Samuel committed
1407

1408
   Return nonzero iff any such cases were found for which the two
Alex Samuel committed
1409 1410 1411
   regs were not already in the same class.  */

static int
1412
make_regs_equivalent_over_bad_edges (int bb, partition reg_partition)
Alex Samuel committed
1413 1414 1415
{
  int changed = 0;
  basic_block b = BASIC_BLOCK (bb);
1416
  rtx phi;
Alex Samuel committed
1417 1418

  /* Advance to the first phi node.  */
1419
  phi = first_insn_after_basic_block_note (b);
Alex Samuel committed
1420 1421

  /* Scan all the phi nodes.  */
Kazu Hirata committed
1422
  for (;
Alex Samuel committed
1423 1424 1425 1426 1427 1428 1429 1430
       PHI_NODE_P (phi);
       phi = next_nonnote_insn (phi))
    {
      edge e;
      int tgt_regno;
      rtx set = PATTERN (phi);
      rtx tgt = SET_DEST (set);

1431
      /* The set target is expected to be an SSA register.  */
Kazu Hirata committed
1432
      if (GET_CODE (tgt) != REG
1433
	  || !CONVERT_REGISTER_TO_SSA_P (REGNO (tgt)))
Alex Samuel committed
1434 1435 1436 1437 1438
	abort ();
      tgt_regno = REGNO (tgt);

      /* Scan incoming abnormal critical edges.  */
      for (e = b->pred; e; e = e->pred_next)
1439
	if ((e->flags & EDGE_ABNORMAL) && EDGE_CRITICAL_P (e))
Alex Samuel committed
1440
	  {
1441
	    rtx *alt = phi_alternative (set, e->src->index);
Alex Samuel committed
1442 1443 1444 1445 1446 1447 1448
	    int alt_regno;

	    /* If there is no alternative corresponding to this edge,
	       the value is undefined along the edge, so just go on.  */
	    if (alt == 0)
	      continue;

1449
	    /* The phi alternative is expected to be an SSA register.  */
Kazu Hirata committed
1450
	    if (GET_CODE (*alt) != REG
1451
		|| !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
Alex Samuel committed
1452 1453 1454 1455 1456
	      abort ();
	    alt_regno = REGNO (*alt);

	    /* If the set destination and the phi alternative aren't
	       already in the same class...  */
Kazu Hirata committed
1457
	    if (partition_find (reg_partition, tgt_regno)
Alex Samuel committed
1458 1459 1460
		!= partition_find (reg_partition, alt_regno))
	      {
		/* ... make them such.  */
1461 1462 1463 1464
		if (conflicting_hard_regs_p (tgt_regno, alt_regno))
		  /* It is illegal to unify a hard register with a
		     different register.  */
		  abort ();
Kazu Hirata committed
1465 1466

		partition_union (reg_partition,
Alex Samuel committed
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
				 tgt_regno, alt_regno);
		++changed;
	      }
	  }
    }

  return changed;
}

/* Consider phi insns in basic block BB pairwise.  If the set target
1477
   of both insns are equivalent pseudos, make the corresponding phi
Alex Samuel committed
1478 1479 1480 1481 1482
   alternatives in each phi corresponding equivalent.

   Return nonzero if any new register classes were unioned.  */

static int
1483
make_equivalent_phi_alternatives_equivalent (int bb, partition reg_partition)
Alex Samuel committed
1484 1485 1486
{
  int changed = 0;
  basic_block b = BASIC_BLOCK (bb);
1487
  rtx phi;
Alex Samuel committed
1488 1489

  /* Advance to the first phi node.  */
1490
  phi = first_insn_after_basic_block_note (b);
Alex Samuel committed
1491 1492

  /* Scan all the phi nodes.  */
Kazu Hirata committed
1493
  for (;
Alex Samuel committed
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
       PHI_NODE_P (phi);
       phi = next_nonnote_insn (phi))
    {
      rtx set = PATTERN (phi);
      /* The regno of the destination of the set.  */
      int tgt_regno = REGNO (SET_DEST (PATTERN (phi)));

      rtx phi2 = next_nonnote_insn (phi);

      /* Scan all phi nodes following this one.  */
      for (;
	   PHI_NODE_P (phi2);
	   phi2 = next_nonnote_insn (phi2))
	{
	  rtx set2 = PATTERN (phi2);
	  /* The regno of the destination of the set.  */
	  int tgt2_regno = REGNO (SET_DEST (set2));
Kazu Hirata committed
1511

Alex Samuel committed
1512 1513 1514 1515 1516 1517 1518 1519
	  /* Are the set destinations equivalent regs?  */
	  if (partition_find (reg_partition, tgt_regno) ==
	      partition_find (reg_partition, tgt2_regno))
	    {
	      edge e;
	      /* Scan over edges.  */
	      for (e = b->pred; e; e = e->pred_next)
		{
1520
		  int pred_block = e->src->index;
1521
		  /* Identify the phi alternatives from both phi
Alex Samuel committed
1522 1523 1524 1525 1526 1527 1528 1529 1530
		     nodes corresponding to this edge.  */
		  rtx *alt = phi_alternative (set, pred_block);
		  rtx *alt2 = phi_alternative (set2, pred_block);

		  /* If one of the phi nodes doesn't have a
		     corresponding alternative, just skip it.  */
		  if (alt == 0 || alt2 == 0)
		    continue;

1531
		  /* Both alternatives should be SSA registers.  */
Alex Samuel committed
1532
		  if (GET_CODE (*alt) != REG
1533
		      || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
Alex Samuel committed
1534 1535
		    abort ();
		  if (GET_CODE (*alt2) != REG
1536
		      || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt2)))
Alex Samuel committed
1537 1538
		    abort ();

1539
		  /* If the alternatives aren't already in the same
1540
		     class ...  */
Kazu Hirata committed
1541
		  if (partition_find (reg_partition, REGNO (*alt))
Alex Samuel committed
1542 1543 1544
		      != partition_find (reg_partition, REGNO (*alt2)))
		    {
		      /* ... make them so.  */
1545 1546
		      if (conflicting_hard_regs_p (REGNO (*alt), REGNO (*alt2)))
			/* It is illegal to unify a hard register with
1547
			   a different register.  */
1548 1549
			abort ();

Kazu Hirata committed
1550
		      partition_union (reg_partition,
Alex Samuel committed
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
				       REGNO (*alt), REGNO (*alt2));
		      ++changed;
		    }
		}
	    }
	}
    }

  return changed;
}

/* Compute a conservative partition of outstanding pseudo registers.
   See Morgan 7.3.1.  */

static partition
1566
compute_conservative_reg_partition (void)
Alex Samuel committed
1567
{
1568
  basic_block bb;
Alex Samuel committed
1569 1570 1571 1572 1573
  int changed = 0;

  /* We don't actually work with hard registers, but it's easier to
     carry them around anyway rather than constantly doing register
     number arithmetic.  */
Kazu Hirata committed
1574
  partition p =
1575
    partition_new (ssa_definition->num_elements);
Alex Samuel committed
1576 1577 1578 1579 1580

  /* The first priority is to make sure registers that might have to
     be copied on abnormal critical edges are placed in the same
     partition.  This saves us from having to split abnormal critical
     edges.  */
1581 1582
  FOR_EACH_BB_REVERSE (bb)
    changed += make_regs_equivalent_over_bad_edges (bb->index, p);
1583

Alex Samuel committed
1584 1585 1586 1587 1588 1589
  /* Now we have to insure that corresponding arguments of phi nodes
     assigning to corresponding regs are equivalent.  Iterate until
     nothing changes.  */
  while (changed > 0)
    {
      changed = 0;
1590 1591
      FOR_EACH_BB_REVERSE (bb)
	changed += make_equivalent_phi_alternatives_equivalent (bb->index, p);
Alex Samuel committed
1592 1593 1594 1595 1596
    }

  return p;
}

Alex Samuel committed
1597 1598 1599 1600 1601 1602 1603 1604 1605
/* The following functions compute a register partition that attempts
   to eliminate as many reg copies and phi node copies as possible by
   coalescing registers.   This is the strategy:

    1. As in the conservative case, the top priority is to coalesce
       registers that otherwise would cause copies to be placed on
       abnormal critical edges (which isn't possible).

    2. Figure out which regs are involved (in the LHS or RHS) of
Kazu Hirata committed
1606
       copies and phi nodes.  Compute conflicts among these regs.
Alex Samuel committed
1607 1608 1609 1610 1611

    3. Walk around the instruction stream, placing two regs in the
       same class of the partition if one appears on the LHS and the
       other on the RHS of a copy or phi node and the two regs don't
       conflict.  The conflict information of course needs to be
Kazu Hirata committed
1612
       updated.
Alex Samuel committed
1613 1614 1615 1616 1617 1618 1619

    4. If anything has changed, there may be new opportunities to
       coalesce regs, so go back to 2.
*/

/* If REG1 and REG2 don't conflict in CONFLICTS, place them in the
   same class of partition P, if they aren't already.  Update
Kazu Hirata committed
1620
   CONFLICTS appropriately.
Alex Samuel committed
1621 1622

   Returns one if REG1 and REG2 were placed in the same class but were
Kazu Hirata committed
1623
   not previously; zero otherwise.
Alex Samuel committed
1624 1625 1626

   See Morgan figure 11.15.  */

Kazu Hirata committed
1627
static int
1628 1629
coalesce_if_unconflicting (partition p, conflict_graph conflicts,
			   int reg1, int reg2)
Alex Samuel committed
1630 1631 1632
{
  int reg;

1633
  /* Work only on SSA registers.  */
1634
  if (!CONVERT_REGISTER_TO_SSA_P (reg1) || !CONVERT_REGISTER_TO_SSA_P (reg2))
Alex Samuel committed
1635 1636 1637 1638 1639 1640
    return 0;

  /* Find the canonical regs for the classes containing REG1 and
     REG2.  */
  reg1 = partition_find (p, reg1);
  reg2 = partition_find (p, reg2);
Kazu Hirata committed
1641

Alex Samuel committed
1642 1643 1644 1645 1646
  /* If they're already in the same class, there's nothing to do.  */
  if (reg1 == reg2)
    return 0;

  /* If the regs conflict, our hands are tied.  */
1647 1648
  if (conflicting_hard_regs_p (reg1, reg2) ||
      conflict_graph_conflict_p (conflicts, reg1, reg2))
Alex Samuel committed
1649 1650 1651 1652 1653 1654 1655
    return 0;

  /* We're good to go.  Put the regs in the same partition.  */
  partition_union (p, reg1, reg2);

  /* Find the new canonical reg for the merged class.  */
  reg = partition_find (p, reg1);
Kazu Hirata committed
1656

Alex Samuel committed
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
  /* Merge conflicts from the two previous classes.  */
  conflict_graph_merge_regs (conflicts, reg, reg1);
  conflict_graph_merge_regs (conflicts, reg, reg2);

  return 1;
}

/* For each register copy insn in basic block BB, place the LHS and
   RHS regs in the same class in partition P if they do not conflict
   according to CONFLICTS.

   Returns the number of changes that were made to P.

   See Morgan figure 11.14.  */

static int
1673
coalesce_regs_in_copies (basic_block bb, partition p, conflict_graph conflicts)
Alex Samuel committed
1674 1675 1676
{
  int changed = 0;
  rtx insn;
1677
  rtx end = bb->end;
Alex Samuel committed
1678 1679

  /* Scan the instruction stream of the block.  */
1680
  for (insn = bb->head; insn != end; insn = NEXT_INSN (insn))
Alex Samuel committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    {
      rtx pattern;
      rtx src;
      rtx dest;

      /* If this isn't a set insn, go to the next insn.  */
      if (GET_CODE (insn) != INSN)
	continue;
      pattern = PATTERN (insn);
      if (GET_CODE (pattern) != SET)
	continue;

      src = SET_SRC (pattern);
      dest = SET_DEST (pattern);

      /* We're only looking for copies.  */
      if (GET_CODE (src) != REG || GET_CODE (dest) != REG)
	continue;

      /* Coalesce only if the reg modes are the same.  As long as
	 each reg's rtx is unique, it can have only one mode, so two
Kazu Hirata committed
1702
	 pseudos of different modes can't be coalesced into one.
Alex Samuel committed
1703 1704 1705 1706 1707 1708 1709 1710 1711

         FIXME: We can probably get around this by inserting SUBREGs
         where appropriate, but for now we don't bother.  */
      if (GET_MODE (src) != GET_MODE (dest))
	continue;

      /* Found a copy; see if we can use the same reg for both the
	 source and destination (and thus eliminate the copy,
	 ultimately).  */
Kazu Hirata committed
1712
      changed += coalesce_if_unconflicting (p, conflicts,
Alex Samuel committed
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
					    REGNO (src), REGNO (dest));
    }

  return changed;
}

struct phi_coalesce_context
{
  partition p;
  conflict_graph conflicts;
  int changed;
};

/* Callback function for for_each_successor_phi.  If the set
   destination and the phi alternative regs do not conflict, place
1728
   them in the same partition class.  DATA is a pointer to a
Alex Samuel committed
1729 1730 1731
   phi_coalesce_context struct.  */

static int
1732 1733
coalesce_reg_in_phi (rtx insn ATTRIBUTE_UNUSED, int dest_regno,
		     int src_regno, void *data)
Alex Samuel committed
1734
{
Kazu Hirata committed
1735
  struct phi_coalesce_context *context =
Alex Samuel committed
1736
    (struct phi_coalesce_context *) data;
Kazu Hirata committed
1737

Alex Samuel committed
1738
  /* Attempt to use the same reg, if they don't conflict.  */
Kazu Hirata committed
1739 1740
  context->changed
    += coalesce_if_unconflicting (context->p, context->conflicts,
Alex Samuel committed
1741 1742 1743 1744 1745 1746 1747
				  dest_regno, src_regno);
  return 0;
}

/* For each alternative in a phi function corresponding to basic block
   BB (in phi nodes in successor block to BB), place the reg in the
   phi alternative and the reg to which the phi value is set into the
Kazu Hirata committed
1748
   same class in partition P, if allowed by CONFLICTS.
Alex Samuel committed
1749 1750

   Return the number of changes that were made to P.
Kazu Hirata committed
1751

Alex Samuel committed
1752 1753 1754
   See Morgan figure 11.14.  */

static int
1755 1756
coalesce_regs_in_successor_phi_nodes (basic_block bb, partition p,
				      conflict_graph conflicts)
Alex Samuel committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
{
  struct phi_coalesce_context context;
  context.p = p;
  context.conflicts = conflicts;
  context.changed = 0;

  for_each_successor_phi (bb, &coalesce_reg_in_phi, &context);

  return context.changed;
}

/* Compute and return a partition of pseudos.  Where possible,
Kazu Hirata committed
1769
   non-conflicting pseudos are placed in the same class.
Alex Samuel committed
1770 1771 1772 1773

   The caller is responsible for deallocating the returned partition.  */

static partition
1774
compute_coalesced_reg_partition (void)
Alex Samuel committed
1775
{
1776
  basic_block bb;
Alex Samuel committed
1777
  int changed = 0;
1778 1779
  regset_head phi_set_head;
  regset phi_set = &phi_set_head;
Alex Samuel committed
1780

Kazu Hirata committed
1781
  partition p =
1782
    partition_new (ssa_definition->num_elements);
Alex Samuel committed
1783 1784 1785 1786 1787

  /* The first priority is to make sure registers that might have to
     be copied on abnormal critical edges are placed in the same
     partition.  This saves us from having to split abnormal critical
     edges (which can't be done).  */
1788 1789
  FOR_EACH_BB_REVERSE (bb)
    make_regs_equivalent_over_bad_edges (bb->index, p);
Alex Samuel committed
1790

1791 1792
  INIT_REG_SET (phi_set);

Alex Samuel committed
1793 1794 1795 1796 1797 1798 1799 1800
  do
    {
      conflict_graph conflicts;

      changed = 0;

      /* Build the set of registers involved in phi nodes, either as
	 arguments to the phi function or as the target of a set.  */
1801 1802
      CLEAR_REG_SET (phi_set);
      mark_phi_and_copy_regs (phi_set);
Alex Samuel committed
1803 1804

      /* Compute conflicts.  */
1805
      conflicts = conflict_graph_compute (phi_set, p);
Alex Samuel committed
1806 1807 1808 1809 1810

      /* FIXME: Better would be to process most frequently executed
	 blocks first, so that most frequently executed copies would
	 be more likely to be removed by register coalescing.  But any
	 order will generate correct, if non-optimal, results.  */
1811
      FOR_EACH_BB_REVERSE (bb)
Alex Samuel committed
1812
	{
1813
	  changed += coalesce_regs_in_copies (bb, p, conflicts);
1814
	  changed +=
1815
	    coalesce_regs_in_successor_phi_nodes (bb, p, conflicts);
Alex Samuel committed
1816 1817 1818 1819 1820 1821
	}

      conflict_graph_delete (conflicts);
    }
  while (changed > 0);

1822 1823
  FREE_REG_SET (phi_set);

Alex Samuel committed
1824 1825 1826 1827 1828 1829 1830 1831
  return p;
}

/* Mark the regs in a phi node.  PTR is a phi expression or one of its
   components (a REG or a CONST_INT).  DATA is a reg set in which to
   set all regs.  Called from for_each_rtx.  */

static int
1832
mark_reg_in_phi (rtx *ptr, void *data)
Alex Samuel committed
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
{
  rtx expr = *ptr;
  regset set = (regset) data;

  switch (GET_CODE (expr))
    {
    case REG:
      SET_REGNO_REG_SET (set, REGNO (expr));
      /* Fall through.  */
    case CONST_INT:
    case PHI:
      return 0;
    default:
      abort ();
    }
}

/* Mark in PHI_SET all pseudos that are used in a phi node -- either
   set from a phi expression, or used as an argument in one.  Also
   mark regs that are the source or target of a reg copy.  Uses
   ssa_definition.  */

static void
1856
mark_phi_and_copy_regs (regset phi_set)
Alex Samuel committed
1857
{
1858
  unsigned int reg;
Alex Samuel committed
1859 1860

  /* Scan the definitions of all regs.  */
1861 1862 1863 1864 1865 1866 1867
  for (reg = 0; reg < VARRAY_SIZE (ssa_definition); ++reg)
    if (CONVERT_REGISTER_TO_SSA_P (reg))
      {
	rtx insn = VARRAY_RTX (ssa_definition, reg);
	rtx pattern;
	rtx src;

1868 1869 1870
	if (insn == NULL
	    || (GET_CODE (insn) == NOTE
		&& NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED))
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
	  continue;
	pattern = PATTERN (insn);
	/* Sometimes we get PARALLEL insns.  These aren't phi nodes or
	   copies.  */
	if (GET_CODE (pattern) != SET)
	  continue;
	src = SET_SRC (pattern);

	if (GET_CODE (src) == REG)
	  {
	    /* It's a reg copy.  */
	    SET_REGNO_REG_SET (phi_set, reg);
	    SET_REGNO_REG_SET (phi_set, REGNO (src));
	  }
	else if (GET_CODE (src) == PHI)
	  {
	    /* It's a phi node.  Mark the reg being set.  */
	    SET_REGNO_REG_SET (phi_set, reg);
	    /* Mark the regs used in the phi function.  */
	    for_each_rtx (&src, mark_reg_in_phi, phi_set);
	  }
	/* ... else nothing to do.  */
      }
Alex Samuel committed
1894
}
Alex Samuel committed
1895 1896 1897 1898 1899

/* Rename regs in insn PTR that are equivalent.  DATA is the register
   partition which specifies equivalences.  */

static int
1900
rename_equivalent_regs_in_insn (rtx *ptr, void* data)
Alex Samuel committed
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
{
  rtx x = *ptr;
  partition reg_partition = (partition) data;

  if (x == NULL_RTX)
    return 0;

  switch (GET_CODE (x))
    {
    case REG:
1911
      if (CONVERT_REGISTER_TO_SSA_P (REGNO (x)))
Alex Samuel committed
1912
	{
1913 1914 1915 1916
	  unsigned int regno = REGNO (x);
	  unsigned int new_regno = partition_find (reg_partition, regno);
	  rtx canonical_element_rtx = ssa_rename_from_lookup (new_regno);

Kazu Hirata committed
1917
	  if (canonical_element_rtx != NULL_RTX &&
1918 1919 1920 1921 1922 1923
	      HARD_REGISTER_P (canonical_element_rtx))
	    {
	      if (REGNO (canonical_element_rtx) != regno)
		*ptr = canonical_element_rtx;
	    }
	  else if (regno != new_regno)
Alex Samuel committed
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
	    {
	      rtx new_reg = regno_reg_rtx[new_regno];
	      if (GET_MODE (x) != GET_MODE (new_reg))
		abort ();
	      *ptr = new_reg;
	    }
	}
      return -1;

    case PHI:
      /* No need to rename the phi nodes.  We'll check equivalence
	 when inserting copies.  */
      return -1;

    default:
      /* Anything else, continue traversing.  */
      return 0;
    }
}

1944 1945 1946 1947 1948
/* Record the register's canonical element stored in SRFP in the
   canonical_elements sbitmap packaged in DATA.  This function is used
   as a callback function for traversing ssa_rename_from.  */

static int
1949
record_canonical_element_1 (void **srfp, void *data)
1950 1951 1952 1953 1954 1955
{
  unsigned int reg = ((ssa_rename_from_pair *) *srfp)->reg;
  sbitmap canonical_elements =
    ((struct ssa_rename_from_hash_table_data *) data)->canonical_elements;
  partition reg_partition =
    ((struct ssa_rename_from_hash_table_data *) data)->reg_partition;
Kazu Hirata committed
1956

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
  SET_BIT (canonical_elements, partition_find (reg_partition, reg));
  return 1;
}

/* For each class in the REG_PARTITION corresponding to a particular
   hard register and machine mode, check that there are no other
   classes with the same hard register and machine mode.  Returns
   nonzero if this is the case, i.e., the partition is acceptable.  */

static int
1967
check_hard_regs_in_partition (partition reg_partition)
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
{
  /* CANONICAL_ELEMENTS has a nonzero bit if a class with the given register
     number and machine mode has already been seen.  This is a
     problem with the partition.  */
  sbitmap canonical_elements;
  int element_index;
  int already_seen[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];
  int reg;
  int mach_mode;

  /* Collect a list of canonical elements.  */
  canonical_elements = sbitmap_alloc (max_reg_num ());
  sbitmap_zero (canonical_elements);
  ssa_rename_from_traverse (&record_canonical_element_1,
			    canonical_elements, reg_partition);

  /* We have not seen any hard register uses.  */
  for (reg = 0; reg < FIRST_PSEUDO_REGISTER; ++reg)
    for (mach_mode = 0; mach_mode < NUM_MACHINE_MODES; ++mach_mode)
      already_seen[reg][mach_mode] = 0;

  /* Check for classes with the same hard register and machine mode.  */
  EXECUTE_IF_SET_IN_SBITMAP (canonical_elements, 0, element_index,
  {
    rtx hard_reg_rtx = ssa_rename_from_lookup (element_index);
    if (hard_reg_rtx != NULL_RTX &&
	HARD_REGISTER_P (hard_reg_rtx) &&
	already_seen[REGNO (hard_reg_rtx)][GET_MODE (hard_reg_rtx)] != 0)
	  /* Two distinct partition classes should be mapped to the same
	     hard register.  */
	  return 0;
  });

  sbitmap_free (canonical_elements);

  return 1;
}

/* Rename regs that are equivalent in REG_PARTITION.  Also collapse
   any SEQUENCE insns.  */
Alex Samuel committed
2008 2009

static void
2010
rename_equivalent_regs (partition reg_partition)
Alex Samuel committed
2011
{
2012
  basic_block b;
Alex Samuel committed
2013

2014
  FOR_EACH_BB_REVERSE (b)
Alex Samuel committed
2015 2016 2017 2018 2019 2020 2021 2022
    {
      rtx next = b->head;
      rtx last = b->end;
      rtx insn;

      do
	{
	  insn = next;
2023
	  if (INSN_P (insn))
Alex Samuel committed
2024
	    {
Kazu Hirata committed
2025 2026
	      for_each_rtx (&PATTERN (insn),
			    rename_equivalent_regs_in_insn,
Alex Samuel committed
2027
			    reg_partition);
Kazu Hirata committed
2028 2029
	      for_each_rtx (&REG_NOTES (insn),
			    rename_equivalent_regs_in_insn,
Alex Samuel committed
2030
			    reg_partition);
2031 2032 2033 2034 2035 2036 2037 2038

	      if (GET_CODE (PATTERN (insn)) == SEQUENCE)
		{
		  rtx s = PATTERN (insn);
		  int slen = XVECLEN (s, 0);
		  int i;

		  if (slen <= 1)
Kazu Hirata committed
2039
		    abort ();
2040

2041
		  PATTERN (insn) = XVECEXP (s, 0, slen-1);
2042
		  for (i = 0; i < slen - 1; i++)
2043
		    emit_insn_before (XVECEXP (s, 0, i), insn);
2044
		}
Alex Samuel committed
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
	    }

	  next = NEXT_INSN (insn);
	}
      while (insn != last);
    }
}

/* The main entry point for moving from SSA.  */

void
2056
convert_from_ssa (void)
Alex Samuel committed
2057
{
2058
  basic_block b, bb;
Alex Samuel committed
2059
  partition reg_partition;
Alex Samuel committed
2060
  rtx insns = get_insns ();
2061

2062 2063
  /* Need global_live_at_{start,end} up to date.  There should not be
     any significant dead code at this point, except perhaps dead
Kazu Hirata committed
2064
     stores.  So do not take the time to perform dead code elimination.
2065

2066 2067
     Register coalescing needs death notes, so generate them.  */
  life_analysis (insns, NULL, PROP_DEATH_NOTES);
Alex Samuel committed
2068 2069 2070 2071 2072 2073 2074 2075

  /* Figure out which regs in copies and phi nodes don't conflict and
     therefore can be coalesced.  */
  if (conservative_reg_partition)
    reg_partition = compute_conservative_reg_partition ();
  else
    reg_partition = compute_coalesced_reg_partition ();

2076 2077 2078 2079 2080
  if (!check_hard_regs_in_partition (reg_partition))
    /* Two separate partitions should correspond to the same hard
       register but do not.  */
    abort ();

Alex Samuel committed
2081 2082 2083
  rename_equivalent_regs (reg_partition);

  /* Eliminate the PHI nodes.  */
2084
  FOR_EACH_BB_REVERSE (b)
Alex Samuel committed
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
    {
      edge e;

      for (e = b->pred; e; e = e->pred_next)
	if (e->src != ENTRY_BLOCK_PTR)
	  eliminate_phi (e, reg_partition);
    }

  partition_delete (reg_partition);

  /* Actually delete the PHI nodes.  */
2096
  FOR_EACH_BB_REVERSE (bb)
Alex Samuel committed
2097
    {
2098
      rtx insn = bb->head;
Alex Samuel committed
2099

2100
      while (1)
Alex Samuel committed
2101
	{
2102 2103 2104
	  /* If this is a PHI node delete it.  */
	  if (PHI_NODE_P (insn))
	    {
2105 2106
	      if (insn == bb->end)
		bb->end = PREV_INSN (insn);
2107
	      insn = delete_insn (insn);
2108 2109 2110 2111 2112 2113 2114
	    }
	  /* Since all the phi nodes come at the beginning of the
	     block, if we find an ordinary insn, we can stop looking
	     for more phi nodes.  */
	  else if (INSN_P (insn))
	    break;
	  /* If we've reached the end of the block, stop.  */
2115
	  else if (insn == bb->end)
2116
	    break;
Kazu Hirata committed
2117
	  else
2118
	    insn = NEXT_INSN (insn);
Alex Samuel committed
2119 2120 2121 2122 2123 2124
	}
    }

  /* Commit all the copy nodes needed to convert out of SSA form.  */
  commit_edge_insertions ();

Alex Samuel committed
2125 2126
  in_ssa_form = 0;

Alex Samuel committed
2127
  count_or_remove_death_notes (NULL, 1);
2128 2129

  /* Deallocate the data structures.  */
2130
  ssa_definition = 0;
2131
  ssa_rename_from_free ();
Alex Samuel committed
2132
}
Alex Samuel committed
2133 2134 2135 2136 2137 2138 2139

/* Scan phi nodes in successors to BB.  For each such phi node that
   has a phi alternative value corresponding to BB, invoke FN.  FN
   is passed the entire phi node insn, the regno of the set
   destination, the regno of the phi argument corresponding to BB,
   and DATA.

2140
   If FN ever returns nonzero, stops immediately and returns this
Alex Samuel committed
2141 2142 2143
   value.  Otherwise, returns zero.  */

int
2144
for_each_successor_phi (basic_block bb, successor_phi_fn fn, void *data)
Alex Samuel committed
2145 2146
{
  edge e;
Kazu Hirata committed
2147

2148
  if (bb == EXIT_BLOCK_PTR)
Alex Samuel committed
2149 2150 2151
    return 0;

  /* Scan outgoing edges.  */
2152
  for (e = bb->succ; e != NULL; e = e->succ_next)
Alex Samuel committed
2153 2154 2155 2156
    {
      rtx insn;

      basic_block successor = e->dest;
Kazu Hirata committed
2157
      if (successor == ENTRY_BLOCK_PTR
2158
	  || successor == EXIT_BLOCK_PTR)
Alex Samuel committed
2159 2160 2161
	continue;

      /* Advance to the first non-label insn of the successor block.  */
2162
      insn = first_insn_after_basic_block_note (successor);
Alex Samuel committed
2163 2164 2165 2166 2167 2168 2169 2170 2171

      if (insn == NULL)
	continue;

      /* Scan phi nodes in the successor.  */
      for ( ; PHI_NODE_P (insn); insn = NEXT_INSN (insn))
	{
	  int result;
	  rtx phi_set = PATTERN (insn);
2172
	  rtx *alternative = phi_alternative (phi_set, bb->index);
Alex Samuel committed
2173
	  rtx phi_src;
Kazu Hirata committed
2174

Alex Samuel committed
2175 2176 2177 2178 2179 2180 2181 2182
	  /* This phi function may not have an alternative
	     corresponding to the incoming edge, indicating the
	     assigned variable is not defined along the edge.  */
	  if (alternative == NULL)
	    continue;
	  phi_src = *alternative;

	  /* Invoke the callback.  */
Kazu Hirata committed
2183
	  result = (*fn) (insn, REGNO (SET_DEST (phi_set)),
Alex Samuel committed
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
			  REGNO (phi_src), data);

	  /* Terminate if requested.  */
	  if (result != 0)
	    return result;
	}
    }

  return 0;
}
2194 2195 2196 2197 2198 2199 2200

/* Assuming the ssa_rename_from mapping has been established, yields
   nonzero if 1) only one SSA register of REG1 and REG2 comes from a
   hard register or 2) both SSA registers REG1 and REG2 come from
   different hard registers.  */

static int
2201
conflicting_hard_regs_p (int reg1, int reg2)
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
{
  int orig_reg1 = original_register (reg1);
  int orig_reg2 = original_register (reg2);
  if (HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2)
      && orig_reg1 != orig_reg2)
    return 1;
  if (HARD_REGISTER_NUM_P (orig_reg1) && !HARD_REGISTER_NUM_P (orig_reg2))
    return 1;
  if (!HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2))
    return 1;
Kazu Hirata committed
2212

2213 2214
  return 0;
}