OSDN Git Service

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