OSDN Git Service

PR tree-opt/14329
[pf3gnuchains/gcc-fork.git] / gcc / tree-outof-ssa.c
1 /* Convert a program in SSA form into Normal form.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Andrew Macleod <amacleod@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "ggc.h"
31 #include "langhooks.h"
32 #include "hard-reg-set.h"
33 #include "basic-block.h"
34 #include "output.h"
35 #include "errors.h"
36 #include "expr.h"
37 #include "function.h"
38 #include "diagnostic.h"
39 #include "bitmap.h"
40 #include "tree-flow.h"
41 #include "tree-gimple.h"
42 #include "tree-inline.h"
43 #include "varray.h"
44 #include "timevar.h"
45 #include "hashtab.h"
46 #include "tree-dump.h"
47 #include "tree-ssa-live.h"
48 #include "tree-pass.h"
49
50 /* Flags to pass to remove_ssa_form.  */
51
52 #define SSANORM_PERFORM_TER             0x1
53 #define SSANORM_COMBINE_TEMPS           0x2
54 #define SSANORM_REMOVE_ALL_PHIS         0x4
55 #define SSANORM_COALESCE_PARTITIONS     0x8
56 #define SSANORM_USE_COALESCE_LIST       0x10
57
58 /* Used to hold all the components required to do SSA PHI elimination.
59    The node and pred/succ list is a simple linear list of nodes and
60    edges represented as pairs of nodes.
61
62    The predecessor and successor list:  Nodes are entered in pairs, where
63    [0] ->PRED, [1]->SUCC.  All the even indexes in the array represent 
64    predecessors, all the odd elements are successors. 
65    
66    Rationale:
67    When implemented as bitmaps, very large programs SSA->Normal times were 
68    being dominated by clearing the interference graph.
69
70    Typically this list of edges is extremely small since it only includes 
71    PHI results and uses from a single edge which have not coalesced with 
72    each other.  This means that no virtual PHI nodes are included, and
73    empirical evidence suggests that the number of edges rarely exceed
74    3, and in a bootstrap of GCC, the maximum size encountered was 7.
75    This also limits the number of possible nodes that are involved to
76    rarely more than 6, and in the bootstrap of gcc, the maximum number
77    of nodes encountered was 12.  */
78  
79 typedef struct _elim_graph {
80   /* Size of the elimination vectors.  */
81   int size;
82
83   /* List of nodes in the elimination graph.  */
84   varray_type nodes;
85
86   /*  The predecessor and successor edge list.  */
87   varray_type edge_list;
88
89   /* Visited vector.  */
90   sbitmap visited;
91
92   /* Stack for visited nodes.  */
93   varray_type stack;
94   
95   /* The variable partition map.  */
96   var_map map;
97
98   /* Edge being eliminated by this graph.  */
99   edge e;
100
101   /* List of constant copies to emit.  These are pushed on in pairs.  */
102   varray_type  const_copies;
103 } *elim_graph;
104
105
106 /* Local functions.  */
107 static tree create_temp (tree);
108 static void insert_copy_on_edge (edge, tree, tree);
109 static elim_graph new_elim_graph (int);
110 static inline void delete_elim_graph (elim_graph);
111 static inline void clear_elim_graph (elim_graph);
112 static inline int elim_graph_size (elim_graph);
113 static inline void elim_graph_add_node (elim_graph, tree);
114 static inline void elim_graph_add_edge (elim_graph, int, int);
115 static inline int elim_graph_remove_succ_edge (elim_graph, int);
116
117 static inline void eliminate_name (elim_graph, tree);
118 static void eliminate_build (elim_graph, basic_block);
119 static void elim_forward (elim_graph, int);
120 static int elim_unvisited_predecessor (elim_graph, int);
121 static void elim_backward (elim_graph, int);
122 static void elim_create (elim_graph, int);
123 static void eliminate_phi (edge, elim_graph);
124 static tree_live_info_p coalesce_ssa_name (var_map, int);
125 static void assign_vars (var_map);
126 static bool replace_use_variable (var_map, use_operand_p, tree *);
127 static bool replace_def_variable (var_map, def_operand_p, tree *);
128 static void eliminate_virtual_phis (void);
129 static void coalesce_abnormal_edges (var_map, conflict_graph, root_var_p);
130 static void print_exprs (FILE *, const char *, tree, const char *, tree,
131                          const char *);
132 static void print_exprs_edge (FILE *, edge, const char *, tree, const char *,
133                               tree);
134
135
136 /* Create a temporary variable based on the type of variable T.  Use T's name
137    as the prefix.  */
138
139 static tree
140 create_temp (tree t)
141 {
142   tree tmp;
143   const char *name = NULL;
144   tree type;
145
146   if (TREE_CODE (t) == SSA_NAME)
147     t = SSA_NAME_VAR (t);
148
149   gcc_assert (TREE_CODE (t) == VAR_DECL || TREE_CODE (t) == PARM_DECL);
150
151   type = TREE_TYPE (t);
152   tmp = DECL_NAME (t);
153   if (tmp)
154     name = IDENTIFIER_POINTER (tmp);
155
156   if (name == NULL)
157     name = "temp";
158   tmp = create_tmp_var (type, name);
159
160   if (DECL_DEBUG_EXPR (t) && DECL_DEBUG_EXPR_IS_FROM (t))
161     {
162       DECL_DEBUG_EXPR (tmp) = DECL_DEBUG_EXPR (t);  
163       DECL_DEBUG_EXPR_IS_FROM (tmp) = 1;
164     }
165   else if (!DECL_IGNORED_P (t))
166     {
167       DECL_DEBUG_EXPR (tmp) = t;
168       DECL_DEBUG_EXPR_IS_FROM (tmp) = 1;
169     }
170   DECL_ARTIFICIAL (tmp) = DECL_ARTIFICIAL (t);
171   DECL_IGNORED_P (tmp) = DECL_IGNORED_P (t);
172   add_referenced_tmp_var (tmp);
173
174   /* add_referenced_tmp_var will create the annotation and set up some
175      of the flags in the annotation.  However, some flags we need to
176      inherit from our original variable.  */
177   var_ann (tmp)->type_mem_tag = var_ann (t)->type_mem_tag;
178   if (is_call_clobbered (t))
179     mark_call_clobbered (tmp);
180
181   return tmp;
182 }
183
184
185 /* This helper function fill insert a copy from a constant or variable SRC to 
186    variable DEST on edge E.  */
187
188 static void
189 insert_copy_on_edge (edge e, tree dest, tree src)
190 {
191   tree copy;
192
193   copy = build (MODIFY_EXPR, TREE_TYPE (dest), dest, src);
194   set_is_used (dest);
195
196   if (TREE_CODE (src) == ADDR_EXPR)
197     src = TREE_OPERAND (src, 0);
198   if (TREE_CODE (src) == VAR_DECL || TREE_CODE (src) == PARM_DECL)
199     set_is_used (src);
200
201   if (dump_file && (dump_flags & TDF_DETAILS))
202     {
203       fprintf (dump_file,
204                "Inserting a copy on edge BB%d->BB%d :",
205                e->src->index,
206                e->dest->index);
207       print_generic_expr (dump_file, copy, dump_flags);
208       fprintf (dump_file, "\n");
209     }
210
211   bsi_insert_on_edge (e, copy);
212 }
213
214
215 /* Create an elimination graph with SIZE nodes and associated data
216    structures.  */
217
218 static elim_graph
219 new_elim_graph (int size)
220 {
221   elim_graph g = (elim_graph) xmalloc (sizeof (struct _elim_graph));
222
223   VARRAY_TREE_INIT (g->nodes, 30, "Elimination Node List");
224   VARRAY_TREE_INIT (g->const_copies, 20, "Elimination Constant Copies");
225   VARRAY_INT_INIT (g->edge_list, 20, "Elimination Edge List");
226   VARRAY_INT_INIT (g->stack, 30, " Elimination Stack");
227   
228   g->visited = sbitmap_alloc (size);
229
230   return g;
231 }
232
233
234 /* Empty elimination graph G.  */
235
236 static inline void
237 clear_elim_graph (elim_graph g)
238 {
239   VARRAY_POP_ALL (g->nodes);
240   VARRAY_POP_ALL (g->edge_list);
241 }
242
243
244 /* Delete elimination graph G.  */
245
246 static inline void
247 delete_elim_graph (elim_graph g)
248 {
249   sbitmap_free (g->visited);
250   free (g);
251 }
252
253
254 /* Return the number of nodes in graph G.  */
255
256 static inline int
257 elim_graph_size (elim_graph g)
258 {
259   return VARRAY_ACTIVE_SIZE (g->nodes);
260 }
261
262
263 /* Add NODE to graph G, if it doesn't exist already.  */
264
265 static inline void 
266 elim_graph_add_node (elim_graph g, tree node)
267 {
268   int x;
269   for (x = 0; x < elim_graph_size (g); x++)
270     if (VARRAY_TREE (g->nodes, x) == node)
271       return;
272   VARRAY_PUSH_TREE (g->nodes, node);
273 }
274
275
276 /* Add the edge PRED->SUCC to graph G.  */
277
278 static inline void
279 elim_graph_add_edge (elim_graph g, int pred, int succ)
280 {
281   VARRAY_PUSH_INT (g->edge_list, pred);
282   VARRAY_PUSH_INT (g->edge_list, succ);
283 }
284
285
286 /* Remove an edge from graph G for which NODE is the predecessor, and
287    return the successor node.  -1 is returned if there is no such edge.  */
288
289 static inline int
290 elim_graph_remove_succ_edge (elim_graph g, int node)
291 {
292   int y;
293   unsigned x;
294   for (x = 0; x < VARRAY_ACTIVE_SIZE (g->edge_list); x += 2)
295     if (VARRAY_INT (g->edge_list, x) == node)
296       {
297         VARRAY_INT (g->edge_list, x) = -1;
298         y = VARRAY_INT (g->edge_list, x + 1);
299         VARRAY_INT (g->edge_list, x + 1) = -1;
300         return y;
301       }
302   return -1;
303 }
304
305
306 /* Find all the nodes in GRAPH which are successors to NODE in the
307    edge list.  VAR will hold the partition number found.  CODE is the
308    code fragment executed for every node found.  */
309
310 #define FOR_EACH_ELIM_GRAPH_SUCC(GRAPH, NODE, VAR, CODE)                \
311 do {                                                                    \
312   unsigned x_;                                                          \
313   int y_;                                                               \
314   for (x_ = 0; x_ < VARRAY_ACTIVE_SIZE ((GRAPH)->edge_list); x_ += 2)   \
315     {                                                                   \
316       y_ = VARRAY_INT ((GRAPH)->edge_list, x_);                         \
317       if (y_ != (NODE))                                                 \
318         continue;                                                       \
319       (VAR) = VARRAY_INT ((GRAPH)->edge_list, x_ + 1);                  \
320       CODE;                                                             \
321     }                                                                   \
322 } while (0)
323
324
325 /* Find all the nodes which are predecessors of NODE in the edge list for
326    GRAPH.  VAR will hold the partition number found.  CODE is the
327    code fragment executed for every node found.  */
328
329 #define FOR_EACH_ELIM_GRAPH_PRED(GRAPH, NODE, VAR, CODE)                \
330 do {                                                                    \
331   unsigned x_;                                                          \
332   int y_;                                                               \
333   for (x_ = 0; x_ < VARRAY_ACTIVE_SIZE ((GRAPH)->edge_list); x_ += 2)   \
334     {                                                                   \
335       y_ = VARRAY_INT ((GRAPH)->edge_list, x_ + 1);                     \
336       if (y_ != (NODE))                                                 \
337         continue;                                                       \
338       (VAR) = VARRAY_INT ((GRAPH)->edge_list, x_);                      \
339       CODE;                                                             \
340     }                                                                   \
341 } while (0)
342
343
344 /* Add T to elimination graph G.  */
345
346 static inline void
347 eliminate_name (elim_graph g, tree T)
348 {
349   elim_graph_add_node (g, T);
350 }
351
352
353 /* Build elimination graph G for basic block BB on incoming PHI edge
354    G->e.  */
355
356 static void
357 eliminate_build (elim_graph g, basic_block B)
358 {
359   tree phi;
360   tree T0, Ti;
361   int p0, pi;
362
363   clear_elim_graph (g);
364   
365   for (phi = phi_nodes (B); phi; phi = PHI_CHAIN (phi))
366     {
367       T0 = var_to_partition_to_var (g->map, PHI_RESULT (phi));
368       
369       /* Ignore results which are not in partitions.  */
370       if (T0 == NULL_TREE)
371         continue;
372
373       Ti = PHI_ARG_DEF (phi, g->e->dest_idx);
374
375       /* If this argument is a constant, or a SSA_NAME which is being
376          left in SSA form, just queue a copy to be emitted on this
377          edge.  */
378       if (!phi_ssa_name_p (Ti)
379           || (TREE_CODE (Ti) == SSA_NAME
380               && var_to_partition (g->map, Ti) == NO_PARTITION))
381         {
382           /* Save constant copies until all other copies have been emitted
383              on this edge.  */
384           VARRAY_PUSH_TREE (g->const_copies, T0);
385           VARRAY_PUSH_TREE (g->const_copies, Ti);
386         }
387       else
388         {
389           Ti = var_to_partition_to_var (g->map, Ti);
390           if (T0 != Ti)
391             {
392               eliminate_name (g, T0);
393               eliminate_name (g, Ti);
394               p0 = var_to_partition (g->map, T0);
395               pi = var_to_partition (g->map, Ti);
396               elim_graph_add_edge (g, p0, pi);
397             }
398         }
399     }
400 }
401
402
403 /* Push successors of T onto the elimination stack for G.  */
404
405 static void 
406 elim_forward (elim_graph g, int T)
407 {
408   int S;
409   SET_BIT (g->visited, T);
410   FOR_EACH_ELIM_GRAPH_SUCC (g, T, S,
411     {
412       if (!TEST_BIT (g->visited, S))
413         elim_forward (g, S);
414     });
415   VARRAY_PUSH_INT (g->stack, T);
416 }
417
418
419 /* Return 1 if there unvisited predecessors of T in graph G.  */
420
421 static int
422 elim_unvisited_predecessor (elim_graph g, int T)
423 {
424   int P;
425   FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
426     {
427       if (!TEST_BIT (g->visited, P))
428         return 1;
429     });
430   return 0;
431 }
432
433 /* Process predecessors first, and insert a copy.  */
434
435 static void
436 elim_backward (elim_graph g, int T)
437 {
438   int P;
439   SET_BIT (g->visited, T);
440   FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
441     {
442       if (!TEST_BIT (g->visited, P))
443         {
444           elim_backward (g, P);
445           insert_copy_on_edge (g->e, 
446                                partition_to_var (g->map, P), 
447                                partition_to_var (g->map, T));
448         }
449     });
450 }
451
452 /* Insert required copies for T in graph G.  Check for a strongly connected 
453    region, and create a temporary to break the cycle if one is found.  */
454
455 static void 
456 elim_create (elim_graph g, int T)
457 {
458   tree U;
459   int P, S;
460
461   if (elim_unvisited_predecessor (g, T))
462     {
463       U = create_temp (partition_to_var (g->map, T));
464       insert_copy_on_edge (g->e, U, partition_to_var (g->map, T));
465       FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
466         {
467           if (!TEST_BIT (g->visited, P))
468             {
469               elim_backward (g, P);
470               insert_copy_on_edge (g->e, partition_to_var (g->map, P), U);
471             }
472         });
473     }
474   else
475     {
476       S = elim_graph_remove_succ_edge (g, T);
477       if (S != -1)
478         {
479           SET_BIT (g->visited, T);
480           insert_copy_on_edge (g->e, 
481                                partition_to_var (g->map, T), 
482                                partition_to_var (g->map, S));
483         }
484     }
485   
486 }
487
488 /* Eliminate all the phi nodes on edge E in graph G.  */
489
490 static void
491 eliminate_phi (edge e, elim_graph g)
492 {
493   int num_nodes = 0;
494   int x;
495   basic_block B = e->dest;
496
497   gcc_assert (VARRAY_ACTIVE_SIZE (g->const_copies) == 0);
498
499   /* Abnormal edges already have everything coalesced, or the coalescer
500      would have aborted.  */
501   if (e->flags & EDGE_ABNORMAL)
502     return;
503
504   num_nodes = num_var_partitions (g->map);
505   g->e = e;
506
507   eliminate_build (g, B);
508
509   if (elim_graph_size (g) != 0)
510     {
511       sbitmap_zero (g->visited);
512       VARRAY_POP_ALL (g->stack);
513
514       for (x = 0; x < elim_graph_size (g); x++)
515         {
516           tree var = VARRAY_TREE (g->nodes, x);
517           int p = var_to_partition (g->map, var);
518           if (!TEST_BIT (g->visited, p))
519             elim_forward (g, p);
520         }
521        
522       sbitmap_zero (g->visited);
523       while (VARRAY_ACTIVE_SIZE (g->stack) > 0)
524         {
525           x = VARRAY_TOP_INT (g->stack);
526           VARRAY_POP (g->stack);
527           if (!TEST_BIT (g->visited, x))
528             elim_create (g, x);
529         }
530     }
531
532   /* If there are any pending constant copies, issue them now.  */
533   while (VARRAY_ACTIVE_SIZE (g->const_copies) > 0)
534     {
535       tree src, dest;
536       src = VARRAY_TOP_TREE (g->const_copies);
537       VARRAY_POP (g->const_copies);
538       dest = VARRAY_TOP_TREE (g->const_copies);
539       VARRAY_POP (g->const_copies);
540       insert_copy_on_edge (e, dest, src);
541     }
542 }
543
544
545 /* Shortcut routine to print messages to file F of the form:
546    "STR1 EXPR1 STR2 EXPR2 STR3."  */
547
548 static void
549 print_exprs (FILE *f, const char *str1, tree expr1, const char *str2,
550              tree expr2, const char *str3)
551 {
552   fprintf (f, "%s", str1);
553   print_generic_expr (f, expr1, TDF_SLIM);
554   fprintf (f, "%s", str2);
555   print_generic_expr (f, expr2, TDF_SLIM);
556   fprintf (f, "%s", str3);
557 }
558
559
560 /* Shortcut routine to print abnormal edge messages to file F of the form:
561    "STR1 EXPR1 STR2 EXPR2 across edge E.  */
562
563 static void
564 print_exprs_edge (FILE *f, edge e, const char *str1, tree expr1, 
565                   const char *str2, tree expr2)
566 {
567   print_exprs (f, str1, expr1, str2, expr2, " across an abnormal edge");
568   fprintf (f, " from BB%d->BB%d\n", e->src->index,
569                e->dest->index);
570 }
571
572
573 /* Coalesce partitions in MAP which are live across abnormal edges in GRAPH.
574    RV is the root variable groupings of the partitions in MAP.  Since code 
575    cannot be inserted on these edges, failure to coalesce something across
576    an abnormal edge is an error.  */
577
578 static void
579 coalesce_abnormal_edges (var_map map, conflict_graph graph, root_var_p rv)
580 {
581   basic_block bb;
582   edge e;
583   tree phi, var, tmp;
584   int x, y, z;
585   edge_iterator ei;
586
587   /* Code cannot be inserted on abnormal edges. Look for all abnormal 
588      edges, and coalesce any PHI results with their arguments across 
589      that edge.  */
590
591   FOR_EACH_BB (bb)
592     FOR_EACH_EDGE (e, ei, bb->succs)
593       if (e->dest != EXIT_BLOCK_PTR && e->flags & EDGE_ABNORMAL)
594         for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
595           {
596             /* Visit each PHI on the destination side of this abnormal
597                edge, and attempt to coalesce the argument with the result.  */
598             var = PHI_RESULT (phi);
599             x = var_to_partition (map, var);
600
601             /* Ignore results which are not relevant.  */
602             if (x == NO_PARTITION)
603               continue;
604
605             tmp = PHI_ARG_DEF (phi, e->dest_idx);
606 #ifdef ENABLE_CHECKING
607             if (!phi_ssa_name_p (tmp))
608               {
609                 print_exprs_edge (stderr, e,
610                                   "\nConstant argument in PHI. Can't insert :",
611                                   var, " = ", tmp);
612                 internal_error ("SSA corruption");
613               }
614 #else
615             gcc_assert (phi_ssa_name_p (tmp));
616 #endif
617             y = var_to_partition (map, tmp);
618             gcc_assert (x != NO_PARTITION);
619             gcc_assert (y != NO_PARTITION);
620 #ifdef ENABLE_CHECKING
621             if (root_var_find (rv, x) != root_var_find (rv, y))
622               {
623                 print_exprs_edge (stderr, e, "\nDifferent root vars: ",
624                                   root_var (rv, root_var_find (rv, x)), 
625                                   " and ", 
626                                   root_var (rv, root_var_find (rv, y)));
627                 internal_error ("SSA corruption");
628               }
629 #else
630             gcc_assert (root_var_find (rv, x) == root_var_find (rv, y));
631 #endif
632
633             if (x != y)
634               {
635 #ifdef ENABLE_CHECKING
636                 if (conflict_graph_conflict_p (graph, x, y))
637                   {
638                     print_exprs_edge (stderr, e, "\n Conflict ", 
639                                       partition_to_var (map, x),
640                                       " and ", partition_to_var (map, y));
641                     internal_error ("SSA corruption");
642                   }
643 #else
644                 gcc_assert (!conflict_graph_conflict_p (graph, x, y));
645 #endif
646                 
647                 /* Now map the partitions back to their real variables.  */
648                 var = partition_to_var (map, x);
649                 tmp = partition_to_var (map, y);
650                 if (dump_file && (dump_flags & TDF_DETAILS))
651                   {
652                     print_exprs_edge (dump_file, e, 
653                                       "ABNORMAL: Coalescing ",
654                                       var, " and ", tmp);
655                   }
656                 z = var_union (map, var, tmp);
657 #ifdef ENABLE_CHECKING
658                 if (z == NO_PARTITION)
659                   {
660                     print_exprs_edge (stderr, e, "\nUnable to coalesce", 
661                                       partition_to_var (map, x), " and ", 
662                                       partition_to_var (map, y));
663                     internal_error ("SSA corruption");
664                   }
665 #else
666                 gcc_assert (z != NO_PARTITION);
667 #endif
668                 gcc_assert (z == x || z == y);
669                 if (z == x)
670                   conflict_graph_merge_regs (graph, x, y);
671                 else
672                   conflict_graph_merge_regs (graph, y, x);
673               }
674           }
675 }
676
677
678 /* Reduce the number of live ranges in MAP.  Live range information is 
679    returned if FLAGS indicates that we are combining temporaries, otherwise 
680    NULL is returned.  The only partitions which are associated with actual 
681    variables at this point are those which are forced to be coalesced for 
682    various reason. (live on entry, live across abnormal edges, etc.).  */
683
684 static tree_live_info_p
685 coalesce_ssa_name (var_map map, int flags)
686 {
687   unsigned num, x, i;
688   sbitmap live;
689   tree var, phi;
690   root_var_p rv;
691   tree_live_info_p liveinfo;
692   var_ann_t ann;
693   conflict_graph graph;
694   basic_block bb;
695   coalesce_list_p cl = NULL;
696
697   if (num_var_partitions (map) <= 1)
698     return NULL;
699
700   /* If no preference given, use cheap coalescing of all partitions.  */
701   if ((flags & (SSANORM_COALESCE_PARTITIONS | SSANORM_USE_COALESCE_LIST)) == 0)
702     flags |= SSANORM_COALESCE_PARTITIONS;
703   
704   liveinfo = calculate_live_on_entry (map);
705   calculate_live_on_exit (liveinfo);
706   rv = root_var_init (map);
707
708   /* Remove single element variable from the list.  */
709   root_var_compact (rv);
710
711   if (flags & SSANORM_USE_COALESCE_LIST)
712     {
713       cl = create_coalesce_list (map);
714       
715       /* Add all potential copies via PHI arguments to the list.  */
716       FOR_EACH_BB (bb)
717         {
718           for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
719             {
720               tree res = PHI_RESULT (phi);
721               int p = var_to_partition (map, res);
722               if (p == NO_PARTITION)
723                 continue;
724               for (x = 0; x < (unsigned)PHI_NUM_ARGS (phi); x++)
725                 {
726                   tree arg = PHI_ARG_DEF (phi, x);
727                   int p2;
728
729                   if (TREE_CODE (arg) != SSA_NAME)
730                     continue;
731                   if (SSA_NAME_VAR (res) != SSA_NAME_VAR (arg))
732                     continue;
733                   p2 = var_to_partition (map, PHI_ARG_DEF (phi, x));
734                   if (p2 != NO_PARTITION)
735                     add_coalesce (cl, p, p2, 1);
736                 }
737             }
738         }
739
740       /* Coalesce all the result decls together.  */
741       var = NULL_TREE;
742       i = 0;
743       for (x = 0; x < num_var_partitions (map); x++)
744         {
745           tree p = partition_to_var (map, x);
746           if (TREE_CODE (SSA_NAME_VAR(p)) == RESULT_DECL)
747             {
748               if (var == NULL_TREE)
749                 {
750                   var = p;
751                   i = x;
752                 }
753               else
754                 add_coalesce (cl, i, x, 1);
755             }
756         }
757     }
758
759   /* Build a conflict graph.  */
760   graph = build_tree_conflict_graph (liveinfo, rv, cl);
761
762   if (cl)
763     {
764       if (dump_file && (dump_flags & TDF_DETAILS))
765         {
766           fprintf (dump_file, "Before sorting:\n");
767           dump_coalesce_list (dump_file, cl);
768         }
769
770       sort_coalesce_list (cl);
771
772       if (dump_file && (dump_flags & TDF_DETAILS))
773         {
774           fprintf (dump_file, "\nAfter sorting:\n");
775           dump_coalesce_list (dump_file, cl);
776         }
777     }
778
779   /* Put the single element variables back in.  */
780   root_var_decompact (rv);
781
782   /* First, coalesce all live on entry variables to their root variable. 
783      This will ensure the first use is coming from the correct location.  */
784
785   live = sbitmap_alloc (num_var_partitions (map));
786   sbitmap_zero (live);
787
788   /* Set 'live' vector to indicate live on entry partitions.  */
789   num = num_var_partitions (map);
790   for (x = 0 ; x < num; x++)
791     {
792       var = partition_to_var (map, x);
793       if (default_def (SSA_NAME_VAR (var)) == var)
794         SET_BIT (live, x);
795     }
796
797   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
798     {
799       delete_tree_live_info (liveinfo);
800       liveinfo = NULL;
801     }
802
803   /* Assign root variable as partition representative for each live on entry
804      partition.  */
805   EXECUTE_IF_SET_IN_SBITMAP (live, 0, x, 
806     {
807       var = root_var (rv, root_var_find (rv, x));
808       ann = var_ann (var);
809       /* If these aren't already coalesced...  */
810       if (partition_to_var (map, x) != var)
811         {
812           /* This root variable should have not already been assigned
813              to another partition which is not coalesced with this one.  */
814           gcc_assert (!ann->out_of_ssa_tag);
815
816           if (dump_file && (dump_flags & TDF_DETAILS))
817             {
818               print_exprs (dump_file, "Must coalesce ", 
819                            partition_to_var (map, x),
820                            " with the root variable ", var, ".\n");
821             }
822
823           change_partition_var (map, var, x);
824         }
825     });
826
827   sbitmap_free (live);
828
829   /* Coalesce partitions live across abnormal edges.  */
830   coalesce_abnormal_edges (map, graph, rv);
831
832   if (dump_file && (dump_flags & TDF_DETAILS))
833     dump_var_map (dump_file, map);
834
835   /* Coalesce partitions.  */
836   if (flags & SSANORM_USE_COALESCE_LIST)
837     coalesce_tpa_members (rv, graph, map, cl, 
838                           ((dump_flags & TDF_DETAILS) ? dump_file 
839                                                            : NULL));
840
841   
842   if (flags & SSANORM_COALESCE_PARTITIONS)
843     coalesce_tpa_members (rv, graph, map, NULL, 
844                           ((dump_flags & TDF_DETAILS) ? dump_file 
845                                                            : NULL));
846   if (cl)
847     delete_coalesce_list (cl);
848   root_var_delete (rv);
849   conflict_graph_delete (graph);
850
851   return liveinfo;
852 }
853
854
855 /* Take the ssa-name var_map MAP, and assign real variables to each 
856    partition.  */
857
858 static void
859 assign_vars (var_map map)
860 {
861   int x, i, num, rep;
862   tree t, var;
863   var_ann_t ann;
864   root_var_p rv;
865
866   rv = root_var_init (map);
867   if (!rv) 
868     return;
869
870   /* Coalescing may already have forced some partitions to their root 
871      variable. Find these and tag them.  */
872
873   num = num_var_partitions (map);
874   for (x = 0; x < num; x++)
875     {
876       var = partition_to_var (map, x);
877       if (TREE_CODE (var) != SSA_NAME)
878         {
879           /* Coalescing will already have verified that more than one
880              partition doesn't have the same root variable. Simply marked
881              the variable as assigned.  */
882           ann = var_ann (var);
883           ann->out_of_ssa_tag = 1;
884           if (dump_file && (dump_flags & TDF_DETAILS))
885             {
886               fprintf (dump_file, "partition %d has variable ", x);
887               print_generic_expr (dump_file, var, TDF_SLIM);
888               fprintf (dump_file, " assigned to it.\n");
889             }
890
891         }
892     }
893
894   num = root_var_num (rv);
895   for (x = 0; x < num; x++)
896     {
897       var = root_var (rv, x);
898       ann = var_ann (var);
899       for (i = root_var_first_partition (rv, x);
900            i != ROOT_VAR_NONE;
901            i = root_var_next_partition (rv, i))
902         {
903           t = partition_to_var (map, i);
904
905           if (t == var || TREE_CODE (t) != SSA_NAME)
906             continue;
907
908           rep = var_to_partition (map, t);
909           
910           if (!ann->out_of_ssa_tag)
911             {
912               if (dump_file && (dump_flags & TDF_DETAILS))
913                 print_exprs (dump_file, "", t, "  --> ", var, "\n");
914               change_partition_var (map, var, rep);
915               continue;
916             }
917
918           if (dump_file && (dump_flags & TDF_DETAILS))
919             print_exprs (dump_file, "", t, " not coalesced with ", var, 
920                          "");
921
922           var = create_temp (t);
923           change_partition_var (map, var, rep);
924           ann = var_ann (var);
925
926           if (dump_file && (dump_flags & TDF_DETAILS))
927             {
928               fprintf (dump_file, " -->  New temp:  '");
929               print_generic_expr (dump_file, var, TDF_SLIM);
930               fprintf (dump_file, "'\n");
931             }
932         }
933     }
934
935   root_var_delete (rv);
936 }
937
938
939 /* Replace use operand P with whatever variable it has been rewritten to based 
940    on the partitions in MAP.  EXPR is an optional expression vector over SSA 
941    versions which is used to replace P with an expression instead of a variable.
942    If the stmt is changed, return true.  */ 
943
944 static inline bool
945 replace_use_variable (var_map map, use_operand_p p, tree *expr)
946 {
947   tree new_var;
948   tree var = USE_FROM_PTR (p);
949
950   /* Check if we are replacing this variable with an expression.  */
951   if (expr)
952     {
953       int version = SSA_NAME_VERSION (var);
954       if (expr[version])
955         {
956           tree new_expr = TREE_OPERAND (expr[version], 1);
957           SET_USE (p, new_expr);
958           /* Clear the stmt's RHS, or GC might bite us.  */
959           TREE_OPERAND (expr[version], 1) = NULL_TREE;
960           return true;
961         }
962     }
963
964   new_var = var_to_partition_to_var (map, var);
965   if (new_var)
966     {
967       SET_USE (p, new_var);
968       set_is_used (new_var);
969       return true;
970     }
971   return false;
972 }
973
974
975 /* Replace def operand DEF_P with whatever variable it has been rewritten to 
976    based on the partitions in MAP.  EXPR is an optional expression vector over
977    SSA versions which is used to replace DEF_P with an expression instead of a 
978    variable.  If the stmt is changed, return true.  */ 
979
980 static inline bool
981 replace_def_variable (var_map map, def_operand_p def_p, tree *expr)
982 {
983   tree new_var;
984   tree var = DEF_FROM_PTR (def_p);
985
986   /* Check if we are replacing this variable with an expression.  */
987   if (expr)
988     {
989       int version = SSA_NAME_VERSION (var);
990       if (expr[version])
991         {
992           tree new_expr = TREE_OPERAND (expr[version], 1);
993           SET_DEF (def_p, new_expr);
994           /* Clear the stmt's RHS, or GC might bite us.  */
995           TREE_OPERAND (expr[version], 1) = NULL_TREE;
996           return true;
997         }
998     }
999
1000   new_var = var_to_partition_to_var (map, var);
1001   if (new_var)
1002     {
1003       SET_DEF (def_p, new_var);
1004       set_is_used (new_var);
1005       return true;
1006     }
1007   return false;
1008 }
1009
1010
1011 /* Remove any PHI node which is a virtual PHI.  */
1012
1013 static void
1014 eliminate_virtual_phis (void)
1015 {
1016   basic_block bb;
1017   tree phi, next;
1018
1019   FOR_EACH_BB (bb)
1020     {
1021       for (phi = phi_nodes (bb); phi; phi = next)
1022         {
1023           next = PHI_CHAIN (phi);
1024           if (!is_gimple_reg (SSA_NAME_VAR (PHI_RESULT (phi))))
1025             {
1026 #ifdef ENABLE_CHECKING
1027               int i;
1028               /* There should be no arguments of this PHI which are in
1029                  the partition list, or we get incorrect results.  */
1030               for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1031                 {
1032                   tree arg = PHI_ARG_DEF (phi, i);
1033                   if (TREE_CODE (arg) == SSA_NAME 
1034                       && is_gimple_reg (SSA_NAME_VAR (arg)))
1035                     {
1036                       fprintf (stderr, "Argument of PHI is not virtual (");
1037                       print_generic_expr (stderr, arg, TDF_SLIM);
1038                       fprintf (stderr, "), but the result is :");
1039                       print_generic_stmt (stderr, phi, TDF_SLIM);
1040                       internal_error ("SSA corruption");
1041                     }
1042                 }
1043 #endif
1044               remove_phi_node (phi, NULL_TREE, bb);
1045             }
1046         }
1047     }
1048 }
1049
1050
1051 /* This routine will coalesce variables in MAP of the same type which do not 
1052    interfere with each other. LIVEINFO is the live range info for variables
1053    of interest.  This will both reduce the memory footprint of the stack, and 
1054    allow us to coalesce together local copies of globals and scalarized 
1055    component refs.  */
1056
1057 static void
1058 coalesce_vars (var_map map, tree_live_info_p liveinfo)
1059 {
1060   basic_block bb;
1061   type_var_p tv;
1062   tree var;
1063   unsigned x, p, p2;
1064   coalesce_list_p cl;
1065   conflict_graph graph;
1066
1067   cl = create_coalesce_list (map);
1068
1069   /* Merge all the live on entry vectors for coalesced partitions.  */
1070   for (x = 0; x < num_var_partitions (map); x++)
1071     {
1072       var = partition_to_var (map, x);
1073       p = var_to_partition (map, var);
1074       if (p != x)
1075         live_merge_and_clear (liveinfo, p, x);
1076     }
1077
1078   /* When PHI nodes are turned into copies, the result of each PHI node
1079      becomes live on entry to the block. Mark these now.  */
1080   FOR_EACH_BB (bb)
1081     {
1082       tree phi, arg;
1083       unsigned p;
1084       
1085       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1086         {
1087           p = var_to_partition (map, PHI_RESULT (phi));
1088
1089           /* Skip virtual PHI nodes.  */
1090           if (p == (unsigned)NO_PARTITION)
1091             continue;
1092
1093           make_live_on_entry (liveinfo, bb, p);
1094
1095           /* Each argument is a potential copy operation. Add any arguments 
1096              which are not coalesced to the result to the coalesce list.  */
1097           for (x = 0; x < (unsigned)PHI_NUM_ARGS (phi); x++)
1098             {
1099               arg = PHI_ARG_DEF (phi, x);
1100               if (!phi_ssa_name_p (arg))
1101                 continue;
1102               p2 = var_to_partition (map, arg);
1103               if (p2 == (unsigned)NO_PARTITION)
1104                 continue;
1105               if (p != p2)
1106                 add_coalesce (cl, p, p2, 1);
1107             }
1108         }
1109    }
1110
1111   
1112   /* Re-calculate live on exit info.  */
1113   calculate_live_on_exit (liveinfo);
1114
1115   if (dump_file && (dump_flags & TDF_DETAILS))
1116     {
1117       fprintf (dump_file, "Live range info for variable memory coalescing.\n");
1118       dump_live_info (dump_file, liveinfo, LIVEDUMP_ALL);
1119
1120       fprintf (dump_file, "Coalesce list from phi nodes:\n");
1121       dump_coalesce_list (dump_file, cl);
1122     }
1123
1124
1125   tv = type_var_init (map);
1126   if (dump_file)
1127     type_var_dump (dump_file, tv);
1128   type_var_compact (tv);
1129   if (dump_file)
1130     type_var_dump (dump_file, tv);
1131
1132   graph = build_tree_conflict_graph (liveinfo, tv, cl);
1133
1134   type_var_decompact (tv);
1135   if (dump_file && (dump_flags & TDF_DETAILS))
1136     {
1137       fprintf (dump_file, "type var list now looks like:n");
1138       type_var_dump (dump_file, tv);
1139
1140       fprintf (dump_file, "Coalesce list after conflict graph build:\n");
1141       dump_coalesce_list (dump_file, cl);
1142     }
1143
1144   sort_coalesce_list (cl);
1145   if (dump_file && (dump_flags & TDF_DETAILS))
1146     {
1147       fprintf (dump_file, "Coalesce list after sorting:\n");
1148       dump_coalesce_list (dump_file, cl);
1149     }
1150
1151   coalesce_tpa_members (tv, graph, map, cl, 
1152                         ((dump_flags & TDF_DETAILS) ? dump_file : NULL));
1153
1154   type_var_delete (tv);
1155   delete_coalesce_list (cl);
1156 }
1157
1158
1159 /* Temporary Expression Replacement (TER)
1160
1161    Replace SSA version variables during out-of-ssa with their defining
1162    expression if there is only one use of the variable.
1163
1164    A pass is made through the function, one block at a time.  No cross block
1165    information is tracked.
1166
1167    Variables which only have one use, and whose defining stmt is considered
1168    a replaceable expression (see check_replaceable) are entered into 
1169    consideration by adding a list of dependent partitions to the version_info
1170    vector for that ssa_name_version.  This information comes from the partition
1171    mapping for each USE.  At the same time, the partition_dep_list vector for 
1172    these partitions have this version number entered into their lists.
1173
1174    When the use of a replaceable ssa_variable is encountered, the dependence
1175    list in version_info[] is moved to the "pending_dependence" list in case
1176    the current expression is also replaceable. (To be determined later in 
1177    processing this stmt.) version_info[] for the version is then updated to 
1178    point to the defining stmt and the 'replaceable' bit is set.
1179
1180    Any partition which is defined by a statement 'kills' any expression which
1181    is dependent on this partition.  Every ssa version in the partitions' 
1182    dependence list is removed from future consideration.
1183
1184    All virtual references are lumped together.  Any expression which is
1185    dependent on any virtual variable (via a VUSE) has a dependence added
1186    to the special partition defined by VIRTUAL_PARTITION.
1187
1188    Whenever a V_MAY_DEF is seen, all expressions dependent this 
1189    VIRTUAL_PARTITION are removed from consideration.
1190
1191    At the end of a basic block, all expression are removed from consideration
1192    in preparation for the next block.  
1193    
1194    The end result is a vector over SSA_NAME_VERSION which is passed back to
1195    rewrite_out_of_ssa.  As the SSA variables are being rewritten, instead of
1196    replacing the SSA_NAME tree element with the partition it was assigned, 
1197    it is replaced with the RHS of the defining expression.  */
1198
1199
1200 /* Dependency list element.  This can contain either a partition index or a
1201    version number, depending on which list it is in.  */
1202
1203 typedef struct value_expr_d 
1204 {
1205   int value;
1206   struct value_expr_d *next;
1207 } *value_expr_p;
1208
1209
1210 /* Temporary Expression Replacement (TER) table information.  */
1211
1212 typedef struct temp_expr_table_d 
1213 {
1214   var_map map;
1215   void **version_info;          
1216   value_expr_p *partition_dep_list;
1217   bitmap replaceable;
1218   bool saw_replaceable;
1219   int virtual_partition;
1220   bitmap partition_in_use;
1221   value_expr_p free_list;
1222   value_expr_p pending_dependence;
1223 } *temp_expr_table_p;
1224
1225 /* Used to indicate a dependency on V_MAY_DEFs.  */
1226 #define VIRTUAL_PARTITION(table)        (table->virtual_partition)
1227
1228 static temp_expr_table_p new_temp_expr_table (var_map);
1229 static tree *free_temp_expr_table (temp_expr_table_p);
1230 static inline value_expr_p new_value_expr (temp_expr_table_p);
1231 static inline void free_value_expr (temp_expr_table_p, value_expr_p);
1232 static inline value_expr_p find_value_in_list (value_expr_p, int, 
1233                                                value_expr_p *);
1234 static inline void add_value_to_list (temp_expr_table_p, value_expr_p *, int);
1235 static inline void add_info_to_list (temp_expr_table_p, value_expr_p *, 
1236                                      value_expr_p);
1237 static value_expr_p remove_value_from_list (value_expr_p *, int);
1238 static void add_dependance (temp_expr_table_p, int, tree);
1239 static bool check_replaceable (temp_expr_table_p, tree);
1240 static void finish_expr (temp_expr_table_p, int, bool);
1241 static void mark_replaceable (temp_expr_table_p, tree);
1242 static inline void kill_expr (temp_expr_table_p, int, bool);
1243 static inline void kill_virtual_exprs (temp_expr_table_p, bool);
1244 static void find_replaceable_in_bb (temp_expr_table_p, basic_block);
1245 static tree *find_replaceable_exprs (var_map);
1246 static void dump_replaceable_exprs (FILE *, tree *);
1247
1248
1249 /* Create a new TER table for MAP.  */
1250
1251 static temp_expr_table_p
1252 new_temp_expr_table (var_map map)
1253 {
1254   temp_expr_table_p t;
1255
1256   t = (temp_expr_table_p) xmalloc (sizeof (struct temp_expr_table_d));
1257   t->map = map;
1258
1259   t->version_info = xcalloc (num_ssa_names + 1, sizeof (void *));
1260   t->partition_dep_list = xcalloc (num_var_partitions (map) + 1, 
1261                                    sizeof (value_expr_p));
1262
1263   t->replaceable = BITMAP_XMALLOC ();
1264   t->partition_in_use = BITMAP_XMALLOC ();
1265
1266   t->saw_replaceable = false;
1267   t->virtual_partition = num_var_partitions (map);
1268   t->free_list = NULL;
1269   t->pending_dependence = NULL;
1270
1271   return t;
1272 }
1273
1274
1275 /* Free TER table T.  If there are valid replacements, return the expression 
1276    vector.  */
1277
1278 static tree *
1279 free_temp_expr_table (temp_expr_table_p t)
1280 {
1281   value_expr_p p;
1282   tree *ret = NULL;
1283
1284 #ifdef ENABLE_CHECKING
1285   unsigned x;
1286   for (x = 0; x <= num_var_partitions (t->map); x++)
1287     gcc_assert (!t->partition_dep_list[x]);
1288 #endif
1289
1290   while ((p = t->free_list))
1291     {
1292       t->free_list = p->next;
1293       free (p);
1294     }
1295
1296   BITMAP_XFREE (t->partition_in_use);
1297   BITMAP_XFREE (t->replaceable);
1298
1299   free (t->partition_dep_list);
1300   if (t->saw_replaceable)
1301     ret = (tree *)t->version_info;
1302   else
1303     free (t->version_info);
1304   
1305   free (t);
1306   return ret;
1307 }
1308
1309
1310 /* Allocate a new value list node. Take it from the free list in TABLE if 
1311    possible.  */
1312
1313 static inline value_expr_p
1314 new_value_expr (temp_expr_table_p table)
1315 {
1316   value_expr_p p;
1317   if (table->free_list)
1318     {
1319       p = table->free_list;
1320       table->free_list = p->next;
1321     }
1322   else
1323     p = (value_expr_p) xmalloc (sizeof (struct value_expr_d));
1324
1325   return p;
1326 }
1327
1328
1329 /* Add value list node P to the free list in TABLE.  */
1330
1331 static inline void
1332 free_value_expr (temp_expr_table_p table, value_expr_p p)
1333 {
1334   p->next = table->free_list;
1335   table->free_list = p;
1336 }
1337
1338
1339 /* Find VALUE if it's in LIST.  Return a pointer to the list object if found,  
1340    else return NULL.  If LAST_PTR is provided, it will point to the previous 
1341    item upon return, or NULL if this is the first item in the list.  */
1342
1343 static inline value_expr_p
1344 find_value_in_list (value_expr_p list, int value, value_expr_p *last_ptr)
1345 {
1346   value_expr_p curr;
1347   value_expr_p last = NULL;
1348
1349   for (curr = list; curr; last = curr, curr = curr->next)
1350     {
1351       if (curr->value == value)
1352         break;
1353     }
1354   if (last_ptr)
1355     *last_ptr = last;
1356   return curr;
1357 }
1358
1359
1360 /* Add VALUE to LIST, if it isn't already present.  TAB is the expression 
1361    table */
1362
1363 static inline void
1364 add_value_to_list (temp_expr_table_p tab, value_expr_p *list, int value)
1365 {
1366   value_expr_p info;
1367
1368   if (!find_value_in_list (*list, value, NULL))
1369     {
1370       info = new_value_expr (tab);
1371       info->value = value;
1372       info->next = *list;
1373       *list = info;
1374     }
1375 }
1376
1377
1378 /* Add value node INFO if it's value isn't already in LIST.  Free INFO if
1379    it is already in the list. TAB is the expression table.  */
1380
1381 static inline void
1382 add_info_to_list (temp_expr_table_p tab, value_expr_p *list, value_expr_p info)
1383 {
1384   if (find_value_in_list (*list, info->value, NULL))
1385     free_value_expr (tab, info);
1386   else
1387     {
1388       info->next = *list;
1389       *list = info;
1390     }
1391 }
1392
1393
1394 /* Look for VALUE in LIST.  If found, remove it from the list and return it's 
1395    pointer.  */
1396
1397 static value_expr_p
1398 remove_value_from_list (value_expr_p *list, int value)
1399 {
1400   value_expr_p info, last;
1401
1402   info = find_value_in_list (*list, value, &last);
1403   if (!info)
1404     return NULL;
1405   if (!last)
1406     *list = info->next;
1407   else
1408     last->next = info->next;
1409  
1410   return info;
1411 }
1412
1413
1414 /* Add a dependency between the def of ssa VERSION and VAR.  If VAR is 
1415    replaceable by an expression, add a dependence each of the elements of the 
1416    expression.  These are contained in the pending list.  TAB is the
1417    expression table.  */
1418
1419 static void
1420 add_dependance (temp_expr_table_p tab, int version, tree var)
1421 {
1422   int i, x;
1423   value_expr_p info;
1424
1425   i = SSA_NAME_VERSION (var);
1426   if (bitmap_bit_p (tab->replaceable, i))
1427     {
1428       /* This variable is being substituted, so use whatever dependences
1429          were queued up when we marked this as replaceable earlier.  */
1430       while ((info = tab->pending_dependence))
1431         {
1432           tab->pending_dependence = info->next;
1433           /* Get the partition this variable was dependent on. Reuse this
1434              object to represent the current  expression instead.  */
1435           x = info->value;
1436           info->value = version;
1437           add_info_to_list (tab, &(tab->partition_dep_list[x]), info);
1438           add_value_to_list (tab, 
1439                              (value_expr_p *)&(tab->version_info[version]), x);
1440           bitmap_set_bit (tab->partition_in_use, x);
1441         }
1442     }
1443   else
1444     {
1445       i = var_to_partition (tab->map, var);
1446       gcc_assert (i != NO_PARTITION);
1447       add_value_to_list (tab, &(tab->partition_dep_list[i]), version);
1448       add_value_to_list (tab, 
1449                          (value_expr_p *)&(tab->version_info[version]), i);
1450       bitmap_set_bit (tab->partition_in_use, i);
1451     }
1452 }
1453
1454
1455 /* Check if expression STMT is suitable for replacement in table TAB.  If so, 
1456    create an expression entry.  Return true if this stmt is replaceable.  */
1457
1458 static bool
1459 check_replaceable (temp_expr_table_p tab, tree stmt)
1460 {
1461   stmt_ann_t ann;
1462   vuse_optype vuseops;
1463   def_optype defs;
1464   use_optype uses;
1465   tree var, def;
1466   int num_use_ops, version;
1467   var_map map = tab->map;
1468   ssa_op_iter iter;
1469   tree call_expr;
1470
1471   if (TREE_CODE (stmt) != MODIFY_EXPR)
1472     return false;
1473   
1474   ann = stmt_ann (stmt);
1475   defs = DEF_OPS (ann);
1476
1477   /* Punt if there is more than 1 def, or more than 1 use.  */
1478   if (NUM_DEFS (defs) != 1)
1479     return false;
1480   def = DEF_OP (defs, 0);
1481   if (version_ref_count (map, def) != 1)
1482     return false;
1483
1484   /* There must be no V_MAY_DEFS.  */
1485   if (NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) != 0)
1486     return false;
1487
1488   /* There must be no V_MUST_DEFS.  */
1489   if (NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) != 0)
1490     return false;
1491
1492   /* Float expressions must go through memory if float-store is on.  */
1493   if (flag_float_store && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 1))))
1494     return false;
1495
1496   /* Calls to functions with side-effects cannot be replaced.  */
1497   if ((call_expr = get_call_expr_in (stmt)) != NULL_TREE)
1498     {
1499       int call_flags = call_expr_flags (call_expr);
1500       if (TREE_SIDE_EFFECTS (call_expr)
1501           && !(call_flags & (ECF_PURE | ECF_CONST | ECF_NORETURN)))
1502         return false;
1503     }
1504
1505   uses = USE_OPS (ann);
1506   num_use_ops = NUM_USES (uses);
1507   vuseops = VUSE_OPS (ann);
1508
1509   /* Any expression which has no virtual operands and no real operands
1510      should have been propagated if it's possible to do anything with them. 
1511      If this happens here, it probably exists that way for a reason, so we 
1512      won't touch it.   An example is:
1513          b_4 = &tab
1514      There are no virtual uses nor any real uses, so we just leave this 
1515      alone to be safe.  */
1516
1517   if (num_use_ops == 0 && NUM_VUSES (vuseops) == 0)
1518     return false;
1519
1520   version = SSA_NAME_VERSION (def);
1521
1522   /* Add this expression to the dependency list for each use partition.  */
1523   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
1524     {
1525       add_dependance (tab, version, var);
1526     }
1527
1528   /* If there are VUSES, add a dependence on virtual defs.  */
1529   if (NUM_VUSES (vuseops) != 0)
1530     {
1531       add_value_to_list (tab, (value_expr_p *)&(tab->version_info[version]), 
1532                          VIRTUAL_PARTITION (tab));
1533       add_value_to_list (tab, 
1534                          &(tab->partition_dep_list[VIRTUAL_PARTITION (tab)]), 
1535                          version);
1536       bitmap_set_bit (tab->partition_in_use, VIRTUAL_PARTITION (tab));
1537     }
1538
1539   return true;
1540 }
1541
1542
1543 /* This function will remove the expression for VERSION from replacement 
1544    consideration.n table TAB  If 'replace' is true, it is marked as 
1545    replaceable, otherwise not.  */
1546
1547 static void
1548 finish_expr (temp_expr_table_p tab, int version, bool replace)
1549 {
1550   value_expr_p info, tmp;
1551   int partition;
1552
1553   /* Remove this expression from its dependent lists.  The partition dependence
1554      list is retained and transfered later to whomever uses this version.  */
1555   for (info = (value_expr_p) tab->version_info[version]; info; info = tmp)
1556     {
1557       partition = info->value;
1558       gcc_assert (tab->partition_dep_list[partition]);
1559       tmp = remove_value_from_list (&(tab->partition_dep_list[partition]), 
1560                                     version);
1561       gcc_assert (tmp);
1562       free_value_expr (tab, tmp);
1563       /* Only clear the bit when the dependency list is emptied via 
1564          a replacement. Otherwise kill_expr will take care of it.  */
1565       if (!(tab->partition_dep_list[partition]) && replace)
1566         bitmap_clear_bit (tab->partition_in_use, partition);
1567       tmp = info->next;
1568       if (!replace)
1569         free_value_expr (tab, info);
1570     }
1571
1572   if (replace)
1573     {
1574       tab->saw_replaceable = true;
1575       bitmap_set_bit (tab->replaceable, version);
1576     }
1577   else
1578     {
1579       gcc_assert (!bitmap_bit_p (tab->replaceable, version));
1580       tab->version_info[version] = NULL;
1581     }
1582 }
1583
1584
1585 /* Mark the expression associated with VAR as replaceable, and enter
1586    the defining stmt into the version_info table TAB.  */
1587
1588 static void
1589 mark_replaceable (temp_expr_table_p tab, tree var)
1590 {
1591   value_expr_p info;
1592   int version = SSA_NAME_VERSION (var);
1593   finish_expr (tab, version, true);
1594
1595   /* Move the dependence list to the pending list.  */
1596   if (tab->version_info[version])
1597     {
1598       info = (value_expr_p) tab->version_info[version]; 
1599       for ( ; info->next; info = info->next)
1600         continue;
1601       info->next = tab->pending_dependence;
1602       tab->pending_dependence = (value_expr_p)tab->version_info[version];
1603     }
1604
1605   tab->version_info[version] = SSA_NAME_DEF_STMT (var);
1606 }
1607
1608
1609 /* This function marks any expression in TAB which is dependent on PARTITION
1610    as NOT replaceable.  CLEAR_BIT is used to determine whether partition_in_use
1611    should have its bit cleared.  Since this routine can be called within an
1612    EXECUTE_IF_SET_IN_BITMAP, the bit can't always be cleared.  */
1613
1614 static inline void
1615 kill_expr (temp_expr_table_p tab, int partition, bool clear_bit)
1616 {
1617   value_expr_p ptr;
1618
1619   /* Mark every active expr dependent on this var as not replaceable.  */
1620   while ((ptr = tab->partition_dep_list[partition]) != NULL)
1621     finish_expr (tab, ptr->value, false);
1622
1623   if (clear_bit)
1624     bitmap_clear_bit (tab->partition_in_use, partition);
1625 }
1626
1627
1628 /* This function kills all expressions in TAB which are dependent on virtual 
1629    DEFs.  CLEAR_BIT determines whether partition_in_use gets cleared.  */
1630
1631 static inline void
1632 kill_virtual_exprs (temp_expr_table_p tab, bool clear_bit)
1633 {
1634   kill_expr (tab, VIRTUAL_PARTITION (tab), clear_bit);
1635 }
1636
1637
1638 /* This function processes basic block BB, and looks for variables which can
1639    be replaced by their expressions.  Results are stored in TAB.  */
1640
1641 static void
1642 find_replaceable_in_bb (temp_expr_table_p tab, basic_block bb)
1643 {
1644   block_stmt_iterator bsi;
1645   tree stmt, def;
1646   stmt_ann_t ann;
1647   int partition;
1648   var_map map = tab->map;
1649   value_expr_p p;
1650   ssa_op_iter iter;
1651
1652   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1653     {
1654       stmt = bsi_stmt (bsi);
1655       ann = stmt_ann (stmt);
1656
1657       /* Determine if this stmt finishes an existing expression.  */
1658       FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_USE)
1659         {
1660           if (tab->version_info[SSA_NAME_VERSION (def)])
1661             {
1662               /* Mark expression as replaceable unless stmt is volatile.  */
1663               if (!ann->has_volatile_ops)
1664                 mark_replaceable (tab, def);
1665               else
1666                 finish_expr (tab, SSA_NAME_VERSION (def), false);
1667             }
1668         }
1669       
1670       /* Next, see if this stmt kills off an active expression.  */
1671       FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1672         {
1673           partition = var_to_partition (map, def);
1674           if (partition != NO_PARTITION && tab->partition_dep_list[partition])
1675             kill_expr (tab, partition, true);
1676         }
1677
1678       /* Now see if we are creating a new expression or not.  */
1679       if (!ann->has_volatile_ops)
1680         check_replaceable (tab, stmt);
1681
1682       /* Free any unused dependency lists.  */
1683       while ((p = tab->pending_dependence))
1684         {
1685           tab->pending_dependence = p->next;
1686           free_value_expr (tab, p);
1687         }
1688
1689       /* A V_MAY_DEF kills any expression using a virtual operand.  */
1690       if (NUM_V_MAY_DEFS (V_MAY_DEF_OPS (ann)) > 0)
1691         kill_virtual_exprs (tab, true);
1692         
1693       /* A V_MUST_DEF kills any expression using a virtual operand.  */
1694       if (NUM_V_MUST_DEFS (V_MUST_DEF_OPS (ann)) > 0)
1695         kill_virtual_exprs (tab, true);
1696     }
1697 }
1698
1699
1700 /* This function is the driver routine for replacement of temporary expressions
1701    in the SSA->normal phase, operating on MAP.  If there are replaceable 
1702    expressions, a table is returned which maps SSA versions to the 
1703    expressions they should be replaced with.  A NULL_TREE indicates no 
1704    replacement should take place.  If there are no replacements at all, 
1705    NULL is returned by the function, otherwise an expression vector indexed
1706    by SSA_NAME version numbers.  */
1707
1708 static tree *
1709 find_replaceable_exprs (var_map map)
1710 {
1711   basic_block bb;
1712   unsigned i;
1713   temp_expr_table_p table;
1714   tree *ret;
1715
1716   table = new_temp_expr_table (map);
1717   FOR_EACH_BB (bb)
1718     {
1719       bitmap_iterator bi;
1720
1721       find_replaceable_in_bb (table, bb);
1722       EXECUTE_IF_SET_IN_BITMAP ((table->partition_in_use), 0, i, bi)
1723         {
1724           kill_expr (table, i, false);
1725         }
1726     }
1727
1728   ret = free_temp_expr_table (table);
1729   return ret;
1730 }
1731
1732
1733 /* Dump TER expression table EXPR to file F.  */
1734
1735 static void
1736 dump_replaceable_exprs (FILE *f, tree *expr)
1737 {
1738   tree stmt, var;
1739   int x;
1740   fprintf (f, "\nReplacing Expressions\n");
1741   for (x = 0; x < (int)num_ssa_names + 1; x++)
1742     if (expr[x])
1743       {
1744         stmt = expr[x];
1745         var = DEF_OP (STMT_DEF_OPS (stmt), 0);
1746         print_generic_expr (f, var, TDF_SLIM);
1747         fprintf (f, " replace with --> ");
1748         print_generic_expr (f, TREE_OPERAND (stmt, 1), TDF_SLIM);
1749         fprintf (f, "\n");
1750       }
1751   fprintf (f, "\n");
1752 }
1753
1754
1755 /* Helper function for discover_nonconstant_array_refs. 
1756    Look for ARRAY_REF nodes with non-constant indexes and mark them
1757    addressable.  */
1758
1759 static tree
1760 discover_nonconstant_array_refs_r (tree * tp, int *walk_subtrees,
1761                                    void *data ATTRIBUTE_UNUSED)
1762 {
1763   tree t = *tp;
1764
1765   if (IS_TYPE_OR_DECL_P (t))
1766     *walk_subtrees = 0;
1767   else if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1768     {
1769       while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1770               && is_gimple_min_invariant (TREE_OPERAND (t, 1))
1771               && (!TREE_OPERAND (t, 2)
1772                   || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1773              || (TREE_CODE (t) == COMPONENT_REF
1774                  && (!TREE_OPERAND (t,2)
1775                      || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1776              || TREE_CODE (t) == BIT_FIELD_REF
1777              || TREE_CODE (t) == REALPART_EXPR
1778              || TREE_CODE (t) == IMAGPART_EXPR
1779              || TREE_CODE (t) == VIEW_CONVERT_EXPR
1780              || TREE_CODE (t) == NOP_EXPR
1781              || TREE_CODE (t) == CONVERT_EXPR)
1782         t = TREE_OPERAND (t, 0);
1783
1784       if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1785         {
1786           t = get_base_address (t);
1787           if (t && DECL_P (t))
1788             TREE_ADDRESSABLE (t) = 1;
1789         }
1790
1791       *walk_subtrees = 0;
1792     }
1793
1794   return NULL_TREE;
1795 }
1796
1797
1798 /* RTL expansion is not able to compile array references with variable
1799    offsets for arrays stored in single register.  Discover such
1800    expressions and mark variables as addressable to avoid this
1801    scenario.  */
1802
1803 static void
1804 discover_nonconstant_array_refs (void)
1805 {
1806   basic_block bb;
1807   block_stmt_iterator bsi;
1808
1809   FOR_EACH_BB (bb)
1810     {
1811       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1812         walk_tree (bsi_stmt_ptr (bsi), discover_nonconstant_array_refs_r,
1813                    NULL , NULL);
1814     }
1815 }
1816
1817
1818 /* This function will rewrite the current program using the variable mapping
1819    found in MAP.  If the replacement vector VALUES is provided, any 
1820    occurrences of partitions with non-null entries in the vector will be 
1821    replaced with the expression in the vector instead of its mapped 
1822    variable.  */
1823
1824 static void
1825 rewrite_trees (var_map map, tree *values)
1826 {
1827   elim_graph g;
1828   basic_block bb;
1829   block_stmt_iterator si;
1830   edge e;
1831   tree phi;
1832   bool changed;
1833  
1834 #ifdef ENABLE_CHECKING
1835   /* Search for PHIs where the destination has no partition, but one
1836      or more arguments has a partition.  This should not happen and can
1837      create incorrect code.  */
1838   FOR_EACH_BB (bb)
1839     {
1840       tree phi;
1841
1842       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1843         {
1844           tree T0 = var_to_partition_to_var (map, PHI_RESULT (phi));
1845       
1846           if (T0 == NULL_TREE)
1847             {
1848               int i;
1849
1850               for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1851                 {
1852                   tree arg = PHI_ARG_DEF (phi, i);
1853
1854                   if (TREE_CODE (arg) == SSA_NAME
1855                       && var_to_partition (map, arg) != NO_PARTITION)
1856                     {
1857                       fprintf (stderr, "Argument of PHI is in a partition :(");
1858                       print_generic_expr (stderr, arg, TDF_SLIM);
1859                       fprintf (stderr, "), but the result is not :");
1860                       print_generic_stmt (stderr, phi, TDF_SLIM);
1861                       internal_error ("SSA corruption");
1862                     }
1863                 }
1864             }
1865         }
1866     }
1867 #endif
1868
1869   /* Replace PHI nodes with any required copies.  */
1870   g = new_elim_graph (map->num_partitions);
1871   g->map = map;
1872   FOR_EACH_BB (bb)
1873     {
1874       for (si = bsi_start (bb); !bsi_end_p (si); )
1875         {
1876           size_t num_uses, num_defs;
1877           use_optype uses;
1878           def_optype defs;
1879           tree stmt = bsi_stmt (si);
1880           use_operand_p use_p;
1881           def_operand_p def_p;
1882           int remove = 0, is_copy = 0;
1883           stmt_ann_t ann;
1884           ssa_op_iter iter;
1885
1886           get_stmt_operands (stmt);
1887           ann = stmt_ann (stmt);
1888           changed = false;
1889
1890           if (TREE_CODE (stmt) == MODIFY_EXPR 
1891               && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME))
1892             is_copy = 1;
1893
1894           uses = USE_OPS (ann);
1895           num_uses = NUM_USES (uses);
1896           FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1897             {
1898               if (replace_use_variable (map, use_p, values))
1899                 changed = true;
1900             }
1901
1902           defs = DEF_OPS (ann);
1903           num_defs = NUM_DEFS (defs);
1904
1905           /* Mark this stmt for removal if it is the list of replaceable 
1906              expressions.  */
1907           if (values && num_defs == 1)
1908             {
1909               tree def = DEF_OP (defs, 0);
1910               tree val;
1911               val = values[SSA_NAME_VERSION (def)];
1912               if (val)
1913                 remove = 1;
1914             }
1915           if (!remove)
1916             {
1917               FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_DEF)
1918                 {
1919                   if (replace_def_variable (map, def_p, NULL))
1920                     changed = true;
1921
1922                   /* If both SSA_NAMEs coalesce to the same variable,
1923                      mark the now redundant copy for removal.  */
1924                   if (is_copy
1925                       && num_uses == 1
1926                       && (DEF_FROM_PTR (def_p) == USE_OP (uses, 0)))
1927                     remove = 1;
1928                 }
1929               if (changed & !remove)
1930                 modify_stmt (stmt);
1931             }
1932
1933           /* Remove any stmts marked for removal.  */
1934           if (remove)
1935             bsi_remove (&si);
1936           else
1937             bsi_next (&si);
1938         }
1939
1940       phi = phi_nodes (bb);
1941       if (phi)
1942         {
1943           edge_iterator ei;
1944           FOR_EACH_EDGE (e, ei, bb->preds)
1945             eliminate_phi (e, g);
1946         }
1947     }
1948
1949   delete_elim_graph (g);
1950 }
1951
1952
1953 /* These are the local work structures used to determine the best place to 
1954    insert the copies that were placed on edges by the SSA->normal pass..  */
1955 static varray_type edge_leader = NULL;
1956 static varray_type GTY(()) stmt_list = NULL;
1957 static bitmap leader_has_match = NULL;
1958 static edge leader_match = NULL;
1959
1960
1961 /* Pass this function to make_forwarder_block so that all the edges with
1962    matching PENDING_STMT lists to 'curr_stmt_list' get redirected.  */
1963 static bool 
1964 same_stmt_list_p (edge e)
1965 {
1966   return (e->aux == (PTR) leader_match) ? true : false;
1967 }
1968
1969
1970 /* Return TRUE if S1 and S2 are equivalent copies.  */
1971 static inline bool
1972 identical_copies_p (tree s1, tree s2)
1973 {
1974 #ifdef ENABLE_CHECKING
1975   gcc_assert (TREE_CODE (s1) == MODIFY_EXPR);
1976   gcc_assert (TREE_CODE (s2) == MODIFY_EXPR);
1977   gcc_assert (DECL_P (TREE_OPERAND (s1, 0)));
1978   gcc_assert (DECL_P (TREE_OPERAND (s2, 0)));
1979 #endif
1980
1981   if (TREE_OPERAND (s1, 0) != TREE_OPERAND (s2, 0))
1982     return false;
1983
1984   s1 = TREE_OPERAND (s1, 1);
1985   s2 = TREE_OPERAND (s2, 1);
1986
1987   if (s1 != s2)
1988     return false;
1989
1990   return true;
1991 }
1992
1993
1994 /* Compare the PENDING_STMT list for two edges, and return true if the lists
1995    contain the same sequence of copies.  */
1996
1997 static inline bool 
1998 identical_stmt_lists_p (edge e1, edge e2)
1999 {
2000   tree t1 = PENDING_STMT (e1);
2001   tree t2 = PENDING_STMT (e2);
2002   tree_stmt_iterator tsi1, tsi2;
2003
2004   gcc_assert (TREE_CODE (t1) == STATEMENT_LIST);
2005   gcc_assert (TREE_CODE (t2) == STATEMENT_LIST);
2006
2007   for (tsi1 = tsi_start (t1), tsi2 = tsi_start (t2);
2008        !tsi_end_p (tsi1) && !tsi_end_p (tsi2); 
2009        tsi_next (&tsi1), tsi_next (&tsi2))
2010     {
2011       if (!identical_copies_p (tsi_stmt (tsi1), tsi_stmt (tsi2)))
2012         break;
2013     }
2014
2015   if (!tsi_end_p (tsi1) || ! tsi_end_p (tsi2))
2016     return false;
2017
2018   return true;
2019 }
2020
2021
2022 /* Look at all the incoming edges to block BB, and decide where the best place
2023    to insert the stmts on each edge are, and perform those insertions.   Output
2024    any debug information to DEBUG_FILE.  Return true if anything other than a 
2025    standard edge insertion is done.  */
2026
2027 static bool 
2028 analyze_edges_for_bb (basic_block bb, FILE *debug_file)
2029 {
2030   edge e;
2031   edge_iterator ei;
2032   int count;
2033   unsigned int x;
2034   bool have_opportunity;
2035   block_stmt_iterator bsi;
2036   tree stmt;
2037   edge single_edge = NULL;
2038   bool is_label;
2039
2040   count = 0;
2041
2042   /* Blocks which contain at least one abnormal edge cannot use 
2043      make_forwarder_block.  Look for these blocks, and commit any PENDING_STMTs
2044      found on edges in these block.  */
2045   have_opportunity = true;
2046   FOR_EACH_EDGE (e, ei, bb->preds)
2047     if (e->flags & EDGE_ABNORMAL)
2048       {
2049         have_opportunity = false;
2050         break;
2051       }
2052
2053   if (!have_opportunity)
2054     {
2055       FOR_EACH_EDGE (e, ei, bb->preds)
2056         if (PENDING_STMT (e))
2057           bsi_commit_one_edge_insert (e, NULL);
2058       return false;
2059     }
2060   /* Find out how many edges there are with interesting pending stmts on them.  
2061      Commit the stmts on edges we are not interested in.  */
2062   FOR_EACH_EDGE (e, ei, bb->preds)
2063     {
2064       if (PENDING_STMT (e))
2065         {
2066           gcc_assert (!(e->flags & EDGE_ABNORMAL));
2067           if (e->flags & EDGE_FALLTHRU)
2068             {
2069               bsi = bsi_start (e->src);
2070               if (!bsi_end_p (bsi))
2071                 {
2072                   stmt = bsi_stmt (bsi);
2073                   bsi_next (&bsi);
2074                   gcc_assert (stmt != NULL_TREE);
2075                   is_label = (TREE_CODE (stmt) == LABEL_EXPR);
2076                   /* Punt if it has non-label stmts, or isn't local.  */
2077                   if (!is_label || DECL_NONLOCAL (TREE_OPERAND (stmt, 0)) 
2078                       || !bsi_end_p (bsi))
2079                     {
2080                       bsi_commit_one_edge_insert (e, NULL);
2081                       continue;
2082                     }
2083                 }
2084             }
2085           single_edge = e;
2086           count++;
2087         }
2088     }
2089
2090   /* If there aren't at least 2 edges, no sharing will happen.  */
2091   if (count < 2)
2092     {
2093       if (single_edge)
2094         bsi_commit_one_edge_insert (single_edge, NULL);
2095       return false;
2096     }
2097
2098   /* Ensure that we have empty worklists.  */
2099   if (edge_leader == NULL)
2100     {
2101       VARRAY_EDGE_INIT (edge_leader, 25, "edge_leader");
2102       VARRAY_TREE_INIT (stmt_list, 25, "stmt_list");
2103       leader_has_match = BITMAP_XMALLOC ();
2104     }
2105   else
2106     {
2107 #ifdef ENABLE_CHECKING
2108       gcc_assert (VARRAY_ACTIVE_SIZE (edge_leader) == 0);
2109       gcc_assert (VARRAY_ACTIVE_SIZE (stmt_list) == 0);
2110       gcc_assert (bitmap_empty_p (leader_has_match));
2111 #endif
2112     }
2113
2114   /* Find the "leader" block for each set of unique stmt lists.  Preference is
2115      given to FALLTHRU blocks since they would need a GOTO to arrive at another
2116      block.  The leader edge destination is the block which all the other edges
2117      with the same stmt list will be redirected to.  */
2118   have_opportunity = false;
2119   FOR_EACH_EDGE (e, ei, bb->preds)
2120     {
2121       if (PENDING_STMT (e))
2122         {
2123           bool found = false;
2124
2125           /* Look for the same stmt list in edge leaders list.  */
2126           for (x = 0; x < VARRAY_ACTIVE_SIZE (edge_leader); x++)
2127             {
2128               edge leader = VARRAY_EDGE (edge_leader, x);
2129               if (identical_stmt_lists_p (leader, e))
2130                 {
2131                   /* Give this edge the same stmt list pointer.  */
2132                   PENDING_STMT (e) = NULL;
2133                   e->aux = leader;
2134                   bitmap_set_bit (leader_has_match, x);
2135                   have_opportunity = found = true;
2136                   break;
2137                 }
2138             }
2139
2140           /* If no similar stmt list, add this edge to the leader list.  */
2141           if (!found)
2142             {
2143               VARRAY_PUSH_EDGE (edge_leader, e);
2144               VARRAY_PUSH_TREE (stmt_list, PENDING_STMT (e));
2145             }
2146         }
2147      }
2148
2149   /* If there are no similar lists, just issue the stmts.  */
2150   if (!have_opportunity)
2151     {
2152       for (x = 0; x < VARRAY_ACTIVE_SIZE (edge_leader); x++)
2153         bsi_commit_one_edge_insert (VARRAY_EDGE (edge_leader, x), NULL);
2154       VARRAY_POP_ALL (edge_leader);
2155       VARRAY_POP_ALL (stmt_list);
2156       bitmap_clear (leader_has_match);
2157       return false;
2158     }
2159
2160
2161   if (debug_file)
2162     fprintf (debug_file, "\nOpportunities in BB %d for stmt/block reduction:\n",
2163              bb->index);
2164
2165   
2166   /* For each common list, create a forwarding block and issue the stmt's
2167      in that block.  */
2168   for (x = 0 ; x < VARRAY_ACTIVE_SIZE (edge_leader); x++)
2169     if (bitmap_bit_p (leader_has_match, x))
2170       {
2171         edge new_edge, leader_edge;
2172         block_stmt_iterator bsi;
2173         tree curr_stmt_list;
2174
2175         leader_match = leader_edge = VARRAY_EDGE (edge_leader, x);
2176
2177         /* The tree_* cfg manipulation routines use the PENDING_EDGE field
2178            for various PHI manipulations, so it gets cleared whhen calls are 
2179            made to make_forwarder_block(). So make sure the edge is clear, 
2180            and use the saved stmt list.  */
2181         PENDING_STMT (leader_edge) = NULL;
2182         leader_edge->aux = leader_edge;
2183         curr_stmt_list = VARRAY_TREE (stmt_list, x);
2184
2185         new_edge = make_forwarder_block (leader_edge->dest, same_stmt_list_p, 
2186                                          NULL);
2187         bb = new_edge->dest;
2188         if (debug_file)
2189           {
2190             fprintf (debug_file, "Splitting BB %d for Common stmt list.  ", 
2191                      leader_edge->dest->index);
2192             fprintf (debug_file, "Original block is now BB%d.\n", bb->index);
2193             print_generic_stmt (debug_file, curr_stmt_list, TDF_VOPS);
2194           }
2195
2196         FOR_EACH_EDGE (e, ei, new_edge->src->preds)
2197           {
2198             e->aux = NULL;
2199             if (debug_file)
2200               fprintf (debug_file, "  Edge (%d->%d) lands here.\n", 
2201                        e->src->index, e->dest->index);
2202           }
2203
2204         bsi = bsi_last (leader_edge->dest);
2205         bsi_insert_after (&bsi, curr_stmt_list, BSI_NEW_STMT);
2206
2207         leader_match = NULL;
2208         /* We should never get a new block now.  */
2209       }
2210     else
2211       {
2212         e = VARRAY_EDGE (edge_leader, x);
2213         PENDING_STMT (e) = VARRAY_TREE (stmt_list, x);
2214         bsi_commit_one_edge_insert (e, NULL);
2215       }
2216
2217    
2218   /* Clear the working data structures.  */
2219   VARRAY_POP_ALL (edge_leader);
2220   VARRAY_POP_ALL (stmt_list);
2221   bitmap_clear (leader_has_match);
2222
2223   return true;
2224 }
2225
2226
2227 /* This function will analyze the insertions which were performed on edges,
2228    and decide whether they should be left on that edge, or whether it is more
2229    efficient to emit some subset of them in a single block.  All stmts are
2230    inserted somewhere, and if non-NULL, debug information is printed via 
2231    DUMP_FILE.  */
2232
2233 static void
2234 perform_edge_inserts (FILE *dump_file)
2235 {
2236   basic_block bb;
2237   bool changed = false;
2238
2239   if (dump_file)
2240     fprintf(dump_file, "Analyzing Edge Insertions.\n");
2241
2242   FOR_EACH_BB (bb)
2243     changed |= analyze_edges_for_bb (bb, dump_file);
2244
2245   changed |= analyze_edges_for_bb (EXIT_BLOCK_PTR, dump_file);
2246
2247   /* Clear out any tables which were created.  */
2248   edge_leader = NULL;
2249   BITMAP_XFREE (leader_has_match);
2250
2251   if (changed)
2252     {
2253       free_dominance_info (CDI_DOMINATORS);
2254       free_dominance_info (CDI_POST_DOMINATORS);
2255     }
2256
2257 #ifdef ENABLE_CHECKING
2258   {
2259     edge_iterator ei;
2260     edge e;
2261     FOR_EACH_BB (bb)
2262       {
2263         FOR_EACH_EDGE (e, ei, bb->preds)
2264           {
2265             if (PENDING_STMT (e))
2266               error (" Pending stmts not issued on PRED edge (%d, %d)\n", 
2267                      e->src->index, e->dest->index);
2268           }
2269         FOR_EACH_EDGE (e, ei, bb->succs)
2270           {
2271             if (PENDING_STMT (e))
2272               error (" Pending stmts not issued on SUCC edge (%d, %d)\n", 
2273                      e->src->index, e->dest->index);
2274           }
2275       }
2276     FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2277       {
2278         if (PENDING_STMT (e))
2279           error (" Pending stmts not issued on ENTRY edge (%d, %d)\n", 
2280                  e->src->index, e->dest->index);
2281       }
2282     FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2283       {
2284         if (PENDING_STMT (e))
2285           error (" Pending stmts not issued on EXIT edge (%d, %d)\n", 
2286                  e->src->index, e->dest->index);
2287       }
2288   }
2289 #endif
2290 }
2291
2292
2293 /* Remove the variables specified in MAP from SSA form.  Any debug information
2294    is sent to DUMP.  FLAGS indicate what options should be used.  */
2295
2296 static void
2297 remove_ssa_form (FILE *dump, var_map map, int flags)
2298 {
2299   tree_live_info_p liveinfo;
2300   basic_block bb;
2301   tree phi, next;
2302   FILE *save;
2303   tree *values = NULL;
2304
2305   save = dump_file;
2306   dump_file = dump;
2307
2308   /* If we are not combining temps, don't calculate live ranges for variables
2309      with only one SSA version.  */
2310   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
2311     compact_var_map (map, VARMAP_NO_SINGLE_DEFS);
2312   else
2313     compact_var_map (map, VARMAP_NORMAL);
2314
2315   if (dump_file && (dump_flags & TDF_DETAILS))
2316     dump_var_map (dump_file, map);
2317
2318   liveinfo = coalesce_ssa_name (map, flags);
2319
2320   /* Make sure even single occurrence variables are in the list now.  */
2321   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
2322     compact_var_map (map, VARMAP_NORMAL);
2323
2324   if (dump_file && (dump_flags & TDF_DETAILS))
2325     {
2326       fprintf (dump_file, "After Coalescing:\n");
2327       dump_var_map (dump_file, map);
2328     }
2329
2330   if (flags & SSANORM_PERFORM_TER)
2331     {
2332       values = find_replaceable_exprs (map);
2333       if (values && dump_file && (dump_flags & TDF_DETAILS))
2334         dump_replaceable_exprs (dump_file, values);
2335     }
2336
2337   /* Assign real variables to the partitions now.  */
2338   assign_vars (map);
2339
2340   if (dump_file && (dump_flags & TDF_DETAILS))
2341     {
2342       fprintf (dump_file, "After Root variable replacement:\n");
2343       dump_var_map (dump_file, map);
2344     }
2345
2346   if ((flags & SSANORM_COMBINE_TEMPS) && liveinfo)
2347     {
2348       coalesce_vars (map, liveinfo);
2349       if (dump_file && (dump_flags & TDF_DETAILS))
2350         {
2351           fprintf (dump_file, "After variable memory coalescing:\n");
2352           dump_var_map (dump_file, map);
2353         }
2354     }
2355   
2356   if (liveinfo)
2357     delete_tree_live_info (liveinfo);
2358
2359   rewrite_trees (map, values);
2360
2361   if (values)
2362     free (values);
2363
2364   /* Remove phi nodes which have been translated back to real variables.  */
2365   FOR_EACH_BB (bb)
2366     {
2367       for (phi = phi_nodes (bb); phi; phi = next)
2368         {
2369           next = PHI_CHAIN (phi);
2370           if ((flags & SSANORM_REMOVE_ALL_PHIS) 
2371               || var_to_partition (map, PHI_RESULT (phi)) != NO_PARTITION)
2372             remove_phi_node (phi, NULL_TREE, bb);
2373         }
2374     }
2375
2376   /* If any copies were inserted on edges, analyze and insert them now.  */
2377   perform_edge_inserts (dump_file);
2378
2379   dump_file = save;
2380 }
2381
2382 /* Search every PHI node for arguments associated with backedges which
2383    we can trivially determine will need a copy (the argument is either
2384    not an SSA_NAME or the argument has a different underlying variable
2385    than the PHI result).
2386
2387    Insert a copy from the PHI argument to a new destination at the
2388    end of the block with the backedge to the top of the loop.  Update
2389    the PHI argument to reference this new destination.  */
2390
2391 static void
2392 insert_backedge_copies (void)
2393 {
2394   basic_block bb;
2395
2396   FOR_EACH_BB (bb)
2397     {
2398       tree phi;
2399
2400       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2401         {
2402           tree result = PHI_RESULT (phi);
2403           tree result_var;
2404           int i;
2405
2406           if (!is_gimple_reg (result))
2407             continue;
2408
2409           result_var = SSA_NAME_VAR (result);
2410           for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2411             {
2412               tree arg = PHI_ARG_DEF (phi, i);
2413               edge e = PHI_ARG_EDGE (phi, i);
2414
2415               /* If the argument is not an SSA_NAME, then we will
2416                  need a constant initialization.  If the argument is
2417                  an SSA_NAME with a different underlying variable and
2418                  we are not combining temporaries, then we will
2419                  need a copy statement.  */
2420               if ((e->flags & EDGE_DFS_BACK)
2421                   && (TREE_CODE (arg) != SSA_NAME
2422                       || (!flag_tree_combine_temps
2423                           && SSA_NAME_VAR (arg) != result_var)))
2424                 {
2425                   tree stmt, name, last = NULL;
2426                   block_stmt_iterator bsi;
2427
2428                   bsi = bsi_last (PHI_ARG_EDGE (phi, i)->src);
2429                   if (!bsi_end_p (bsi))
2430                     last = bsi_stmt (bsi);
2431
2432                   /* In theory the only way we ought to get back to the
2433                      start of a loop should be with a COND_EXPR or GOTO_EXPR.
2434                      However, better safe than sorry. 
2435
2436                      If the block ends with a control statement or
2437                      something that might throw, then we have to
2438                      insert this assignment before the last
2439                      statement.  Else insert it after the last statement.  */
2440                   if (last && stmt_ends_bb_p (last))
2441                     {
2442                       /* If the last statement in the block is the definition
2443                          site of the PHI argument, then we can't insert
2444                          anything after it.  */
2445                       if (TREE_CODE (arg) == SSA_NAME
2446                           && SSA_NAME_DEF_STMT (arg) == last)
2447                         continue;
2448                     }
2449
2450                   /* Create a new instance of the underlying
2451                      variable of the PHI result.  */
2452                   stmt = build (MODIFY_EXPR, TREE_TYPE (result_var),
2453                                 NULL, PHI_ARG_DEF (phi, i));
2454                   name = make_ssa_name (result_var, stmt);
2455                   TREE_OPERAND (stmt, 0) = name;
2456
2457                   /* Insert the new statement into the block and update
2458                      the PHI node.  */
2459                   if (last && stmt_ends_bb_p (last))
2460                     bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
2461                   else
2462                     bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2463                   modify_stmt (stmt);
2464                   SET_PHI_ARG_DEF (phi, i, name);
2465                 }
2466             }
2467         }
2468     }
2469 }
2470
2471 /* Take the current function out of SSA form, as described in
2472    R. Morgan, ``Building an Optimizing Compiler'',
2473    Butterworth-Heinemann, Boston, MA, 1998. pp 176-186.  */
2474
2475 static void
2476 rewrite_out_of_ssa (void)
2477 {
2478   var_map map;
2479   int var_flags = 0;
2480   int ssa_flags = (SSANORM_REMOVE_ALL_PHIS | SSANORM_USE_COALESCE_LIST);
2481
2482   /* If elimination of a PHI requires inserting a copy on a backedge,
2483      then we will have to split the backedge which has numerous
2484      undesirable performance effects.
2485
2486      A significant number of such cases can be handled here by inserting
2487      copies into the loop itself.  */
2488   insert_backedge_copies ();
2489
2490   if (!flag_tree_live_range_split)
2491     ssa_flags |= SSANORM_COALESCE_PARTITIONS;
2492     
2493   eliminate_virtual_phis ();
2494
2495   if (dump_file && (dump_flags & TDF_DETAILS))
2496     dump_tree_cfg (dump_file, dump_flags & ~TDF_DETAILS);
2497
2498   /* We cannot allow unssa to un-gimplify trees before we instrument them.  */
2499   if (flag_tree_ter && !flag_mudflap)
2500     var_flags = SSA_VAR_MAP_REF_COUNT;
2501
2502   map = create_ssa_var_map (var_flags);
2503
2504   if (flag_tree_combine_temps)
2505     ssa_flags |= SSANORM_COMBINE_TEMPS;
2506   if (flag_tree_ter && !flag_mudflap)
2507     ssa_flags |= SSANORM_PERFORM_TER;
2508
2509   remove_ssa_form (dump_file, map, ssa_flags);
2510
2511   if (dump_file && (dump_flags & TDF_DETAILS))
2512     dump_tree_cfg (dump_file, dump_flags & ~TDF_DETAILS);
2513
2514   /* Do some cleanups which reduce the amount of data the
2515      tree->rtl expanders deal with.  */
2516   cfg_remove_useless_stmts ();
2517
2518   /* Flush out flow graph and SSA data.  */
2519   delete_var_map (map);
2520
2521   /* Mark arrays indexed with non-constant indices with TREE_ADDRESSABLE.  */
2522   discover_nonconstant_array_refs ();
2523 }
2524
2525
2526 /* Define the parameters of the out of SSA pass.  */
2527
2528 struct tree_opt_pass pass_del_ssa = 
2529 {
2530   "optimized",                          /* name */
2531   NULL,                                 /* gate */
2532   rewrite_out_of_ssa,                   /* execute */
2533   NULL,                                 /* sub */
2534   NULL,                                 /* next */
2535   0,                                    /* static_pass_number */
2536   TV_TREE_SSA_TO_NORMAL,                /* tv_id */
2537   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2538   0,                                    /* properties_provided */
2539   /* ??? If TER is enabled, we also kill gimple.  */
2540   PROP_ssa,                             /* properties_destroyed */
2541   TODO_verify_ssa | TODO_verify_flow
2542     | TODO_verify_stmts,                /* todo_flags_start */
2543   TODO_dump_func | TODO_ggc_collect,    /* todo_flags_finish */
2544   0                                     /* letter */
2545 };