OSDN Git Service

* config/darwin.h (REGISTER_TARGET_PRAGMAS): Define.
[pf3gnuchains/gcc-fork.git] / gcc / ssa.c
1 /* Static Single Assignment conversion routines for the GNU compiler.
2    Copyright (C) 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 GNU CC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 /* References:
22
23    Building an Optimizing Compiler
24    Robert Morgan
25    Butterworth-Heinemann, 1998
26
27    Static Single Assignment Construction
28    Preston Briggs, Tim Harvey, Taylor Simpson
29    Technical Report, Rice University, 1995
30    ftp://ftp.cs.rice.edu/public/preston/optimizer/SSA.ps.gz.  */
31
32 #include "config.h"
33 #include "system.h"
34
35 #include "rtl.h"
36 #include "expr.h"
37 #include "varray.h"
38 #include "partition.h"
39 #include "sbitmap.h"
40 #include "hashtab.h"
41 #include "regs.h"
42 #include "hard-reg-set.h"
43 #include "flags.h"
44 #include "function.h"
45 #include "real.h"
46 #include "insn-config.h"
47 #include "recog.h"
48 #include "basic-block.h"
49 #include "output.h"
50 #include "ssa.h"
51
52 /* TODO: 
53
54    Handle subregs better, maybe.  For now, if a reg that's set in a
55    subreg expression is duplicated going into SSA form, an extra copy
56    is inserted first that copies the entire reg into the duplicate, so
57    that the other bits are preserved.  This isn't strictly SSA, since
58    at least part of the reg is assigned in more than one place (though
59    they are adjacent).
60
61    ??? What to do about strict_low_part.  Probably I'll have to split
62    them out of their current instructions first thing.
63
64    Actually the best solution may be to have a kind of "mid-level rtl"
65    in which the RTL encodes exactly what we want, without exposing a
66    lot of niggling processor details.  At some later point we lower
67    the representation, calling back into optabs to finish any necessary
68    expansion.  */
69
70 /* All pseudo-registers and select hard registers are converted to SSA
71    form.  When converting out of SSA, these select hard registers are
72    guaranteed to be mapped to their original register number.  Each
73    machine's .h file should define CONVERT_HARD_REGISTER_TO_SSA_P
74    indicating which hard registers should be converted.
75
76    When converting out of SSA, temporaries for all registers are
77    partitioned.  The partition is checked to ensure that all uses of
78    the same hard register in the same machine mode are in the same
79    class.  */
80
81 /* If conservative_reg_partition is non-zero, use a conservative
82    register partitioning algorithm (which leaves more regs after
83    emerging from SSA) instead of the coalescing one.  This is being
84    left in for a limited time only, as a debugging tool until the
85    coalescing algorithm is validated.  */
86
87 static int conservative_reg_partition;
88
89 /* This flag is set when the CFG is in SSA form.  */
90 int in_ssa_form = 0;
91
92 /* Element I is the single instruction that sets register I.  */
93 varray_type ssa_definition;
94
95 /* Element I-PSEUDO is the normal register that originated the ssa
96    register in question.  */
97 varray_type ssa_rename_from;
98
99 /* Element I is the normal register that originated the ssa
100    register in question.
101
102    A hash table stores the (register, rtl) pairs.  These are each
103    xmalloc'ed and deleted when the hash table is destroyed.  */
104 htab_t ssa_rename_from_ht;
105
106 /* The running target ssa register for a given pseudo register.
107    (Pseudo registers appear in only one mode.)  */
108 static rtx *ssa_rename_to_pseudo;
109 /* Similar, but for hard registers.  A hard register can appear in
110    many modes, so we store an equivalent pseudo for each of the
111    modes.  */
112 static rtx ssa_rename_to_hard[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];
113
114 /* ssa_rename_from maps pseudo registers to the original corresponding
115    RTL.  It is implemented as using a hash table.  */
116
117 typedef struct {
118   unsigned int reg;
119   rtx original;
120 } ssa_rename_from_pair;
121
122 struct ssa_rename_from_hash_table_data {
123   sbitmap canonical_elements;
124   partition reg_partition;
125 };
126
127 static void ssa_rename_from_initialize
128   PARAMS ((void));
129 static rtx ssa_rename_from_lookup
130   PARAMS ((int reg));
131 static unsigned int original_register
132   PARAMS ((unsigned int regno));
133 static void ssa_rename_from_insert
134   PARAMS ((unsigned int reg, rtx r));
135 static void ssa_rename_from_free
136   PARAMS ((void));
137 typedef int (*srf_trav) PARAMS ((int regno, rtx r, sbitmap canonical_elements, partition reg_partition));
138 static void ssa_rename_from_traverse
139   PARAMS ((htab_trav callback_function, sbitmap canonical_elements, partition reg_partition));
140 /*static Avoid warnign message.  */ void ssa_rename_from_print
141   PARAMS ((void));
142 static int ssa_rename_from_print_1
143   PARAMS ((void **slot, void *data));
144 static hashval_t ssa_rename_from_hash_function
145   PARAMS ((const void * srfp));
146 static int ssa_rename_from_equal
147   PARAMS ((const void *srfp1, const void *srfp2));
148 static void ssa_rename_from_delete
149   PARAMS ((void *srfp));
150
151 static rtx ssa_rename_to_lookup
152   PARAMS ((rtx reg));
153 static void ssa_rename_to_insert
154   PARAMS ((rtx reg, rtx r));
155
156 /* The number of registers that were live on entry to the SSA routines.  */
157 static unsigned int ssa_max_reg_num;
158
159 /* Local function prototypes.  */
160
161 struct rename_context;
162
163 static inline rtx * phi_alternative
164   PARAMS ((rtx, int));
165 static rtx first_insn_after_basic_block_note
166   PARAMS ((basic_block));
167 static void compute_dominance_frontiers_1
168   PARAMS ((sbitmap *frontiers, int *idom, int bb, sbitmap done));
169 static void find_evaluations_1
170   PARAMS ((rtx dest, rtx set, void *data));
171 static void find_evaluations
172   PARAMS ((sbitmap *evals, int nregs));
173 static void compute_iterated_dominance_frontiers
174   PARAMS ((sbitmap *idfs, sbitmap *frontiers, sbitmap *evals, int nregs));
175 static void insert_phi_node
176   PARAMS ((int regno, int b));
177 static void insert_phi_nodes
178   PARAMS ((sbitmap *idfs, sbitmap *evals, int nregs));
179 static void create_delayed_rename 
180   PARAMS ((struct rename_context *, rtx *));
181 static void apply_delayed_renames 
182   PARAMS ((struct rename_context *));
183 static int rename_insn_1 
184   PARAMS ((rtx *ptr, void *data));
185 static void rename_block 
186   PARAMS ((int b, int *idom));
187 static void rename_registers 
188   PARAMS ((int nregs, int *idom));
189
190 static inline int ephi_add_node
191   PARAMS ((rtx reg, rtx *nodes, int *n_nodes));
192 static int * ephi_forward
193   PARAMS ((int t, sbitmap visited, sbitmap *succ, int *tstack));
194 static void ephi_backward
195   PARAMS ((int t, sbitmap visited, sbitmap *pred, rtx *nodes));
196 static void ephi_create
197   PARAMS ((int t, sbitmap visited, sbitmap *pred, sbitmap *succ, rtx *nodes));
198 static void eliminate_phi
199   PARAMS ((edge e, partition reg_partition));
200 static int make_regs_equivalent_over_bad_edges 
201   PARAMS ((int bb, partition reg_partition));
202
203 /* These are used only in the conservative register partitioning
204    algorithms.  */
205 static int make_equivalent_phi_alternatives_equivalent 
206   PARAMS ((int bb, partition reg_partition));
207 static partition compute_conservative_reg_partition 
208   PARAMS ((void));
209 static int record_canonical_element_1
210   PARAMS ((void **srfp, void *data));
211 static int check_hard_regs_in_partition
212   PARAMS ((partition reg_partition));
213 static int rename_equivalent_regs_in_insn 
214   PARAMS ((rtx *ptr, void *data));
215
216 /* These are used in the register coalescing algorithm.  */
217 static int coalesce_if_unconflicting
218   PARAMS ((partition p, conflict_graph conflicts, int reg1, int reg2));
219 static int coalesce_regs_in_copies
220   PARAMS ((basic_block bb, partition p, conflict_graph conflicts));
221 static int coalesce_reg_in_phi
222   PARAMS ((rtx, int dest_regno, int src_regno, void *data));
223 static int coalesce_regs_in_successor_phi_nodes
224   PARAMS ((basic_block bb, partition p, conflict_graph conflicts));
225 static partition compute_coalesced_reg_partition
226   PARAMS ((void));
227 static int mark_reg_in_phi 
228   PARAMS ((rtx *ptr, void *data));
229 static void mark_phi_and_copy_regs
230   PARAMS ((regset phi_set));
231
232 static int rename_equivalent_regs_in_insn 
233   PARAMS ((rtx *ptr, void *data));
234 static void rename_equivalent_regs 
235   PARAMS ((partition reg_partition));
236
237 /* Deal with hard registers.  */
238 static int conflicting_hard_regs_p
239   PARAMS ((int reg1, int reg2));
240
241 /* ssa_rename_to maps registers and machine modes to SSA pseudo registers.  */
242
243 /* Find the register associated with REG in the indicated mode.  */
244
245 static rtx
246 ssa_rename_to_lookup (reg)
247      rtx reg;
248 {
249   if (!HARD_REGISTER_P (reg))
250     return ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER];
251   else
252     return ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)];
253 }
254
255 /* Store a new value mapping REG to R in ssa_rename_to.  */
256
257 static void
258 ssa_rename_to_insert(reg, r)
259      rtx reg;
260      rtx r;
261 {
262   if (!HARD_REGISTER_P (reg))
263     ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER] = r;
264   else
265     ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)] = r;
266 }
267
268 /* Prepare ssa_rename_from for use.  */
269
270 static void
271 ssa_rename_from_initialize ()
272 {
273   /* We use an arbitrary initial hash table size of 64.  */
274   ssa_rename_from_ht = htab_create (64,
275                                     &ssa_rename_from_hash_function,
276                                     &ssa_rename_from_equal,
277                                     &ssa_rename_from_delete);
278 }
279
280 /* Find the REG entry in ssa_rename_from.  Return NULL_RTX if no entry is
281    found.  */
282
283 static rtx
284 ssa_rename_from_lookup (reg)
285      int reg;
286 {
287   ssa_rename_from_pair srfp;
288   ssa_rename_from_pair *answer;
289   srfp.reg = reg;
290   srfp.original = NULL_RTX;
291   answer = (ssa_rename_from_pair *)
292     htab_find_with_hash (ssa_rename_from_ht, (void *) &srfp, reg);
293   return (answer == 0 ? NULL_RTX : answer->original);
294 }
295
296 /* Find the number of the original register specified by REGNO.  If
297    the register is a pseudo, return the original register's number.
298    Otherwise, return this register number REGNO.  */
299
300 static unsigned int
301 original_register (regno)
302      unsigned int regno;
303 {
304   rtx original_rtx = ssa_rename_from_lookup (regno);
305   return original_rtx != NULL_RTX ? REGNO (original_rtx) : regno;
306 }
307
308 /* Add mapping from R to REG to ssa_rename_from even if already present.  */
309
310 static void
311 ssa_rename_from_insert (reg, r)
312      unsigned int reg;
313      rtx r;
314 {
315   void **slot;
316   ssa_rename_from_pair *srfp = xmalloc (sizeof (ssa_rename_from_pair));
317   srfp->reg = reg;
318   srfp->original = r;
319   slot = htab_find_slot_with_hash (ssa_rename_from_ht, (const void *) srfp,
320                                    reg, INSERT);
321   if (*slot != 0)
322     free ((void *) *slot);
323   *slot = srfp;
324 }
325
326 /* Apply the CALLBACK_FUNCTION to each element in ssa_rename_from.
327    CANONICAL_ELEMENTS and REG_PARTITION pass data needed by the only
328    current use of this function.  */
329
330 static void
331 ssa_rename_from_traverse (callback_function,
332                           canonical_elements, reg_partition)
333      htab_trav callback_function;
334      sbitmap canonical_elements;
335      partition reg_partition;
336 {
337   struct ssa_rename_from_hash_table_data srfhd;
338   srfhd.canonical_elements = canonical_elements;
339   srfhd.reg_partition = reg_partition;
340   htab_traverse (ssa_rename_from_ht, callback_function, (void *) &srfhd);
341 }
342
343 /* Destroy ssa_rename_from.  */
344
345 static void
346 ssa_rename_from_free ()
347 {
348   htab_delete (ssa_rename_from_ht);
349 }
350
351 /* Print the contents of ssa_rename_from.  */
352
353 /* static  Avoid erroneous error message.  */
354 void
355 ssa_rename_from_print ()
356 {
357   printf ("ssa_rename_from's hash table contents:\n");
358   htab_traverse (ssa_rename_from_ht, &ssa_rename_from_print_1, NULL);
359 }
360
361 /* Print the contents of the hash table entry SLOT, passing the unused
362    sttribute DATA.  Used as a callback function with htab_traverse ().  */
363
364 static int
365 ssa_rename_from_print_1 (slot, data)
366      void **slot;
367      void *data ATTRIBUTE_UNUSED;
368 {
369   ssa_rename_from_pair * p = *slot;
370   printf ("ssa_rename_from maps pseudo %i to original %i.\n",
371           p->reg, REGNO (p->original));
372   return 1;
373 }
374
375 /* Given a hash entry SRFP, yield a hash value.  */
376
377 static hashval_t
378 ssa_rename_from_hash_function (srfp)
379      const void *srfp;
380 {
381   return ((const ssa_rename_from_pair *) srfp)->reg;
382 }
383
384 /* Test whether two hash table entries SRFP1 and SRFP2 are equal.  */
385
386 static int
387 ssa_rename_from_equal (srfp1, srfp2)
388      const void *srfp1;
389      const void *srfp2;
390 {
391   return ssa_rename_from_hash_function (srfp1) ==
392     ssa_rename_from_hash_function (srfp2);
393 }
394
395 /* Delete the hash table entry SRFP.  */
396
397 static void
398 ssa_rename_from_delete (srfp)
399      void *srfp;
400 {
401   free (srfp);
402 }
403
404 /* Given the SET of a PHI node, return the address of the alternative
405    for predecessor block C.  */
406
407 static inline rtx *
408 phi_alternative (set, c)
409      rtx set;
410      int c;
411 {
412   rtvec phi_vec = XVEC (SET_SRC (set), 0);
413   int v;
414
415   for (v = GET_NUM_ELEM (phi_vec) - 2; v >= 0; v -= 2)
416     if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
417       return &RTVEC_ELT (phi_vec, v);
418
419   return NULL;
420 }
421
422 /* Given the SET of a phi node, remove the alternative for predecessor
423    block C.  Return non-zero on success, or zero if no alternative is
424    found for C.  */
425
426 int
427 remove_phi_alternative (set, block)
428      rtx set;
429      basic_block block;
430 {
431   rtvec phi_vec = XVEC (SET_SRC (set), 0);
432   int num_elem = GET_NUM_ELEM (phi_vec);
433   int v, c;
434
435   c = block->index;
436   for (v = num_elem - 2; v >= 0; v -= 2)
437     if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
438       {
439         if (v < num_elem - 2)
440           {
441             RTVEC_ELT (phi_vec, v) = RTVEC_ELT (phi_vec, num_elem - 2);
442             RTVEC_ELT (phi_vec, v + 1) = RTVEC_ELT (phi_vec, num_elem - 1);
443           }
444         PUT_NUM_ELEM (phi_vec, num_elem - 2);
445         return 1;
446       }
447
448   return 0;
449 }
450
451 /* For all registers, find all blocks in which they are set.
452
453    This is the transform of what would be local kill information that
454    we ought to be getting from flow.  */
455
456 static sbitmap *fe_evals;
457 static int fe_current_bb;
458
459 static void
460 find_evaluations_1 (dest, set, data)
461      rtx dest;
462      rtx set ATTRIBUTE_UNUSED;
463      void *data ATTRIBUTE_UNUSED;
464 {
465   if (GET_CODE (dest) == REG
466       && CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
467     SET_BIT (fe_evals[REGNO (dest)], fe_current_bb);
468 }
469
470 static void
471 find_evaluations (evals, nregs)
472      sbitmap *evals;
473      int nregs;
474 {
475   int bb;
476
477   sbitmap_vector_zero (evals, nregs);
478   fe_evals = evals;
479
480   for (bb = n_basic_blocks; --bb >= 0; )
481     {
482       rtx p, last;
483
484       fe_current_bb = bb;
485       p = BLOCK_HEAD (bb);
486       last = BLOCK_END (bb);
487       while (1)
488         {
489           if (INSN_P (p))
490             note_stores (PATTERN (p), find_evaluations_1, NULL);
491
492           if (p == last)
493             break;
494           p = NEXT_INSN (p);
495         }
496     }
497 }
498
499 /* Computing the Dominance Frontier:
500   
501    As decribed in Morgan, section 3.5, this may be done simply by 
502    walking the dominator tree bottom-up, computing the frontier for
503    the children before the parent.  When considering a block B,
504    there are two cases:
505
506    (1) A flow graph edge leaving B that does not lead to a child
507    of B in the dominator tree must be a block that is either equal
508    to B or not dominated by B.  Such blocks belong in the frontier
509    of B.
510
511    (2) Consider a block X in the frontier of one of the children C
512    of B.  If X is not equal to B and is not dominated by B, it
513    is in the frontier of B.
514 */
515
516 static void
517 compute_dominance_frontiers_1 (frontiers, idom, bb, done)
518      sbitmap *frontiers;
519      int *idom;
520      int bb;
521      sbitmap done;
522 {
523   basic_block b = BASIC_BLOCK (bb);
524   edge e;
525   int c;
526
527   SET_BIT (done, bb);
528   sbitmap_zero (frontiers[bb]);
529
530   /* Do the frontier of the children first.  Not all children in the
531      dominator tree (blocks dominated by this one) are children in the
532      CFG, so check all blocks.  */
533   for (c = 0; c < n_basic_blocks; ++c)
534     if (idom[c] == bb && ! TEST_BIT (done, c))
535       compute_dominance_frontiers_1 (frontiers, idom, c, done);
536
537   /* Find blocks conforming to rule (1) above.  */
538   for (e = b->succ; e; e = e->succ_next)
539     {
540       if (e->dest == EXIT_BLOCK_PTR)
541         continue;
542       if (idom[e->dest->index] != bb)
543         SET_BIT (frontiers[bb], e->dest->index);
544     }
545
546   /* Find blocks conforming to rule (2).  */
547   for (c = 0; c < n_basic_blocks; ++c)
548     if (idom[c] == bb)
549       {
550         int x;
551         EXECUTE_IF_SET_IN_SBITMAP (frontiers[c], 0, x,
552           {
553             if (idom[x] != bb)
554               SET_BIT (frontiers[bb], x);
555           });
556       }
557 }
558
559 void
560 compute_dominance_frontiers (frontiers, idom)
561      sbitmap *frontiers;
562      int *idom;
563 {
564   sbitmap done = sbitmap_alloc (n_basic_blocks);
565   sbitmap_zero (done);
566
567   compute_dominance_frontiers_1 (frontiers, idom, 0, done);
568
569   sbitmap_free (done);
570 }
571
572 /* Computing the Iterated Dominance Frontier:
573
574    This is the set of merge points for a given register.
575
576    This is not particularly intuitive.  See section 7.1 of Morgan, in
577    particular figures 7.3 and 7.4 and the immediately surrounding text.
578 */
579
580 static void
581 compute_iterated_dominance_frontiers (idfs, frontiers, evals, nregs)
582      sbitmap *idfs;
583      sbitmap *frontiers;
584      sbitmap *evals;
585      int nregs;
586 {
587   sbitmap worklist;
588   int reg, passes = 0;
589
590   worklist = sbitmap_alloc (n_basic_blocks);
591
592   for (reg = 0; reg < nregs; ++reg)
593     {
594       sbitmap idf = idfs[reg];
595       int b, changed;
596
597       /* Start the iterative process by considering those blocks that
598          evaluate REG.  We'll add their dominance frontiers to the
599          IDF, and then consider the blocks we just added.  */
600       sbitmap_copy (worklist, evals[reg]);
601
602       /* Morgan's algorithm is incorrect here.  Blocks that evaluate
603          REG aren't necessarily in REG's IDF.  Start with an empty IDF.  */
604       sbitmap_zero (idf);
605
606       /* Iterate until the worklist is empty.  */
607       do
608         {
609           changed = 0;
610           passes++;
611           EXECUTE_IF_SET_IN_SBITMAP (worklist, 0, b,
612             {
613               RESET_BIT (worklist, b);
614               /* For each block on the worklist, add to the IDF all
615                  blocks on its dominance frontier that aren't already
616                  on the IDF.  Every block that's added is also added
617                  to the worklist.  */
618               sbitmap_union_of_diff (worklist, worklist, frontiers[b], idf);
619               sbitmap_a_or_b (idf, idf, frontiers[b]);
620               changed = 1;
621             });
622         }
623       while (changed);
624     }
625
626   sbitmap_free (worklist);
627
628   if (rtl_dump_file)
629     {
630       fprintf(rtl_dump_file,
631               "Iterated dominance frontier: %d passes on %d regs.\n",
632               passes, nregs);
633     }
634 }
635
636 /* Return the INSN immediately following the NOTE_INSN_BASIC_BLOCK
637    note associated with the BLOCK.  */
638
639 static rtx
640 first_insn_after_basic_block_note (block)
641      basic_block block;
642 {
643   rtx insn;
644
645   /* Get the first instruction in the block.  */
646   insn = block->head;
647
648   if (insn == NULL_RTX)
649     return NULL_RTX;
650   if (GET_CODE (insn) == CODE_LABEL)
651     insn = NEXT_INSN (insn);
652   if (!NOTE_INSN_BASIC_BLOCK_P (insn))
653     abort ();
654
655   return NEXT_INSN (insn);
656 }
657
658 /* Insert the phi nodes.  */
659
660 static void
661 insert_phi_node (regno, bb)
662      int regno, bb;
663 {
664   basic_block b = BASIC_BLOCK (bb);
665   edge e;
666   int npred, i;
667   rtvec vec;
668   rtx phi, reg;
669   rtx insn;
670   int end_p;
671
672   /* Find out how many predecessors there are.  */
673   for (e = b->pred, npred = 0; e; e = e->pred_next)
674     if (e->src != ENTRY_BLOCK_PTR)
675       npred++;
676
677   /* If this block has no "interesting" preds, then there is nothing to
678      do.  Consider a block that only has the entry block as a pred.  */
679   if (npred == 0)
680     return;
681
682   /* This is the register to which the phi function will be assigned.  */
683   reg = regno_reg_rtx[regno];
684
685   /* Construct the arguments to the PHI node.  The use of pc_rtx is just
686      a placeholder; we'll insert the proper value in rename_registers.  */
687   vec = rtvec_alloc (npred * 2);
688   for (e = b->pred, i = 0; e ; e = e->pred_next, i += 2)
689     if (e->src != ENTRY_BLOCK_PTR)
690       {
691         RTVEC_ELT (vec, i + 0) = pc_rtx;
692         RTVEC_ELT (vec, i + 1) = GEN_INT (e->src->index);
693       }
694
695   phi = gen_rtx_PHI (VOIDmode, vec);
696   phi = gen_rtx_SET (VOIDmode, reg, phi);
697
698   insn = first_insn_after_basic_block_note (b);
699   end_p = PREV_INSN (insn) == b->end;
700   emit_insn_before (phi, insn);
701   if (end_p)
702     b->end = PREV_INSN (insn);
703 }
704
705 static void
706 insert_phi_nodes (idfs, evals, nregs)
707      sbitmap *idfs;
708      sbitmap *evals ATTRIBUTE_UNUSED;
709      int nregs;
710 {
711   int reg;
712
713   for (reg = 0; reg < nregs; ++reg)
714     if (CONVERT_REGISTER_TO_SSA_P (reg))
715     {
716       int b;
717       EXECUTE_IF_SET_IN_SBITMAP (idfs[reg], 0, b,
718         {
719           if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start, reg))
720             insert_phi_node (reg, b);
721         });
722     }
723 }
724
725 /* Rename the registers to conform to SSA. 
726
727    This is essentially the algorithm presented in Figure 7.8 of Morgan,
728    with a few changes to reduce pattern search time in favour of a bit
729    more memory usage.  */
730
731 /* One of these is created for each set.  It will live in a list local
732    to its basic block for the duration of that block's processing.  */
733 struct rename_set_data
734 {
735   struct rename_set_data *next;
736   /* This is the SET_DEST of the (first) SET that sets the REG.  */
737   rtx *reg_loc;
738   /* This is what used to be at *REG_LOC.  */
739   rtx old_reg;
740   /* This is the REG that will replace OLD_REG.  It's set only
741      when the rename data is moved onto the DONE_RENAMES queue.  */
742   rtx new_reg;
743   /* This is what to restore ssa_rename_to_lookup (old_reg) to.  It is
744      usually the previous contents of ssa_rename_to_lookup (old_reg).  */
745   rtx prev_reg;
746   /* This is the insn that contains all the SETs of the REG.  */
747   rtx set_insn;
748 };
749
750 /* This struct is used to pass information to callback functions while
751    renaming registers.  */
752 struct rename_context
753 {
754   struct rename_set_data *new_renames;
755   struct rename_set_data *done_renames;
756   rtx current_insn;
757 };
758
759 /* Queue the rename of *REG_LOC.  */
760 static void
761 create_delayed_rename (c, reg_loc)
762      struct rename_context *c;
763      rtx *reg_loc;
764 {
765   struct rename_set_data *r;
766   r = (struct rename_set_data *) xmalloc (sizeof(*r));
767   
768   if (GET_CODE (*reg_loc) != REG
769       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*reg_loc)))
770     abort();
771
772   r->reg_loc = reg_loc;
773   r->old_reg = *reg_loc;
774   r->prev_reg = ssa_rename_to_lookup(r->old_reg);
775   r->set_insn = c->current_insn;
776   r->next = c->new_renames;
777   c->new_renames = r;
778 }
779
780 /* This is part of a rather ugly hack to allow the pre-ssa regno to be
781    reused.  If, during processing, a register has not yet been touched,
782    ssa_rename_to[regno][machno] will be NULL.  Now, in the course of pushing
783    and popping values from ssa_rename_to, when we would ordinarily 
784    pop NULL back in, we pop RENAME_NO_RTX.  We treat this exactly the
785    same as NULL, except that it signals that the original regno has
786    already been reused.  */
787 #define RENAME_NO_RTX  pc_rtx
788
789 /* Move all the entries from NEW_RENAMES onto DONE_RENAMES by
790    applying all the renames on NEW_RENAMES.  */
791
792 static void
793 apply_delayed_renames (c)
794        struct rename_context *c;
795 {
796   struct rename_set_data *r;
797   struct rename_set_data *last_r = NULL;
798
799   for (r = c->new_renames; r != NULL; r = r->next)
800     {
801       int new_regno;
802       
803       /* Failure here means that someone has a PARALLEL that sets
804          a register twice (bad!).  */
805       if (ssa_rename_to_lookup (r->old_reg) != r->prev_reg)
806         abort();
807       /* Failure here means we have changed REG_LOC before applying
808          the rename.  */
809       /* For the first set we come across, reuse the original regno.  */
810       if (r->prev_reg == NULL_RTX && !HARD_REGISTER_P (r->old_reg))
811         {
812           r->new_reg = r->old_reg;
813           /* We want to restore RENAME_NO_RTX rather than NULL_RTX. */
814           r->prev_reg = RENAME_NO_RTX;
815         }
816       else
817         r->new_reg = gen_reg_rtx (GET_MODE (r->old_reg));
818       new_regno = REGNO (r->new_reg);
819       ssa_rename_to_insert (r->old_reg, r->new_reg);
820
821       if (new_regno >= (int) ssa_definition->num_elements)
822         {
823           int new_limit = new_regno * 5 / 4;
824           VARRAY_GROW (ssa_definition, new_limit);
825         }
826
827       VARRAY_RTX (ssa_definition, new_regno) = r->set_insn;
828       ssa_rename_from_insert (new_regno, r->old_reg);
829       last_r = r;
830     }
831   if (last_r != NULL)
832     {
833       last_r->next = c->done_renames;
834       c->done_renames = c->new_renames;
835       c->new_renames = NULL;
836     }
837 }
838
839 /* Part one of the first step of rename_block, called through for_each_rtx. 
840    Mark pseudos that are set for later update.  Transform uses of pseudos.  */
841
842 static int
843 rename_insn_1 (ptr, data)
844      rtx *ptr;
845      void *data;
846 {
847   rtx x = *ptr;
848   struct rename_context *context = data;
849
850   if (x == NULL_RTX)
851     return 0;
852
853   switch (GET_CODE (x))
854     {
855     case SET:
856       {
857         rtx *destp = &SET_DEST (x);
858         rtx dest = SET_DEST (x);
859
860         /* Some SETs also use the REG specified in their LHS.
861            These can be detected by the presence of
862            STRICT_LOW_PART, SUBREG, SIGN_EXTRACT, and ZERO_EXTRACT
863            in the LHS.  Handle these by changing
864            (set (subreg (reg foo)) ...)
865            into
866            (sequence [(set (reg foo_1) (reg foo))
867                       (set (subreg (reg foo_1)) ...)])  
868
869            FIXME: Much of the time this is too much.  For many libcalls,
870            paradoxical SUBREGs, etc., the input register is dead.  We should
871            recognise this in rename_block or here and not make a false
872            dependency.  */
873            
874         if (GET_CODE (dest) == STRICT_LOW_PART
875             || GET_CODE (dest) == SUBREG
876             || GET_CODE (dest) == SIGN_EXTRACT
877             || GET_CODE (dest) == ZERO_EXTRACT)
878           {
879             rtx i, reg;
880             reg = dest;
881             
882             while (GET_CODE (reg) == STRICT_LOW_PART
883                    || GET_CODE (reg) == SUBREG
884                    || GET_CODE (reg) == SIGN_EXTRACT
885                    || GET_CODE (reg) == ZERO_EXTRACT)
886                 reg = XEXP (reg, 0);
887             
888             if (GET_CODE (reg) == REG
889                 && CONVERT_REGISTER_TO_SSA_P (REGNO (reg)))
890               {
891                 /* Generate (set reg reg), and do renaming on it so
892                    that it becomes (set reg_1 reg_0), and we will
893                    replace reg with reg_1 in the SUBREG.  */
894
895                 struct rename_set_data *saved_new_renames;
896                 saved_new_renames = context->new_renames;
897                 context->new_renames = NULL;
898                 i = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
899                 for_each_rtx (&i, rename_insn_1, data);
900                 apply_delayed_renames (context);
901                 context->new_renames = saved_new_renames;
902               }
903           }
904         else if (GET_CODE (dest) == REG &&
905                  CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
906           {
907             /* We found a genuine set of an interesting register.  Tag
908                it so that we can create a new name for it after we finish
909                processing this insn.  */
910
911             create_delayed_rename (context, destp);
912
913             /* Since we do not wish to (directly) traverse the
914                SET_DEST, recurse through for_each_rtx for the SET_SRC
915                and return.  */
916             if (GET_CODE (x) == SET)
917               for_each_rtx (&SET_SRC (x), rename_insn_1, data);
918             return -1;
919           }
920
921         /* Otherwise, this was not an interesting destination.  Continue
922            on, marking uses as normal.  */
923         return 0;
924       }
925
926     case REG:
927       if (CONVERT_REGISTER_TO_SSA_P (REGNO (x)) &&
928           REGNO (x) < ssa_max_reg_num)
929         {
930           rtx new_reg = ssa_rename_to_lookup (x);
931
932           if (new_reg != NULL_RTX && new_reg != RENAME_NO_RTX)
933             {
934               if (GET_MODE (x) != GET_MODE (new_reg))
935                 abort ();
936               *ptr = new_reg;
937             }
938           /* Else this is a use before a set.  Warn?  */
939         }
940       return -1;
941
942     case CLOBBER:
943       /* There is considerable debate on how CLOBBERs ought to be
944          handled in SSA.  For now, we're keeping the CLOBBERs, which
945          means that we don't really have SSA form.  There are a couple
946          of proposals for how to fix this problem, but neither is
947          implemented yet.  */
948       {
949         rtx dest = XCEXP (x, 0, CLOBBER);
950         if (REG_P (dest))
951           {
952             if (CONVERT_REGISTER_TO_SSA_P (REGNO (dest))
953                 && REGNO (dest) < ssa_max_reg_num)
954               {
955                 rtx new_reg = ssa_rename_to_lookup (dest);
956                 if (new_reg != NULL_RTX && new_reg != RENAME_NO_RTX)
957                     XCEXP (x, 0, CLOBBER) = new_reg;
958               }
959             /* Stop traversing.  */
960             return -1;
961           }         
962         else
963           /* Continue traversing.  */
964           return 0;
965       }
966
967     case PHI:
968       /* Never muck with the phi.  We do that elsewhere, special-like.  */
969       return -1;
970
971     default:
972       /* Anything else, continue traversing.  */
973       return 0;
974     }
975 }
976
977 static void
978 rename_block (bb, idom)
979      int bb;
980      int *idom;
981 {
982   basic_block b = BASIC_BLOCK (bb);
983   edge e;
984   rtx insn, next, last;
985   struct rename_set_data *set_data = NULL;
986   int c;
987
988   /* Step One: Walk the basic block, adding new names for sets and
989      replacing uses.  */
990      
991   next = b->head;
992   last = b->end;
993   do
994     {
995       insn = next;
996       if (INSN_P (insn))
997         {
998           struct rename_context context;
999           context.done_renames = set_data;
1000           context.new_renames = NULL;
1001           context.current_insn = insn;
1002
1003           start_sequence ();
1004           for_each_rtx (&PATTERN (insn), rename_insn_1, &context);
1005           for_each_rtx (&REG_NOTES (insn), rename_insn_1, &context);
1006
1007           /* Sometimes, we end up with a sequence of insns that
1008              SSA needs to treat as a single insn.  Wrap these in a
1009              SEQUENCE.  (Any notes now get attached to the SEQUENCE,
1010              not to the old version inner insn.)  */
1011           if (get_insns () != NULL_RTX)
1012             {
1013               rtx seq;
1014               int i;
1015               
1016               emit (PATTERN (insn));
1017               seq = gen_sequence ();
1018               /* We really want a SEQUENCE of SETs, not a SEQUENCE
1019                  of INSNs.  */
1020               for (i = 0; i < XVECLEN (seq, 0); i++)
1021                 XVECEXP (seq, 0, i) = PATTERN (XVECEXP (seq, 0, i));
1022               PATTERN (insn) = seq;
1023             }
1024           end_sequence ();
1025           
1026           apply_delayed_renames (&context);
1027           set_data = context.done_renames;
1028         }
1029
1030       next = NEXT_INSN (insn);
1031     }
1032   while (insn != last);
1033
1034   /* Step Two: Update the phi nodes of this block's successors.  */
1035
1036   for (e = b->succ; e; e = e->succ_next)
1037     {
1038       if (e->dest == EXIT_BLOCK_PTR)
1039         continue;
1040
1041       insn = first_insn_after_basic_block_note (e->dest);
1042
1043       while (PHI_NODE_P (insn))
1044         {
1045           rtx phi = PATTERN (insn);
1046           rtx reg;
1047
1048           /* Find out which of our outgoing registers this node is
1049              intended to replace.  Note that if this is not the first PHI
1050              node to have been created for this register, we have to
1051              jump through rename links to figure out which register
1052              we're talking about.  This can easily be recognized by
1053              noting that the regno is new to this pass.  */
1054           reg = SET_DEST (phi);
1055           if (REGNO (reg) >= ssa_max_reg_num)
1056             reg = ssa_rename_from_lookup (REGNO (reg));
1057           if (reg == NULL_RTX)
1058             abort ();
1059           reg = ssa_rename_to_lookup (reg);
1060
1061           /* It is possible for the variable to be uninitialized on
1062              edges in.  Reduce the arity of the PHI so that we don't
1063              consider those edges.  */
1064           if (reg == NULL || reg == RENAME_NO_RTX)
1065             {
1066               if (! remove_phi_alternative (phi, b))
1067                 abort ();
1068             }
1069           else
1070             {
1071               /* When we created the PHI nodes, we did not know what mode
1072              the register should be.  Now that we've found an original,
1073              we can fill that in.  */
1074               if (GET_MODE (SET_DEST (phi)) == VOIDmode)
1075                 PUT_MODE (SET_DEST (phi), GET_MODE (reg));
1076               else if (GET_MODE (SET_DEST (phi)) != GET_MODE (reg))
1077                 abort();
1078
1079               *phi_alternative (phi, bb) = reg;
1080             }
1081
1082           insn = NEXT_INSN (insn);
1083         }
1084     }
1085
1086   /* Step Three: Do the same to the children of this block in
1087      dominator order.  */
1088
1089   for (c = 0; c < n_basic_blocks; ++c)
1090     if (idom[c] == bb)
1091       rename_block (c, idom);
1092
1093   /* Step Four: Update the sets to refer to their new register,
1094      and restore ssa_rename_to to its previous state.  */
1095
1096   while (set_data)
1097     {
1098       struct rename_set_data *next;
1099       rtx old_reg = *set_data->reg_loc;
1100
1101       if (*set_data->reg_loc != set_data->old_reg)
1102         abort();
1103       *set_data->reg_loc = set_data->new_reg;
1104
1105       ssa_rename_to_insert (old_reg, set_data->prev_reg);
1106
1107       next = set_data->next;
1108       free (set_data);
1109       set_data = next;
1110     }      
1111 }
1112
1113 static void
1114 rename_registers (nregs, idom)
1115      int nregs;
1116      int *idom;
1117 {
1118   VARRAY_RTX_INIT (ssa_definition, nregs * 3, "ssa_definition");
1119   ssa_rename_from_initialize ();
1120
1121   ssa_rename_to_pseudo = (rtx *) alloca (nregs * sizeof(rtx));
1122   memset ((char *) ssa_rename_to_pseudo, 0, nregs * sizeof(rtx));
1123   memset ((char *) ssa_rename_to_hard, 0, 
1124          FIRST_PSEUDO_REGISTER * NUM_MACHINE_MODES * sizeof (rtx));
1125
1126   rename_block (0, idom);
1127
1128   /* ??? Update basic_block_live_at_start, and other flow info 
1129      as needed.  */
1130
1131   ssa_rename_to_pseudo = NULL;
1132 }
1133
1134 /* The main entry point for moving to SSA.  */
1135
1136 void
1137 convert_to_ssa ()
1138 {
1139   /* Element I is the set of blocks that set register I.  */
1140   sbitmap *evals;
1141
1142   /* Dominator bitmaps.  */
1143   sbitmap *dfs;
1144   sbitmap *idfs;
1145
1146   /* Element I is the immediate dominator of block I.  */
1147   int *idom;
1148
1149   int nregs;
1150
1151   /* Don't do it twice.  */
1152   if (in_ssa_form)
1153     abort ();
1154
1155   /* Need global_live_at_{start,end} up to date.  Do not remove any
1156      dead code.  We'll let the SSA optimizers do that.  */
1157   life_analysis (get_insns (), NULL, 0);
1158
1159   idom = (int *) alloca (n_basic_blocks * sizeof (int));
1160   memset ((void *)idom, -1, (size_t)n_basic_blocks * sizeof (int));
1161   calculate_dominance_info (idom, NULL, CDI_DOMINATORS);
1162
1163   if (rtl_dump_file)
1164     {
1165       int i;
1166       fputs (";; Immediate Dominators:\n", rtl_dump_file);
1167       for (i = 0; i < n_basic_blocks; ++i)
1168         fprintf (rtl_dump_file, ";\t%3d = %3d\n", i, idom[i]);
1169       fflush (rtl_dump_file);
1170     }
1171
1172   /* Compute dominance frontiers.  */
1173
1174   dfs = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
1175   compute_dominance_frontiers (dfs, idom);
1176
1177   if (rtl_dump_file)
1178     {
1179       dump_sbitmap_vector (rtl_dump_file, ";; Dominance Frontiers:",
1180                            "; Basic Block", dfs, n_basic_blocks);
1181       fflush (rtl_dump_file);
1182     }
1183
1184   /* Compute register evaluations.  */
1185
1186   ssa_max_reg_num = max_reg_num();
1187   nregs = ssa_max_reg_num;
1188   evals = sbitmap_vector_alloc (nregs, n_basic_blocks);
1189   find_evaluations (evals, nregs);
1190
1191   /* Compute the iterated dominance frontier for each register.  */
1192
1193   idfs = sbitmap_vector_alloc (nregs, n_basic_blocks);
1194   compute_iterated_dominance_frontiers (idfs, dfs, evals, nregs);
1195
1196   if (rtl_dump_file)
1197     {
1198       dump_sbitmap_vector (rtl_dump_file, ";; Iterated Dominance Frontiers:",
1199                            "; Register", idfs, nregs);
1200       fflush (rtl_dump_file);
1201     }
1202
1203   /* Insert the phi nodes.  */
1204
1205   insert_phi_nodes (idfs, evals, nregs);
1206
1207   /* Rename the registers to satisfy SSA.  */
1208
1209   rename_registers (nregs, idom);
1210
1211   /* All done!  Clean up and go home.  */
1212
1213   sbitmap_vector_free (dfs);
1214   sbitmap_vector_free (evals);
1215   sbitmap_vector_free (idfs);
1216   in_ssa_form = 1;
1217
1218   reg_scan (get_insns (), max_reg_num (), 1);
1219 }
1220
1221 /* REG is the representative temporary of its partition.  Add it to the
1222    set of nodes to be processed, if it hasn't been already.  Return the
1223    index of this register in the node set.  */
1224
1225 static inline int
1226 ephi_add_node (reg, nodes, n_nodes)
1227      rtx reg, *nodes;
1228      int *n_nodes;
1229 {
1230   int i;
1231   for (i = *n_nodes - 1; i >= 0; --i)
1232     if (REGNO (reg) == REGNO (nodes[i]))
1233       return i;
1234
1235   nodes[i = (*n_nodes)++] = reg;
1236   return i;
1237 }
1238
1239 /* Part one of the topological sort.  This is a forward (downward) search
1240    through the graph collecting a stack of nodes to process.  Assuming no
1241    cycles, the nodes at top of the stack when we are finished will have
1242    no other dependancies.  */
1243
1244 static int *
1245 ephi_forward (t, visited, succ, tstack)
1246      int t;
1247      sbitmap visited;
1248      sbitmap *succ;
1249      int *tstack;
1250 {
1251   int s;
1252
1253   SET_BIT (visited, t);
1254
1255   EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
1256     {
1257       if (! TEST_BIT (visited, s))
1258         tstack = ephi_forward (s, visited, succ, tstack);
1259     });
1260
1261   *tstack++ = t;
1262   return tstack;
1263 }
1264
1265 /* Part two of the topological sort.  The is a backward search through
1266    a cycle in the graph, copying the data forward as we go.  */
1267
1268 static void
1269 ephi_backward (t, visited, pred, nodes)
1270      int t;
1271      sbitmap visited, *pred;
1272      rtx *nodes;
1273 {
1274   int p;
1275
1276   SET_BIT (visited, t);
1277
1278   EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1279     {
1280       if (! TEST_BIT (visited, p))
1281         {
1282           ephi_backward (p, visited, pred, nodes);
1283           emit_move_insn (nodes[p], nodes[t]);
1284         }
1285     });
1286 }
1287
1288 /* Part two of the topological sort.  Create the copy for a register
1289    and any cycle of which it is a member.  */
1290
1291 static void
1292 ephi_create (t, visited, pred, succ, nodes)
1293      int t;
1294      sbitmap visited, *pred, *succ;
1295      rtx *nodes;
1296 {
1297   rtx reg_u = NULL_RTX;
1298   int unvisited_predecessors = 0;
1299   int p;
1300
1301   /* Iterate through the predecessor list looking for unvisited nodes.
1302      If there are any, we have a cycle, and must deal with that.  At 
1303      the same time, look for a visited predecessor.  If there is one,
1304      we won't need to create a temporary.  */
1305
1306   EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1307     {
1308       if (! TEST_BIT (visited, p))
1309         unvisited_predecessors = 1;
1310       else if (!reg_u)
1311         reg_u = nodes[p];
1312     });
1313
1314   if (unvisited_predecessors)
1315     {
1316       /* We found a cycle.  Copy out one element of the ring (if necessary),
1317          then traverse the ring copying as we go.  */
1318
1319       if (!reg_u)
1320         {
1321           reg_u = gen_reg_rtx (GET_MODE (nodes[t]));
1322           emit_move_insn (reg_u, nodes[t]);
1323         }
1324
1325       EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1326         {
1327           if (! TEST_BIT (visited, p))
1328             {
1329               ephi_backward (p, visited, pred, nodes);
1330               emit_move_insn (nodes[p], reg_u);
1331             }
1332         });
1333     }  
1334   else 
1335     {
1336       /* No cycle.  Just copy the value from a successor.  */
1337
1338       int s;
1339       EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
1340         {
1341           SET_BIT (visited, t);
1342           emit_move_insn (nodes[t], nodes[s]);
1343           return;
1344         });
1345     }
1346 }
1347
1348 /* Convert the edge to normal form.  */
1349
1350 static void
1351 eliminate_phi (e, reg_partition)
1352      edge e;
1353      partition reg_partition;
1354 {
1355   int n_nodes;
1356   sbitmap *pred, *succ;
1357   sbitmap visited;
1358   rtx *nodes;
1359   int *stack, *tstack;
1360   rtx insn;
1361   int i;
1362
1363   /* Collect an upper bound on the number of registers needing processing.  */
1364
1365   insn = first_insn_after_basic_block_note (e->dest);
1366
1367   n_nodes = 0;
1368   while (PHI_NODE_P (insn))
1369     {
1370       insn = next_nonnote_insn (insn);
1371       n_nodes += 2;
1372     }
1373
1374   if (n_nodes == 0)
1375     return;
1376
1377   /* Build the auxilliary graph R(B). 
1378
1379      The nodes of the graph are the members of the register partition
1380      present in Phi(B).  There is an edge from FIND(T0)->FIND(T1) for
1381      each T0 = PHI(...,T1,...), where T1 is for the edge from block C.  */
1382
1383   nodes = (rtx *) alloca (n_nodes * sizeof(rtx));
1384   pred = sbitmap_vector_alloc (n_nodes, n_nodes);
1385   succ = sbitmap_vector_alloc (n_nodes, n_nodes);
1386   sbitmap_vector_zero (pred, n_nodes);
1387   sbitmap_vector_zero (succ, n_nodes);
1388
1389   insn = first_insn_after_basic_block_note (e->dest);
1390
1391   n_nodes = 0;
1392   for (; PHI_NODE_P (insn); insn = next_nonnote_insn (insn))
1393     {
1394       rtx* preg = phi_alternative (PATTERN (insn), e->src->index);
1395       rtx tgt = SET_DEST (PATTERN (insn));
1396       rtx reg;
1397
1398       /* There may be no phi alternative corresponding to this edge.
1399          This indicates that the phi variable is undefined along this
1400          edge.  */
1401       if (preg == NULL)
1402         continue;
1403       reg = *preg;
1404
1405       if (GET_CODE (reg) != REG || GET_CODE (tgt) != REG)
1406         abort();
1407
1408       reg = regno_reg_rtx[partition_find (reg_partition, REGNO (reg))];
1409       tgt = regno_reg_rtx[partition_find (reg_partition, REGNO (tgt))];
1410       /* If the two registers are already in the same partition, 
1411          nothing will need to be done.  */
1412       if (reg != tgt)
1413         {
1414           int ireg, itgt;
1415
1416           ireg = ephi_add_node (reg, nodes, &n_nodes);
1417           itgt = ephi_add_node (tgt, nodes, &n_nodes);
1418
1419           SET_BIT (pred[ireg], itgt);
1420           SET_BIT (succ[itgt], ireg);
1421         }
1422     }
1423
1424   if (n_nodes == 0)
1425     goto out;
1426
1427   /* Begin a topological sort of the graph.  */
1428
1429   visited = sbitmap_alloc (n_nodes);
1430   sbitmap_zero (visited);
1431
1432   tstack = stack = (int *) alloca (n_nodes * sizeof (int));
1433
1434   for (i = 0; i < n_nodes; ++i)
1435     if (! TEST_BIT (visited, i))
1436       tstack = ephi_forward (i, visited, succ, tstack);
1437
1438   sbitmap_zero (visited);
1439
1440   /* As we find a solution to the tsort, collect the implementation 
1441      insns in a sequence.  */
1442   start_sequence ();
1443   
1444   while (tstack != stack)
1445     {
1446       i = *--tstack;
1447       if (! TEST_BIT (visited, i))
1448         ephi_create (i, visited, pred, succ, nodes);
1449     }
1450
1451   insn = gen_sequence ();
1452   end_sequence ();
1453   insert_insn_on_edge (insn, e);
1454   if (rtl_dump_file)
1455     fprintf (rtl_dump_file, "Emitting copy on edge (%d,%d)\n",
1456              e->src->index, e->dest->index);
1457
1458   sbitmap_free (visited);
1459 out:
1460   sbitmap_vector_free (pred);
1461   sbitmap_vector_free (succ);
1462 }
1463
1464 /* For basic block B, consider all phi insns which provide an
1465    alternative corresponding to an incoming abnormal critical edge.
1466    Place the phi alternative corresponding to that abnormal critical
1467    edge in the same register class as the destination of the set.  
1468
1469    From Morgan, p. 178:
1470
1471      For each abnormal critical edge (C, B), 
1472      if T0 = phi (T1, ..., Ti, ..., Tm) is a phi node in B, 
1473      and C is the ith predecessor of B, 
1474      then T0 and Ti must be equivalent. 
1475
1476    Return non-zero iff any such cases were found for which the two
1477    regs were not already in the same class.  */
1478
1479 static int
1480 make_regs_equivalent_over_bad_edges (bb, reg_partition)
1481      int bb;
1482      partition reg_partition;
1483 {
1484   int changed = 0;
1485   basic_block b = BASIC_BLOCK (bb);
1486   rtx phi;
1487
1488   /* Advance to the first phi node.  */
1489   phi = first_insn_after_basic_block_note (b);
1490
1491   /* Scan all the phi nodes.  */
1492   for (; 
1493        PHI_NODE_P (phi);
1494        phi = next_nonnote_insn (phi))
1495     {
1496       edge e;
1497       int tgt_regno;
1498       rtx set = PATTERN (phi);
1499       rtx tgt = SET_DEST (set);
1500
1501       /* The set target is expected to be an SSA register.  */
1502       if (GET_CODE (tgt) != REG 
1503           || !CONVERT_REGISTER_TO_SSA_P (REGNO (tgt)))
1504         abort ();
1505       tgt_regno = REGNO (tgt);
1506
1507       /* Scan incoming abnormal critical edges.  */
1508       for (e = b->pred; e; e = e->pred_next)
1509         if ((e->flags & (EDGE_ABNORMAL | EDGE_CRITICAL)) 
1510                 == (EDGE_ABNORMAL | EDGE_CRITICAL))
1511           {
1512             rtx *alt = phi_alternative (set, e->src->index);
1513             int alt_regno;
1514
1515             /* If there is no alternative corresponding to this edge,
1516                the value is undefined along the edge, so just go on.  */
1517             if (alt == 0)
1518               continue;
1519
1520             /* The phi alternative is expected to be an SSA register.  */
1521             if (GET_CODE (*alt) != REG 
1522                 || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
1523               abort ();
1524             alt_regno = REGNO (*alt);
1525
1526             /* If the set destination and the phi alternative aren't
1527                already in the same class...  */
1528             if (partition_find (reg_partition, tgt_regno) 
1529                 != partition_find (reg_partition, alt_regno))
1530               {
1531                 /* ... make them such.  */
1532                 if (conflicting_hard_regs_p (tgt_regno, alt_regno))
1533                   /* It is illegal to unify a hard register with a
1534                      different register.  */
1535                   abort ();
1536                 
1537                 partition_union (reg_partition, 
1538                                  tgt_regno, alt_regno);
1539                 ++changed;
1540               }
1541           }
1542     }
1543
1544   return changed;
1545 }
1546
1547 /* Consider phi insns in basic block BB pairwise.  If the set target
1548    of both isns are equivalent pseudos, make the corresponding phi
1549    alternatives in each phi corresponding equivalent.
1550
1551    Return nonzero if any new register classes were unioned.  */
1552
1553 static int
1554 make_equivalent_phi_alternatives_equivalent (bb, reg_partition)
1555      int bb;
1556      partition reg_partition;
1557 {
1558   int changed = 0;
1559   basic_block b = BASIC_BLOCK (bb);
1560   rtx phi;
1561
1562   /* Advance to the first phi node.  */
1563   phi = first_insn_after_basic_block_note (b);
1564
1565   /* Scan all the phi nodes.  */
1566   for (; 
1567        PHI_NODE_P (phi);
1568        phi = next_nonnote_insn (phi))
1569     {
1570       rtx set = PATTERN (phi);
1571       /* The regno of the destination of the set.  */
1572       int tgt_regno = REGNO (SET_DEST (PATTERN (phi)));
1573
1574       rtx phi2 = next_nonnote_insn (phi);
1575
1576       /* Scan all phi nodes following this one.  */
1577       for (;
1578            PHI_NODE_P (phi2);
1579            phi2 = next_nonnote_insn (phi2))
1580         {
1581           rtx set2 = PATTERN (phi2);
1582           /* The regno of the destination of the set.  */
1583           int tgt2_regno = REGNO (SET_DEST (set2));
1584                   
1585           /* Are the set destinations equivalent regs?  */
1586           if (partition_find (reg_partition, tgt_regno) ==
1587               partition_find (reg_partition, tgt2_regno))
1588             {
1589               edge e;
1590               /* Scan over edges.  */
1591               for (e = b->pred; e; e = e->pred_next)
1592                 {
1593                   int pred_block = e->src->index;
1594                   /* Identify the phi alternatives from both phi
1595                      nodes corresponding to this edge.  */
1596                   rtx *alt = phi_alternative (set, pred_block);
1597                   rtx *alt2 = phi_alternative (set2, pred_block);
1598
1599                   /* If one of the phi nodes doesn't have a
1600                      corresponding alternative, just skip it.  */
1601                   if (alt == 0 || alt2 == 0)
1602                     continue;
1603
1604                   /* Both alternatives should be SSA registers.  */
1605                   if (GET_CODE (*alt) != REG
1606                       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
1607                     abort ();
1608                   if (GET_CODE (*alt2) != REG
1609                       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt2)))
1610                     abort ();
1611
1612                   /* If the alternatives aren't already in the same
1613                      class ... */
1614                   if (partition_find (reg_partition, REGNO (*alt)) 
1615                       != partition_find (reg_partition, REGNO (*alt2)))
1616                     {
1617                       /* ... make them so.  */
1618                       if (conflicting_hard_regs_p (REGNO (*alt), REGNO (*alt2)))
1619                         /* It is illegal to unify a hard register with
1620                            a different register. */
1621                         abort ();
1622
1623                       partition_union (reg_partition, 
1624                                        REGNO (*alt), REGNO (*alt2));
1625                       ++changed;
1626                     }
1627                 }
1628             }
1629         }
1630     }
1631
1632   return changed;
1633 }
1634
1635 /* Compute a conservative partition of outstanding pseudo registers.
1636    See Morgan 7.3.1.  */
1637
1638 static partition
1639 compute_conservative_reg_partition ()
1640 {
1641   int bb;
1642   int changed = 0;
1643
1644   /* We don't actually work with hard registers, but it's easier to
1645      carry them around anyway rather than constantly doing register
1646      number arithmetic.  */
1647   partition p = 
1648     partition_new (ssa_definition->num_elements);
1649
1650   /* The first priority is to make sure registers that might have to
1651      be copied on abnormal critical edges are placed in the same
1652      partition.  This saves us from having to split abnormal critical
1653      edges.  */
1654   for (bb = n_basic_blocks; --bb >= 0; )
1655     changed += make_regs_equivalent_over_bad_edges (bb, p);
1656   
1657   /* Now we have to insure that corresponding arguments of phi nodes
1658      assigning to corresponding regs are equivalent.  Iterate until
1659      nothing changes.  */
1660   while (changed > 0)
1661     {
1662       changed = 0;
1663       for (bb = n_basic_blocks; --bb >= 0; )
1664         changed += make_equivalent_phi_alternatives_equivalent (bb, p);
1665     }
1666
1667   return p;
1668 }
1669
1670 /* The following functions compute a register partition that attempts
1671    to eliminate as many reg copies and phi node copies as possible by
1672    coalescing registers.   This is the strategy:
1673
1674     1. As in the conservative case, the top priority is to coalesce
1675        registers that otherwise would cause copies to be placed on
1676        abnormal critical edges (which isn't possible).
1677
1678     2. Figure out which regs are involved (in the LHS or RHS) of
1679        copies and phi nodes.  Compute conflicts among these regs.  
1680
1681     3. Walk around the instruction stream, placing two regs in the
1682        same class of the partition if one appears on the LHS and the
1683        other on the RHS of a copy or phi node and the two regs don't
1684        conflict.  The conflict information of course needs to be
1685        updated.  
1686
1687     4. If anything has changed, there may be new opportunities to
1688        coalesce regs, so go back to 2.
1689 */
1690
1691 /* If REG1 and REG2 don't conflict in CONFLICTS, place them in the
1692    same class of partition P, if they aren't already.  Update
1693    CONFLICTS appropriately.  
1694
1695    Returns one if REG1 and REG2 were placed in the same class but were
1696    not previously; zero otherwise.  
1697
1698    See Morgan figure 11.15.  */
1699
1700 static int 
1701 coalesce_if_unconflicting (p, conflicts, reg1, reg2)
1702      partition p;
1703      conflict_graph conflicts;
1704      int reg1;
1705      int reg2;
1706 {
1707   int reg;
1708
1709   /* Work only on SSA registers. */
1710   if (!CONVERT_REGISTER_TO_SSA_P (reg1) || !CONVERT_REGISTER_TO_SSA_P (reg2))
1711     return 0;
1712
1713   /* Find the canonical regs for the classes containing REG1 and
1714      REG2.  */
1715   reg1 = partition_find (p, reg1);
1716   reg2 = partition_find (p, reg2);
1717   
1718   /* If they're already in the same class, there's nothing to do.  */
1719   if (reg1 == reg2)
1720     return 0;
1721
1722   /* If the regs conflict, our hands are tied.  */
1723   if (conflicting_hard_regs_p (reg1, reg2) ||
1724       conflict_graph_conflict_p (conflicts, reg1, reg2))
1725     return 0;
1726
1727   /* We're good to go.  Put the regs in the same partition.  */
1728   partition_union (p, reg1, reg2);
1729
1730   /* Find the new canonical reg for the merged class.  */
1731   reg = partition_find (p, reg1);
1732   
1733   /* Merge conflicts from the two previous classes.  */
1734   conflict_graph_merge_regs (conflicts, reg, reg1);
1735   conflict_graph_merge_regs (conflicts, reg, reg2);
1736
1737   return 1;
1738 }
1739
1740 /* For each register copy insn in basic block BB, place the LHS and
1741    RHS regs in the same class in partition P if they do not conflict
1742    according to CONFLICTS.
1743
1744    Returns the number of changes that were made to P.
1745
1746    See Morgan figure 11.14.  */
1747
1748 static int
1749 coalesce_regs_in_copies (bb, p, conflicts)
1750      basic_block bb;
1751      partition p;
1752      conflict_graph conflicts;
1753 {
1754   int changed = 0;
1755   rtx insn;
1756   rtx end = bb->end;
1757
1758   /* Scan the instruction stream of the block.  */
1759   for (insn = bb->head; insn != end; insn = NEXT_INSN (insn))
1760     {
1761       rtx pattern;
1762       rtx src;
1763       rtx dest;
1764
1765       /* If this isn't a set insn, go to the next insn.  */
1766       if (GET_CODE (insn) != INSN)
1767         continue;
1768       pattern = PATTERN (insn);
1769       if (GET_CODE (pattern) != SET)
1770         continue;
1771
1772       src = SET_SRC (pattern);
1773       dest = SET_DEST (pattern);
1774
1775       /* We're only looking for copies.  */
1776       if (GET_CODE (src) != REG || GET_CODE (dest) != REG)
1777         continue;
1778
1779       /* Coalesce only if the reg modes are the same.  As long as
1780          each reg's rtx is unique, it can have only one mode, so two
1781          pseudos of different modes can't be coalesced into one.  
1782
1783          FIXME: We can probably get around this by inserting SUBREGs
1784          where appropriate, but for now we don't bother.  */
1785       if (GET_MODE (src) != GET_MODE (dest))
1786         continue;
1787
1788       /* Found a copy; see if we can use the same reg for both the
1789          source and destination (and thus eliminate the copy,
1790          ultimately).  */
1791       changed += coalesce_if_unconflicting (p, conflicts, 
1792                                             REGNO (src), REGNO (dest));
1793     }
1794
1795   return changed;
1796 }
1797
1798 struct phi_coalesce_context
1799 {
1800   partition p;
1801   conflict_graph conflicts;
1802   int changed;
1803 };
1804
1805 /* Callback function for for_each_successor_phi.  If the set
1806    destination and the phi alternative regs do not conflict, place
1807    them in the same paritition class.  DATA is a pointer to a
1808    phi_coalesce_context struct.  */
1809
1810 static int
1811 coalesce_reg_in_phi (insn, dest_regno, src_regno, data)
1812      rtx insn ATTRIBUTE_UNUSED;
1813      int dest_regno;
1814      int src_regno;
1815      void *data;
1816 {
1817   struct phi_coalesce_context *context = 
1818     (struct phi_coalesce_context *) data;
1819   
1820   /* Attempt to use the same reg, if they don't conflict.  */
1821   context->changed 
1822     += coalesce_if_unconflicting (context->p, context->conflicts, 
1823                                   dest_regno, src_regno);
1824   return 0;
1825 }
1826
1827 /* For each alternative in a phi function corresponding to basic block
1828    BB (in phi nodes in successor block to BB), place the reg in the
1829    phi alternative and the reg to which the phi value is set into the
1830    same class in partition P, if allowed by CONFLICTS.  
1831
1832    Return the number of changes that were made to P.
1833    
1834    See Morgan figure 11.14.  */
1835
1836 static int
1837 coalesce_regs_in_successor_phi_nodes (bb, p, conflicts)
1838      basic_block bb;
1839      partition p;
1840      conflict_graph conflicts;
1841 {
1842   struct phi_coalesce_context context;
1843   context.p = p;
1844   context.conflicts = conflicts;
1845   context.changed = 0;
1846
1847   for_each_successor_phi (bb, &coalesce_reg_in_phi, &context);
1848
1849   return context.changed;
1850 }
1851
1852 /* Compute and return a partition of pseudos.  Where possible,
1853    non-conflicting pseudos are placed in the same class.  
1854
1855    The caller is responsible for deallocating the returned partition.  */
1856
1857 static partition
1858 compute_coalesced_reg_partition ()
1859 {
1860   int bb;
1861   int changed = 0;
1862
1863   partition p = 
1864     partition_new (ssa_definition->num_elements);
1865
1866   /* The first priority is to make sure registers that might have to
1867      be copied on abnormal critical edges are placed in the same
1868      partition.  This saves us from having to split abnormal critical
1869      edges (which can't be done).  */
1870   for (bb = n_basic_blocks; --bb >= 0; )
1871     make_regs_equivalent_over_bad_edges (bb, p);
1872
1873   do
1874     {
1875       regset_head phi_set;
1876       conflict_graph conflicts;
1877
1878       changed = 0;
1879
1880       /* Build the set of registers involved in phi nodes, either as
1881          arguments to the phi function or as the target of a set.  */
1882       INITIALIZE_REG_SET (phi_set);
1883       mark_phi_and_copy_regs (&phi_set);
1884
1885       /* Compute conflicts.  */
1886       conflicts = conflict_graph_compute (&phi_set, p);
1887
1888       /* FIXME: Better would be to process most frequently executed
1889          blocks first, so that most frequently executed copies would
1890          be more likely to be removed by register coalescing.  But any
1891          order will generate correct, if non-optimal, results.  */
1892       for (bb = n_basic_blocks; --bb >= 0; )
1893         {
1894           basic_block block = BASIC_BLOCK (bb);
1895           changed += coalesce_regs_in_copies (block, p, conflicts);
1896           changed += 
1897             coalesce_regs_in_successor_phi_nodes (block, p, conflicts);
1898         }
1899
1900       conflict_graph_delete (conflicts);
1901     }
1902   while (changed > 0);
1903
1904   return p;
1905 }
1906
1907 /* Mark the regs in a phi node.  PTR is a phi expression or one of its
1908    components (a REG or a CONST_INT).  DATA is a reg set in which to
1909    set all regs.  Called from for_each_rtx.  */
1910
1911 static int
1912 mark_reg_in_phi (ptr, data)
1913      rtx *ptr;
1914      void *data;
1915 {
1916   rtx expr = *ptr;
1917   regset set = (regset) data;
1918
1919   switch (GET_CODE (expr))
1920     {
1921     case REG:
1922       SET_REGNO_REG_SET (set, REGNO (expr));
1923       /* Fall through.  */
1924     case CONST_INT:
1925     case PHI:
1926       return 0;
1927     default:
1928       abort ();
1929     }
1930 }
1931
1932 /* Mark in PHI_SET all pseudos that are used in a phi node -- either
1933    set from a phi expression, or used as an argument in one.  Also
1934    mark regs that are the source or target of a reg copy.  Uses
1935    ssa_definition.  */
1936
1937 static void
1938 mark_phi_and_copy_regs (phi_set)
1939      regset phi_set;
1940 {
1941   unsigned int reg;
1942
1943   /* Scan the definitions of all regs.  */
1944   for (reg = 0; reg < VARRAY_SIZE (ssa_definition); ++reg)
1945     if (CONVERT_REGISTER_TO_SSA_P (reg))
1946       {
1947         rtx insn = VARRAY_RTX (ssa_definition, reg);
1948         rtx pattern;
1949         rtx src;
1950
1951         if (insn == NULL)
1952           continue;
1953         pattern = PATTERN (insn);
1954         /* Sometimes we get PARALLEL insns.  These aren't phi nodes or
1955            copies.  */
1956         if (GET_CODE (pattern) != SET)
1957           continue;
1958         src = SET_SRC (pattern);
1959
1960         if (GET_CODE (src) == REG)
1961           {
1962             /* It's a reg copy.  */
1963             SET_REGNO_REG_SET (phi_set, reg);
1964             SET_REGNO_REG_SET (phi_set, REGNO (src));
1965           }
1966         else if (GET_CODE (src) == PHI)
1967           {
1968             /* It's a phi node.  Mark the reg being set.  */
1969             SET_REGNO_REG_SET (phi_set, reg);
1970             /* Mark the regs used in the phi function.  */
1971             for_each_rtx (&src, mark_reg_in_phi, phi_set);
1972           }
1973         /* ... else nothing to do.  */
1974       }
1975 }
1976
1977 /* Rename regs in insn PTR that are equivalent.  DATA is the register
1978    partition which specifies equivalences.  */
1979
1980 static int
1981 rename_equivalent_regs_in_insn (ptr, data)
1982      rtx *ptr;
1983      void* data;
1984 {
1985   rtx x = *ptr;
1986   partition reg_partition = (partition) data;
1987
1988   if (x == NULL_RTX)
1989     return 0;
1990
1991   switch (GET_CODE (x))
1992     {
1993     case REG:
1994       if (CONVERT_REGISTER_TO_SSA_P (REGNO (x)))
1995         {
1996           unsigned int regno = REGNO (x);
1997           unsigned int new_regno = partition_find (reg_partition, regno);
1998           rtx canonical_element_rtx = ssa_rename_from_lookup (new_regno);
1999
2000           if (canonical_element_rtx != NULL_RTX && 
2001               HARD_REGISTER_P (canonical_element_rtx))
2002             {
2003               if (REGNO (canonical_element_rtx) != regno)
2004                 *ptr = canonical_element_rtx;
2005             }
2006           else if (regno != new_regno)
2007             {
2008               rtx new_reg = regno_reg_rtx[new_regno];
2009               if (GET_MODE (x) != GET_MODE (new_reg))
2010                 abort ();
2011               *ptr = new_reg;
2012             }
2013         }
2014       return -1;
2015
2016     case PHI:
2017       /* No need to rename the phi nodes.  We'll check equivalence
2018          when inserting copies.  */
2019       return -1;
2020
2021     default:
2022       /* Anything else, continue traversing.  */
2023       return 0;
2024     }
2025 }
2026
2027 /* Record the register's canonical element stored in SRFP in the
2028    canonical_elements sbitmap packaged in DATA.  This function is used
2029    as a callback function for traversing ssa_rename_from.  */
2030
2031 static int
2032 record_canonical_element_1 (srfp, data)
2033      void **srfp;
2034      void *data;
2035 {
2036   unsigned int reg = ((ssa_rename_from_pair *) *srfp)->reg;
2037   sbitmap canonical_elements =
2038     ((struct ssa_rename_from_hash_table_data *) data)->canonical_elements;
2039   partition reg_partition =
2040     ((struct ssa_rename_from_hash_table_data *) data)->reg_partition;
2041   
2042   SET_BIT (canonical_elements, partition_find (reg_partition, reg));
2043   return 1;
2044 }
2045
2046 /* For each class in the REG_PARTITION corresponding to a particular
2047    hard register and machine mode, check that there are no other
2048    classes with the same hard register and machine mode.  Returns
2049    nonzero if this is the case, i.e., the partition is acceptable.  */
2050
2051 static int
2052 check_hard_regs_in_partition (reg_partition)
2053      partition reg_partition;
2054 {
2055   /* CANONICAL_ELEMENTS has a nonzero bit if a class with the given register
2056      number and machine mode has already been seen.  This is a
2057      problem with the partition.  */
2058   sbitmap canonical_elements;
2059   int element_index;
2060   int already_seen[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];
2061   int reg;
2062   int mach_mode;
2063
2064   /* Collect a list of canonical elements.  */
2065   canonical_elements = sbitmap_alloc (max_reg_num ());
2066   sbitmap_zero (canonical_elements);
2067   ssa_rename_from_traverse (&record_canonical_element_1,
2068                             canonical_elements, reg_partition);
2069
2070   /* We have not seen any hard register uses.  */
2071   for (reg = 0; reg < FIRST_PSEUDO_REGISTER; ++reg)
2072     for (mach_mode = 0; mach_mode < NUM_MACHINE_MODES; ++mach_mode)
2073       already_seen[reg][mach_mode] = 0;
2074
2075   /* Check for classes with the same hard register and machine mode.  */
2076   EXECUTE_IF_SET_IN_SBITMAP (canonical_elements, 0, element_index,
2077   {
2078     rtx hard_reg_rtx = ssa_rename_from_lookup (element_index);
2079     if (hard_reg_rtx != NULL_RTX &&
2080         HARD_REGISTER_P (hard_reg_rtx) &&
2081         already_seen[REGNO (hard_reg_rtx)][GET_MODE (hard_reg_rtx)] != 0)
2082           /* Two distinct partition classes should be mapped to the same
2083              hard register.  */
2084           return 0;
2085   });
2086
2087   sbitmap_free (canonical_elements);
2088
2089   return 1;
2090 }
2091
2092 /* Rename regs that are equivalent in REG_PARTITION.  Also collapse
2093    any SEQUENCE insns.  */
2094
2095 static void
2096 rename_equivalent_regs (reg_partition)
2097      partition reg_partition;
2098 {
2099   int bb;
2100
2101   for (bb = n_basic_blocks; --bb >= 0; )
2102     {
2103       basic_block b = BASIC_BLOCK (bb);
2104       rtx next = b->head;
2105       rtx last = b->end;
2106       rtx insn;
2107
2108       do
2109         {
2110           insn = next;
2111           if (INSN_P (insn))
2112             {
2113               for_each_rtx (&PATTERN (insn), 
2114                             rename_equivalent_regs_in_insn, 
2115                             reg_partition);
2116               for_each_rtx (&REG_NOTES (insn), 
2117                             rename_equivalent_regs_in_insn, 
2118                             reg_partition);
2119
2120               if (GET_CODE (PATTERN (insn)) == SEQUENCE)
2121                 {
2122                   rtx s = PATTERN (insn);
2123                   int slen = XVECLEN (s, 0);
2124                   int i;
2125
2126                   if (slen <= 1)
2127                     abort();
2128
2129                   PATTERN (insn) = XVECEXP (s, 0, slen-1);
2130                   for (i = 0; i < slen - 1; i++)
2131                     emit_block_insn_before (XVECEXP (s, 0, i), insn, b);
2132                 }
2133             }
2134
2135           next = NEXT_INSN (insn);
2136         }
2137       while (insn != last);
2138     }
2139 }
2140
2141 /* The main entry point for moving from SSA.  */
2142
2143 void
2144 convert_from_ssa()
2145 {
2146   int bb;
2147   partition reg_partition;
2148   rtx insns = get_insns ();
2149
2150   /* Need global_live_at_{start,end} up to date.  There should not be
2151      any significant dead code at this point, except perhaps dead
2152      stores.  So do not take the time to perform dead code elimination. 
2153
2154      Register coalescing needs death notes, so generate them.  */
2155   life_analysis (insns, NULL, PROP_DEATH_NOTES);
2156
2157   /* Figure out which regs in copies and phi nodes don't conflict and
2158      therefore can be coalesced.  */
2159   if (conservative_reg_partition)
2160     reg_partition = compute_conservative_reg_partition ();
2161   else
2162     reg_partition = compute_coalesced_reg_partition ();
2163
2164   if (!check_hard_regs_in_partition (reg_partition))
2165     /* Two separate partitions should correspond to the same hard
2166        register but do not.  */
2167     abort ();
2168
2169   rename_equivalent_regs (reg_partition);
2170
2171   /* Eliminate the PHI nodes.  */
2172   for (bb = n_basic_blocks; --bb >= 0; )
2173     {
2174       basic_block b = BASIC_BLOCK (bb);
2175       edge e;
2176
2177       for (e = b->pred; e; e = e->pred_next)
2178         if (e->src != ENTRY_BLOCK_PTR)
2179           eliminate_phi (e, reg_partition);
2180     }
2181
2182   partition_delete (reg_partition);
2183
2184   /* Actually delete the PHI nodes.  */
2185   for (bb = n_basic_blocks; --bb >= 0; )
2186     {
2187       rtx insn = BLOCK_HEAD (bb);
2188
2189       while (1)
2190         {
2191           /* If this is a PHI node delete it.  */
2192           if (PHI_NODE_P (insn))
2193             {
2194               if (insn == BLOCK_END (bb))
2195                 BLOCK_END (bb) = PREV_INSN (insn);
2196               insn = delete_insn (insn);
2197             }
2198           /* Since all the phi nodes come at the beginning of the
2199              block, if we find an ordinary insn, we can stop looking
2200              for more phi nodes.  */
2201           else if (INSN_P (insn))
2202             break;
2203           /* If we've reached the end of the block, stop.  */
2204           else if (insn == BLOCK_END (bb))
2205             break;
2206           else 
2207             insn = NEXT_INSN (insn);
2208         }
2209     }
2210
2211   /* Commit all the copy nodes needed to convert out of SSA form.  */
2212   commit_edge_insertions ();
2213
2214   in_ssa_form = 0;
2215
2216   count_or_remove_death_notes (NULL, 1);
2217
2218   /* Deallocate the data structures.  */
2219   VARRAY_FREE (ssa_definition);
2220   ssa_rename_from_free ();
2221 }
2222
2223 /* Scan phi nodes in successors to BB.  For each such phi node that
2224    has a phi alternative value corresponding to BB, invoke FN.  FN
2225    is passed the entire phi node insn, the regno of the set
2226    destination, the regno of the phi argument corresponding to BB,
2227    and DATA.
2228
2229    If FN ever returns non-zero, stops immediately and returns this
2230    value.  Otherwise, returns zero.  */
2231
2232 int
2233 for_each_successor_phi (bb, fn, data)
2234      basic_block bb;
2235      successor_phi_fn fn;
2236      void *data;
2237 {
2238   edge e;
2239   
2240   if (bb == EXIT_BLOCK_PTR)
2241     return 0;
2242
2243   /* Scan outgoing edges.  */
2244   for (e = bb->succ; e != NULL; e = e->succ_next)
2245     {
2246       rtx insn;
2247
2248       basic_block successor = e->dest;
2249       if (successor == ENTRY_BLOCK_PTR 
2250           || successor == EXIT_BLOCK_PTR)
2251         continue;
2252
2253       /* Advance to the first non-label insn of the successor block.  */
2254       insn = first_insn_after_basic_block_note (successor);
2255
2256       if (insn == NULL)
2257         continue;
2258
2259       /* Scan phi nodes in the successor.  */
2260       for ( ; PHI_NODE_P (insn); insn = NEXT_INSN (insn))
2261         {
2262           int result;
2263           rtx phi_set = PATTERN (insn);
2264           rtx *alternative = phi_alternative (phi_set, bb->index);
2265           rtx phi_src;
2266           
2267           /* This phi function may not have an alternative
2268              corresponding to the incoming edge, indicating the
2269              assigned variable is not defined along the edge.  */
2270           if (alternative == NULL)
2271             continue;
2272           phi_src = *alternative;
2273
2274           /* Invoke the callback.  */
2275           result = (*fn) (insn, REGNO (SET_DEST (phi_set)), 
2276                           REGNO (phi_src), data);
2277
2278           /* Terminate if requested.  */
2279           if (result != 0)
2280             return result;
2281         }
2282     }
2283
2284   return 0;
2285 }
2286
2287 /* Assuming the ssa_rename_from mapping has been established, yields
2288    nonzero if 1) only one SSA register of REG1 and REG2 comes from a
2289    hard register or 2) both SSA registers REG1 and REG2 come from
2290    different hard registers.  */
2291
2292 static int
2293 conflicting_hard_regs_p (reg1, reg2)
2294      int reg1;
2295      int reg2;
2296 {
2297   int orig_reg1 = original_register (reg1);
2298   int orig_reg2 = original_register (reg2);
2299   if (HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2)
2300       && orig_reg1 != orig_reg2)
2301     return 1;
2302   if (HARD_REGISTER_NUM_P (orig_reg1) && !HARD_REGISTER_NUM_P (orig_reg2))
2303     return 1;
2304   if (!HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2))
2305     return 1;
2306   
2307   return 0;
2308 }