OSDN Git Service

Fix typo...
[pf3gnuchains/gcc-fork.git] / gcc / tree-into-ssa.c
1 /* Rewrite a program in Normal form into SSA.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@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, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, 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 "langhooks.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "expr.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "bitmap.h"
38 #include "tree-flow.h"
39 #include "tree-gimple.h"
40 #include "tree-inline.h"
41 #include "varray.h"
42 #include "timevar.h"
43 #include "hashtab.h"
44 #include "tree-dump.h"
45 #include "tree-pass.h"
46 #include "cfgloop.h"
47 #include "domwalk.h"
48 #include "ggc.h"
49 #include "params.h"
50 #include "vecprim.h"
51
52 /* This file builds the SSA form for a function as described in:
53    R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and K. Zadeck. Efficiently
54    Computing Static Single Assignment Form and the Control Dependence
55    Graph. ACM Transactions on Programming Languages and Systems,
56    13(4):451-490, October 1991.  */
57
58 /* True if the code is in ssa form.  */
59 bool in_ssa_p;
60
61 /* Structure to map a variable VAR to the set of blocks that contain
62    definitions for VAR.  */
63 struct def_blocks_d
64 {
65   /* The variable.  */
66   tree var;
67
68   /* Blocks that contain definitions of VAR.  Bit I will be set if the
69      Ith block contains a definition of VAR.  */
70   bitmap def_blocks;
71
72   /* Blocks that contain a PHI node for VAR.  */
73   bitmap phi_blocks;
74
75   /* Blocks where VAR is live-on-entry.  Similar semantics as
76      DEF_BLOCKS.  */
77   bitmap livein_blocks;
78 };
79
80
81 /* Each entry in DEF_BLOCKS contains an element of type STRUCT
82    DEF_BLOCKS_D, mapping a variable VAR to a bitmap describing all the
83    basic blocks where VAR is defined (assigned a new value).  It also
84    contains a bitmap of all the blocks where VAR is live-on-entry
85    (i.e., there is a use of VAR in block B without a preceding
86    definition in B).  The live-on-entry information is used when
87    computing PHI pruning heuristics.  */
88 static htab_t def_blocks;
89
90 /* Stack of trees used to restore the global currdefs to its original
91    state after completing rewriting of a block and its dominator
92    children.  Its elements have the following properties:
93
94    - An SSA_NAME indicates that the current definition of the
95      underlying variable should be set to the given SSA_NAME.
96
97    - A _DECL node indicates that the underlying variable has no
98      current definition.
99
100    - A NULL node is used to mark the last node associated with the
101      current block.
102
103    - A NULL node at the top entry is used to mark the last node
104      associated with the current block.  */
105 static VEC(tree,heap) *block_defs_stack;
106
107 /* Set of existing SSA names being replaced by update_ssa.  */
108 static sbitmap old_ssa_names;
109
110 /* Set of new SSA names being added by update_ssa.  Note that both
111    NEW_SSA_NAMES and OLD_SSA_NAMES are dense bitmaps because most of
112    the operations done on them are presence tests.  */
113 static sbitmap new_ssa_names;
114
115 /* Symbols whose SSA form needs to be updated or created for the first
116    time.  */
117 static bitmap syms_to_rename;
118
119 /* Set of SSA names that have been marked to be released after they
120    were registered in the replacement table.  They will be finally
121    released after we finish updating the SSA web.  */
122 static bitmap names_to_release;
123
124 /* For each block, the phi nodes that need to be rewritten are stored into
125    these vectors.  */
126
127 typedef VEC(tree, heap) *tree_vec;
128 DEF_VEC_P (tree_vec);
129 DEF_VEC_ALLOC_P (tree_vec, heap);
130
131 static VEC(tree_vec, heap) *phis_to_rewrite;
132
133 /* The bitmap of non-NULL elements of PHIS_TO_REWRITE.  */
134
135 static bitmap blocks_with_phis_to_rewrite;
136
137 /* Growth factor for NEW_SSA_NAMES and OLD_SSA_NAMES.  These sets need
138    to grow as the callers to register_new_name_mapping will typically
139    create new names on the fly.  FIXME.  Currently set to 1/3 to avoid
140    frequent reallocations but still need to find a reasonable growth
141    strategy.  */
142 #define NAME_SETS_GROWTH_FACTOR (MAX (3, num_ssa_names / 3))
143
144 /* Tuple used to represent replacement mappings.  */
145 struct repl_map_d
146 {
147   tree name;
148   bitmap set;
149 };
150
151 /* NEW -> OLD_SET replacement table.  If we are replacing several
152    existing SSA names O_1, O_2, ..., O_j with a new name N_i,
153    then REPL_TBL[N_i] = { O_1, O_2, ..., O_j }.  */
154 static htab_t repl_tbl;
155
156 /* true if register_new_name_mapping needs to initialize the data
157    structures needed by update_ssa.  */
158 static bool need_to_initialize_update_ssa_p = true;
159
160 /* true if update_ssa needs to update virtual operands.  */
161 static bool need_to_update_vops_p = false;
162
163 /* Statistics kept by update_ssa to use in the virtual mapping
164    heuristic.  If the number of virtual mappings is beyond certain
165    threshold, the updater will switch from using the mappings into
166    renaming the virtual symbols from scratch.  In some cases, the
167    large number of name mappings for virtual names causes significant
168    slowdowns in the PHI insertion code.  */
169 struct update_ssa_stats_d
170 {
171   unsigned num_virtual_mappings;
172   unsigned num_total_mappings;
173   bitmap virtual_symbols;
174   unsigned num_virtual_symbols;
175 };
176 static struct update_ssa_stats_d update_ssa_stats;
177
178 /* Global data to attach to the main dominator walk structure.  */
179 struct mark_def_sites_global_data
180 {
181   /* This bitmap contains the variables which are set before they
182      are used in a basic block.  */
183   bitmap kills;
184
185   /* Bitmap of names to rename.  */
186   sbitmap names_to_rename;
187
188   /* Set of blocks that mark_def_sites deems interesting for the
189      renamer to process.  */
190   sbitmap interesting_blocks;
191 };
192
193
194 /* Information stored for SSA names.  */
195 struct ssa_name_info
196 {
197   /* The actual definition of the ssa name.  */
198   tree current_def;
199
200   /* This field indicates whether or not the variable may need PHI nodes.
201      See the enum's definition for more detailed information about the
202      states.  */
203   ENUM_BITFIELD (need_phi_state) need_phi_state : 2;
204
205   /* Age of this record (so that info_for_ssa_name table can be cleared
206      quicky); if AGE < CURRENT_INFO_FOR_SSA_NAME_AGE, then the fields
207      are assumed to be null.  */
208   unsigned age;
209 };
210
211 /* The information associated with names.  */
212 typedef struct ssa_name_info *ssa_name_info_p;
213 DEF_VEC_P (ssa_name_info_p);
214 DEF_VEC_ALLOC_P (ssa_name_info_p, heap);
215
216 static VEC(ssa_name_info_p, heap) *info_for_ssa_name;
217 static unsigned current_info_for_ssa_name_age;
218
219 /* The set of blocks affected by update_ssa.  */
220
221 static bitmap blocks_to_update;
222
223 /* The main entry point to the SSA renamer (rewrite_blocks) may be
224    called several times to do different, but related, tasks.
225    Initially, we need it to rename the whole program into SSA form.
226    At other times, we may need it to only rename into SSA newly
227    exposed symbols.  Finally, we can also call it to incrementally fix
228    an already built SSA web.  */
229 enum rewrite_mode {
230     /* Convert the whole function into SSA form.  */
231     REWRITE_ALL,
232
233     /* Incrementally update the SSA web by replacing existing SSA
234        names with new ones.  See update_ssa for details.  */
235     REWRITE_UPDATE
236 };
237
238
239 /* Use TREE_VISITED to keep track of which statements we want to
240    rename.  When renaming a subset of the variables, not all
241    statements will be processed.  This is decided in mark_def_sites.  */
242 #define REWRITE_THIS_STMT(T)    TREE_VISITED (T)
243
244 /* Use the unsigned flag to keep track of which statements we want to
245    visit when marking new definition sites.  This is slightly
246    different than REWRITE_THIS_STMT: it's used by update_ssa to
247    distinguish statements that need to have both uses and defs
248    processed from those that only need to have their defs processed.
249    Statements that define new SSA names only need to have their defs
250    registered, but they don't need to have their uses renamed.  */
251 #define REGISTER_DEFS_IN_THIS_STMT(T)   (T)->common.unsigned_flag
252
253
254 /* Prototypes for debugging functions.  */
255 extern void dump_tree_ssa (FILE *);
256 extern void debug_tree_ssa (void);
257 extern void debug_def_blocks (void);
258 extern void dump_tree_ssa_stats (FILE *);
259 extern void debug_tree_ssa_stats (void);
260 void dump_update_ssa (FILE *);
261 void debug_update_ssa (void);
262 void dump_names_replaced_by (FILE *, tree);
263 void debug_names_replaced_by (tree);
264
265 /* Get the information associated with NAME.  */
266
267 static inline struct ssa_name_info *
268 get_ssa_name_ann (tree name)
269 {
270   unsigned ver = SSA_NAME_VERSION (name);
271   unsigned len = VEC_length (ssa_name_info_p, info_for_ssa_name);
272   struct ssa_name_info *info;
273
274   if (ver >= len)
275     {
276       unsigned new_len = num_ssa_names;
277
278       VEC_reserve (ssa_name_info_p, heap, info_for_ssa_name, new_len);
279       while (len++ < new_len)
280         {
281           struct ssa_name_info *info = XCNEW (struct ssa_name_info);
282           info->age = current_info_for_ssa_name_age;
283           VEC_quick_push (ssa_name_info_p, info_for_ssa_name, info);
284         }
285     }
286
287   info = VEC_index (ssa_name_info_p, info_for_ssa_name, ver);
288   if (info->age < current_info_for_ssa_name_age)
289     {
290       info->need_phi_state = 0;
291       info->current_def = NULL_TREE;
292       info->age = current_info_for_ssa_name_age;
293     }
294
295   return info;
296 }
297
298 /* Clears info for ssa names.  */
299
300 static void
301 clear_ssa_name_info (void)
302 {
303   current_info_for_ssa_name_age++;
304 }
305
306 /* Gets phi_state field for VAR.  */
307
308 static inline enum need_phi_state
309 get_phi_state (tree var)
310 {
311   if (TREE_CODE (var) == SSA_NAME)
312     return get_ssa_name_ann (var)->need_phi_state;
313   else
314     return var_ann (var)->need_phi_state;
315 }
316
317
318 /* Sets phi_state field for VAR to STATE.  */
319
320 static inline void
321 set_phi_state (tree var, enum need_phi_state state)
322 {
323   if (TREE_CODE (var) == SSA_NAME)
324     get_ssa_name_ann (var)->need_phi_state = state;
325   else
326     var_ann (var)->need_phi_state = state;
327 }
328
329
330 /* Return the current definition for VAR.  */
331
332 tree
333 get_current_def (tree var)
334 {
335   if (TREE_CODE (var) == SSA_NAME)
336     return get_ssa_name_ann (var)->current_def;
337   else
338     return var_ann (var)->current_def;
339 }
340
341
342 /* Sets current definition of VAR to DEF.  */
343
344 void
345 set_current_def (tree var, tree def)
346 {
347   if (TREE_CODE (var) == SSA_NAME)
348     get_ssa_name_ann (var)->current_def = def;
349   else
350     var_ann (var)->current_def = def;
351 }
352
353
354 /* Compute global livein information given the set of blockx where
355    an object is locally live at the start of the block (LIVEIN)
356    and the set of blocks where the object is defined (DEF_BLOCKS).
357
358    Note: This routine augments the existing local livein information
359    to include global livein (i.e., it modifies the underlying bitmap
360    for LIVEIN).  */
361
362 void
363 compute_global_livein (bitmap livein, bitmap def_blocks)
364 {
365   basic_block bb, *worklist, *tos;
366   unsigned i;
367   bitmap_iterator bi;
368
369   tos = worklist
370     = (basic_block *) xmalloc (sizeof (basic_block) * (last_basic_block + 1));
371
372   EXECUTE_IF_SET_IN_BITMAP (livein, 0, i, bi)
373     {
374       *tos++ = BASIC_BLOCK (i);
375     }
376
377   /* Iterate until the worklist is empty.  */
378   while (tos != worklist)
379     {
380       edge e;
381       edge_iterator ei;
382
383       /* Pull a block off the worklist.  */
384       bb = *--tos;
385
386       /* For each predecessor block.  */
387       FOR_EACH_EDGE (e, ei, bb->preds)
388         {
389           basic_block pred = e->src;
390           int pred_index = pred->index;
391
392           /* None of this is necessary for the entry block.  */
393           if (pred != ENTRY_BLOCK_PTR
394               && ! bitmap_bit_p (livein, pred_index)
395               && ! bitmap_bit_p (def_blocks, pred_index))
396             {
397               *tos++ = pred;
398               bitmap_set_bit (livein, pred_index);
399             }
400         }
401     }
402
403   free (worklist);
404 }
405
406
407 /* Cleans up the REWRITE_THIS_STMT and REGISTER_DEFS_IN_THIS_STMT flags for
408    all statements in basic block BB.  */
409
410 static void
411 initialize_flags_in_bb (basic_block bb)
412 {
413   tree phi, stmt;
414   block_stmt_iterator bsi;
415
416   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
417     {
418       REWRITE_THIS_STMT (phi) = 0;
419       REGISTER_DEFS_IN_THIS_STMT (phi) = 0;
420     }
421
422   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
423     {
424       stmt = bsi_stmt (bsi);
425       /* We are going to use the operand cache API, such as
426          SET_USE, SET_DEF, and FOR_EACH_IMM_USE_FAST.  The operand
427          cache for each statement should be up-to-date.  */
428       gcc_assert (!stmt_modified_p (stmt));
429       REWRITE_THIS_STMT (stmt) = 0;
430       REGISTER_DEFS_IN_THIS_STMT (stmt) = 0;
431     }
432 }
433
434 /* Mark block BB as interesting for update_ssa.  */
435
436 static void
437 mark_block_for_update (basic_block bb)
438 {
439   gcc_assert (blocks_to_update != NULL);
440   if (bitmap_bit_p (blocks_to_update, bb->index))
441     return;
442   bitmap_set_bit (blocks_to_update, bb->index);
443   initialize_flags_in_bb (bb);
444 }
445
446 /* Return the set of blocks where variable VAR is defined and the blocks
447    where VAR is live on entry (livein).  If no entry is found in
448    DEF_BLOCKS, a new one is created and returned.  */
449
450 static inline struct def_blocks_d *
451 get_def_blocks_for (tree var)
452 {
453   struct def_blocks_d db, *db_p;
454   void **slot;
455
456   db.var = var;
457   slot = htab_find_slot (def_blocks, (void *) &db, INSERT);
458   if (*slot == NULL)
459     {
460       db_p = XNEW (struct def_blocks_d);
461       db_p->var = var;
462       db_p->def_blocks = BITMAP_ALLOC (NULL);
463       db_p->phi_blocks = BITMAP_ALLOC (NULL);
464       db_p->livein_blocks = BITMAP_ALLOC (NULL);
465       *slot = (void *) db_p;
466     }
467   else
468     db_p = (struct def_blocks_d *) *slot;
469
470   return db_p;
471 }
472
473
474 /* Mark block BB as the definition site for variable VAR.  PHI_P is true if
475    VAR is defined by a PHI node.  */
476
477 static void
478 set_def_block (tree var, basic_block bb, bool phi_p)
479 {
480   struct def_blocks_d *db_p;
481   enum need_phi_state state;
482
483   state = get_phi_state (var);
484   db_p = get_def_blocks_for (var);
485
486   /* Set the bit corresponding to the block where VAR is defined.  */
487   bitmap_set_bit (db_p->def_blocks, bb->index);
488   if (phi_p)
489     bitmap_set_bit (db_p->phi_blocks, bb->index);
490
491   /* Keep track of whether or not we may need to insert PHI nodes.
492
493      If we are in the UNKNOWN state, then this is the first definition
494      of VAR.  Additionally, we have not seen any uses of VAR yet, so
495      we do not need a PHI node for this variable at this time (i.e.,
496      transition to NEED_PHI_STATE_NO).
497
498      If we are in any other state, then we either have multiple definitions
499      of this variable occurring in different blocks or we saw a use of the
500      variable which was not dominated by the block containing the
501      definition(s).  In this case we may need a PHI node, so enter
502      state NEED_PHI_STATE_MAYBE.  */
503   if (state == NEED_PHI_STATE_UNKNOWN)
504     set_phi_state (var, NEED_PHI_STATE_NO);
505   else
506     set_phi_state (var, NEED_PHI_STATE_MAYBE);
507 }
508
509
510 /* Mark block BB as having VAR live at the entry to BB.  */
511
512 static void
513 set_livein_block (tree var, basic_block bb)
514 {
515   struct def_blocks_d *db_p;
516   enum need_phi_state state = get_phi_state (var);
517
518   db_p = get_def_blocks_for (var);
519
520   /* Set the bit corresponding to the block where VAR is live in.  */
521   bitmap_set_bit (db_p->livein_blocks, bb->index);
522
523   /* Keep track of whether or not we may need to insert PHI nodes.
524
525      If we reach here in NEED_PHI_STATE_NO, see if this use is dominated
526      by the single block containing the definition(s) of this variable.  If
527      it is, then we remain in NEED_PHI_STATE_NO, otherwise we transition to
528      NEED_PHI_STATE_MAYBE.  */
529   if (state == NEED_PHI_STATE_NO)
530     {
531       int def_block_index = bitmap_first_set_bit (db_p->def_blocks);
532
533       if (def_block_index == -1
534           || ! dominated_by_p (CDI_DOMINATORS, bb,
535                                BASIC_BLOCK (def_block_index)))
536         set_phi_state (var, NEED_PHI_STATE_MAYBE);
537     }
538   else
539     set_phi_state (var, NEED_PHI_STATE_MAYBE);
540 }
541
542
543 /* Return true if symbol SYM is marked for renaming.  */
544
545 static inline bool
546 symbol_marked_for_renaming (tree sym)
547 {
548   gcc_assert (DECL_P (sym));
549   return bitmap_bit_p (syms_to_rename, DECL_UID (sym));
550 }
551
552
553 /* Return true if NAME is in OLD_SSA_NAMES.  */
554
555 static inline bool
556 is_old_name (tree name)
557 {
558   unsigned ver = SSA_NAME_VERSION (name);
559   return ver < new_ssa_names->n_bits && TEST_BIT (old_ssa_names, ver);
560 }
561
562
563 /* Return true if NAME is in NEW_SSA_NAMES.  */
564
565 static inline bool
566 is_new_name (tree name)
567 {
568   unsigned ver = SSA_NAME_VERSION (name);
569   return ver < new_ssa_names->n_bits && TEST_BIT (new_ssa_names, ver);
570 }
571
572
573 /* Hashing and equality functions for REPL_TBL.  */
574
575 static hashval_t
576 repl_map_hash (const void *p)
577 {
578   return htab_hash_pointer ((const void *)((const struct repl_map_d *)p)->name);
579 }
580
581 static int
582 repl_map_eq (const void *p1, const void *p2)
583 {
584   return ((const struct repl_map_d *)p1)->name
585          == ((const struct repl_map_d *)p2)->name;
586 }
587
588 static void
589 repl_map_free (void *p)
590 {
591   BITMAP_FREE (((struct repl_map_d *)p)->set);
592   free (p);
593 }
594
595
596 /* Return the names replaced by NEW (i.e., REPL_TBL[NEW].SET).  */
597
598 static inline bitmap
599 names_replaced_by (tree new)
600 {
601   struct repl_map_d m;
602   void **slot;
603
604   m.name = new;
605   slot = htab_find_slot (repl_tbl, (void *) &m, NO_INSERT);
606
607   /* If N was not registered in the replacement table, return NULL.  */
608   if (slot == NULL || *slot == NULL)
609     return NULL;
610
611   return ((struct repl_map_d *) *slot)->set;
612 }
613
614
615 /* Add OLD to REPL_TBL[NEW].SET.  */
616
617 static inline void
618 add_to_repl_tbl (tree new, tree old)
619 {
620   struct repl_map_d m, *mp;
621   void **slot;
622
623   m.name = new;
624   slot = htab_find_slot (repl_tbl, (void *) &m, INSERT);
625   if (*slot == NULL)
626     {
627       mp = XNEW (struct repl_map_d);
628       mp->name = new;
629       mp->set = BITMAP_ALLOC (NULL);
630       *slot = (void *) mp;
631     }
632   else
633     mp = (struct repl_map_d *) *slot;
634
635   bitmap_set_bit (mp->set, SSA_NAME_VERSION (old));
636 }
637
638
639 /* Add a new mapping NEW -> OLD REPL_TBL.  Every entry N_i in REPL_TBL
640    represents the set of names O_1 ... O_j replaced by N_i.  This is
641    used by update_ssa and its helpers to introduce new SSA names in an
642    already formed SSA web.  */
643
644 static void
645 add_new_name_mapping (tree new, tree old)
646 {
647   timevar_push (TV_TREE_SSA_INCREMENTAL);
648
649   /* OLD and NEW must be different SSA names for the same symbol.  */
650   gcc_assert (new != old && SSA_NAME_VAR (new) == SSA_NAME_VAR (old));
651
652   /* We may need to grow NEW_SSA_NAMES and OLD_SSA_NAMES because our
653      caller may have created new names since the set was created.  */
654   if (new_ssa_names->n_bits <= num_ssa_names - 1)
655     {
656       unsigned int new_sz = num_ssa_names + NAME_SETS_GROWTH_FACTOR;
657       new_ssa_names = sbitmap_resize (new_ssa_names, new_sz, 0);
658       old_ssa_names = sbitmap_resize (old_ssa_names, new_sz, 0);
659     }
660
661   /* If this mapping is for virtual names, we will need to update
662      virtual operands.  */
663   if (!is_gimple_reg (new))
664     {
665       tree sym;
666       size_t uid;
667
668       need_to_update_vops_p = true;
669
670       /* Keep counts of virtual mappings and symbols to use in the
671          virtual mapping heuristic.  If we have large numbers of
672          virtual mappings for a relatively low number of symbols, it
673          will make more sense to rename the symbols from scratch.
674          Otherwise, the insertion of PHI nodes for each of the old
675          names in these mappings will be very slow.  */
676       sym = SSA_NAME_VAR (new);
677       uid = DECL_UID (sym);
678       update_ssa_stats.num_virtual_mappings++;
679       if (!bitmap_bit_p (update_ssa_stats.virtual_symbols, uid))
680         {
681           bitmap_set_bit (update_ssa_stats.virtual_symbols, uid);
682           update_ssa_stats.num_virtual_symbols++;
683         }
684     }
685
686   /* Update the REPL_TBL table.  */
687   add_to_repl_tbl (new, old);
688
689   /* If OLD had already been registered as a new name, then all the
690      names that OLD replaces should also be replaced by NEW.  */
691   if (is_new_name (old))
692     bitmap_ior_into (names_replaced_by (new), names_replaced_by (old));
693
694   /* Register NEW and OLD in NEW_SSA_NAMES and OLD_SSA_NAMES,
695      respectively.  */
696   SET_BIT (new_ssa_names, SSA_NAME_VERSION (new));
697   SET_BIT (old_ssa_names, SSA_NAME_VERSION (old));
698
699   /* Update mapping counter to use in the virtual mapping heuristic.  */
700   update_ssa_stats.num_total_mappings++;
701
702   timevar_pop (TV_TREE_SSA_INCREMENTAL);
703 }
704
705
706 /* Call back for walk_dominator_tree used to collect definition sites
707    for every variable in the function.  For every statement S in block
708    BB:
709
710    1- Variables defined by S in the DEFS of S are marked in the bitmap
711       WALK_DATA->GLOBAL_DATA->KILLS.
712
713    2- If S uses a variable VAR and there is no preceding kill of VAR,
714       then it is marked in the LIVEIN_BLOCKS bitmap associated with VAR.
715
716    This information is used to determine which variables are live
717    across block boundaries to reduce the number of PHI nodes
718    we create.  */
719
720 static void
721 mark_def_sites (struct dom_walk_data *walk_data,
722                 basic_block bb,
723                 block_stmt_iterator bsi)
724 {
725   struct mark_def_sites_global_data *gd =
726      (struct mark_def_sites_global_data *) walk_data->global_data;
727   bitmap kills = gd->kills;
728   tree stmt, def;
729   use_operand_p use_p;
730   def_operand_p def_p;
731   ssa_op_iter iter;
732
733   stmt = bsi_stmt (bsi);
734   update_stmt_if_modified (stmt);
735
736   gcc_assert (blocks_to_update == NULL);
737   REGISTER_DEFS_IN_THIS_STMT (stmt) = 0;
738   REWRITE_THIS_STMT (stmt) = 0;
739
740   /* If a variable is used before being set, then the variable is live
741      across a block boundary, so mark it live-on-entry to BB.  */
742   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
743                             SSA_OP_USE | SSA_OP_VUSE | SSA_OP_VMUSTKILL)
744     {
745       tree sym = USE_FROM_PTR (use_p);
746       gcc_assert (DECL_P (sym));
747       if (!bitmap_bit_p (kills, DECL_UID (sym)))
748         set_livein_block (sym, bb);
749       REWRITE_THIS_STMT (stmt) = 1;
750     }
751   
752   /* Note that virtual definitions are irrelevant for computing KILLS
753      because a V_MAY_DEF does not constitute a killing definition of the
754      variable.  However, the operand of a virtual definitions is a use
755      of the variable, so it may cause the variable to be considered
756      live-on-entry.  */
757   FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
758     {
759       tree sym = USE_FROM_PTR (use_p);
760       gcc_assert (DECL_P (sym));
761       set_livein_block (sym, bb);
762       set_def_block (sym, bb, false);
763       REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
764       REWRITE_THIS_STMT (stmt) = 1;
765     }
766
767   /* Now process the defs and must-defs made by this statement.  */
768   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF | SSA_OP_VMUSTDEF)
769     {
770       gcc_assert (DECL_P (def));
771       set_def_block (def, bb, false);
772       bitmap_set_bit (kills, DECL_UID (def));
773       REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
774     }
775
776   /* If we found the statement interesting then also mark the block BB
777      as interesting.  */
778   if (REWRITE_THIS_STMT (stmt) || REGISTER_DEFS_IN_THIS_STMT (stmt))
779     SET_BIT (gd->interesting_blocks, bb->index);
780 }
781
782
783 /* Given a set of blocks with variable definitions (DEF_BLOCKS),
784    return a bitmap with all the blocks in the iterated dominance
785    frontier of the blocks in DEF_BLOCKS.  DFS contains dominance
786    frontier information as returned by compute_dominance_frontiers.
787    
788    The resulting set of blocks are the potential sites where PHI nodes
789    are needed.  The caller is responsible from freeing the memory
790    allocated for the return value.  */
791
792 static bitmap
793 find_idf (bitmap def_blocks, bitmap *dfs)
794 {
795   bitmap_iterator bi;
796   unsigned bb_index;
797   VEC(int,heap) *work_stack;
798   bitmap phi_insertion_points;
799
800   work_stack = VEC_alloc (int, heap, n_basic_blocks);
801   phi_insertion_points = BITMAP_ALLOC (NULL);
802
803   /* Seed the work list with all the blocks in DEF_BLOCKS.  */
804   EXECUTE_IF_SET_IN_BITMAP (def_blocks, 0, bb_index, bi)
805     /* We use VEC_quick_push here for speed.  This is safe because we
806        know that the number of definition blocks is no greater than
807        the number of basic blocks, which is the initial capacity of
808        WORK_STACK.  */
809     VEC_quick_push (int, work_stack, bb_index);
810
811   /* Pop a block off the worklist, add every block that appears in
812      the original block's DF that we have not already processed to
813      the worklist.  Iterate until the worklist is empty.   Blocks
814      which are added to the worklist are potential sites for
815      PHI nodes.  */
816   while (VEC_length (int, work_stack) > 0)
817     {
818       bb_index = VEC_pop (int, work_stack);
819
820       /* Since the registration of NEW -> OLD name mappings is done
821          separately from the call to update_ssa, when updating the SSA
822          form, the basic blocks where new and/or old names are defined
823          may have disappeared by CFG cleanup calls.  In this case,
824          we may pull a non-existing block from the work stack.  */
825       gcc_assert (bb_index < (unsigned) last_basic_block);
826
827       EXECUTE_IF_AND_COMPL_IN_BITMAP (dfs[bb_index], phi_insertion_points,
828                                       0, bb_index, bi)
829         {
830           /* Use a safe push because if there is a definition of VAR
831              in every basic block, then WORK_STACK may eventually have
832              more than N_BASIC_BLOCK entries.  */
833           VEC_safe_push (int, heap, work_stack, bb_index);
834           bitmap_set_bit (phi_insertion_points, bb_index);
835         }
836     }
837
838   VEC_free (int, heap, work_stack);
839
840   return phi_insertion_points;
841 }
842
843
844 /* Return the set of blocks where variable VAR is defined and the blocks
845    where VAR is live on entry (livein).  Return NULL, if no entry is
846    found in DEF_BLOCKS.  */
847
848 static inline struct def_blocks_d *
849 find_def_blocks_for (tree var)
850 {
851   struct def_blocks_d dm;
852   dm.var = var;
853   return (struct def_blocks_d *) htab_find (def_blocks, &dm);
854 }
855
856
857 /* Retrieve or create a default definition for symbol SYM.  */
858
859 static inline tree
860 get_default_def_for (tree sym)
861 {
862   tree ddef = default_def (sym);
863
864   if (ddef == NULL_TREE)
865     {
866       ddef = make_ssa_name (sym, build_empty_stmt ());
867       set_default_def (sym, ddef);
868     }
869
870   return ddef;
871 }
872
873
874 /* Marks phi node PHI in basic block BB for rewrite.  */
875
876 static void
877 mark_phi_for_rewrite (basic_block bb, tree phi)
878 {
879   tree_vec phis;
880   unsigned i, idx = bb->index;
881
882   if (REWRITE_THIS_STMT (phi))
883     return;
884   REWRITE_THIS_STMT (phi) = 1;
885
886   if (!blocks_with_phis_to_rewrite)
887     return;
888
889   bitmap_set_bit (blocks_with_phis_to_rewrite, idx);
890   VEC_reserve (tree_vec, heap, phis_to_rewrite, last_basic_block + 1);
891   for (i = VEC_length (tree_vec, phis_to_rewrite); i <= idx; i++)
892     VEC_quick_push (tree_vec, phis_to_rewrite, NULL);
893
894   phis = VEC_index (tree_vec, phis_to_rewrite, idx);
895   if (!phis)
896     phis = VEC_alloc (tree, heap, 10);
897
898   VEC_safe_push (tree, heap, phis, phi);
899   VEC_replace (tree_vec, phis_to_rewrite, idx, phis);
900 }
901
902 /* Insert PHI nodes for variable VAR using the iterated dominance
903    frontier given in PHI_INSERTION_POINTS.  If UPDATE_P is true, this
904    function assumes that the caller is incrementally updating the SSA
905    form, in which case (1) VAR is assumed to be an SSA name, (2) a new
906    SSA name is created for VAR's symbol, and, (3) all the arguments
907    for the newly created PHI node are set to VAR.
908
909    PHI_INSERTION_POINTS is updated to reflect nodes that already had a
910    PHI node for VAR.  On exit, only the nodes that received a PHI node
911    for VAR will be present in PHI_INSERTION_POINTS.  */
912
913 static void
914 insert_phi_nodes_for (tree var, bitmap phi_insertion_points, bool update_p)
915 {
916   unsigned bb_index;
917   edge e;
918   tree phi;
919   basic_block bb;
920   bitmap_iterator bi;
921   struct def_blocks_d *def_map;
922
923   def_map = find_def_blocks_for (var);
924   gcc_assert (def_map);
925
926   /* Remove the blocks where we already have PHI nodes for VAR.  */
927   bitmap_and_compl_into (phi_insertion_points, def_map->phi_blocks);
928
929   /* Now compute global livein for this variable.  Note this modifies
930      def_map->livein_blocks.  */
931   compute_global_livein (def_map->livein_blocks, def_map->def_blocks);
932
933   /* And insert the PHI nodes.  */
934   EXECUTE_IF_AND_IN_BITMAP (phi_insertion_points, def_map->livein_blocks,
935                             0, bb_index, bi)
936     {
937       bb = BASIC_BLOCK (bb_index);
938       if (update_p)
939         mark_block_for_update (bb);
940
941       if (update_p && TREE_CODE (var) == SSA_NAME)
942         {
943           /* If we are rewriting SSA names, create the LHS of the PHI
944              node by duplicating VAR.  This is useful in the case of
945              pointers, to also duplicate pointer attributes (alias
946              information, in particular).  */
947           edge_iterator ei;
948           tree new_lhs;
949
950           phi = create_phi_node (var, bb);
951           new_lhs = duplicate_ssa_name (var, phi);
952           SET_PHI_RESULT (phi, new_lhs);
953           add_new_name_mapping (new_lhs, var);
954
955           /* Add VAR to every argument slot of PHI.  We need VAR in
956              every argument so that rewrite_update_phi_arguments knows
957              which name is this PHI node replacing.  If VAR is a
958              symbol marked for renaming, this is not necessary, the
959              renamer will use the symbol on the LHS to get its
960              reaching definition.  */
961           FOR_EACH_EDGE (e, ei, bb->preds)
962             add_phi_arg (phi, var, e);
963         }
964       else
965         {
966           tree sym = DECL_P (var) ? var : SSA_NAME_VAR (var);
967           phi = create_phi_node (sym, bb);
968         }
969
970       /* Mark this PHI node as interesting for update_ssa.  */
971       REGISTER_DEFS_IN_THIS_STMT (phi) = 1;
972       mark_phi_for_rewrite (bb, phi);
973     }
974 }
975
976
977 /* Insert PHI nodes at the dominance frontier of blocks with variable
978    definitions.  DFS contains the dominance frontier information for
979    the flowgraph.  PHI nodes will only be inserted at the dominance
980    frontier of definition blocks for variables whose NEED_PHI_STATE
981    annotation is marked as ``maybe'' or ``unknown'' (computed by
982    mark_def_sites).  */
983
984 static void
985 insert_phi_nodes (bitmap *dfs)
986 {
987   referenced_var_iterator rvi;
988   tree var;
989
990   timevar_push (TV_TREE_INSERT_PHI_NODES);
991   
992   FOR_EACH_REFERENCED_VAR (var, rvi)
993     {
994       struct def_blocks_d *def_map;
995       bitmap idf;
996
997       def_map = find_def_blocks_for (var);
998       if (def_map == NULL)
999         continue;
1000
1001       if (get_phi_state (var) != NEED_PHI_STATE_NO)
1002         {
1003           idf = find_idf (def_map->def_blocks, dfs);
1004           insert_phi_nodes_for (var, idf, false);
1005           BITMAP_FREE (idf);
1006         }
1007     }
1008
1009   timevar_pop (TV_TREE_INSERT_PHI_NODES);
1010 }
1011
1012
1013 /* Register DEF (an SSA_NAME) to be a new definition for its underlying
1014    variable (SSA_NAME_VAR (DEF)) and push VAR's current reaching definition
1015    into the stack pointed to by BLOCK_DEFS_P.  */
1016
1017 void
1018 register_new_def (tree def, VEC(tree,heap) **block_defs_p)
1019 {
1020   tree var = SSA_NAME_VAR (def);
1021   tree currdef;
1022    
1023   /* If this variable is set in a single basic block and all uses are
1024      dominated by the set(s) in that single basic block, then there is
1025      no reason to record anything for this variable in the block local
1026      definition stacks.  Doing so just wastes time and memory.
1027
1028      This is the same test to prune the set of variables which may
1029      need PHI nodes.  So we just use that information since it's already
1030      computed and available for us to use.  */
1031   if (get_phi_state (var) == NEED_PHI_STATE_NO)
1032     {
1033       set_current_def (var, def);
1034       return;
1035     }
1036
1037   currdef = get_current_def (var);
1038
1039   /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
1040      later used by the dominator tree callbacks to restore the reaching
1041      definitions for all the variables defined in the block after a recursive
1042      visit to all its immediately dominated blocks.  If there is no current
1043      reaching definition, then just record the underlying _DECL node.  */
1044   VEC_safe_push (tree, heap, *block_defs_p, currdef ? currdef : var);
1045
1046   /* Set the current reaching definition for VAR to be DEF.  */
1047   set_current_def (var, def);
1048 }
1049
1050
1051 /* Perform a depth-first traversal of the dominator tree looking for
1052    variables to rename.  BB is the block where to start searching.
1053    Renaming is a five step process:
1054
1055    1- Every definition made by PHI nodes at the start of the blocks is
1056       registered as the current definition for the corresponding variable.
1057
1058    2- Every statement in BB is rewritten.  USE and VUSE operands are
1059       rewritten with their corresponding reaching definition.  DEF and
1060       VDEF targets are registered as new definitions.
1061       
1062    3- All the PHI nodes in successor blocks of BB are visited.  The
1063       argument corresponding to BB is replaced with its current reaching
1064       definition.
1065
1066    4- Recursively rewrite every dominator child block of BB.
1067
1068    5- Restore (in reverse order) the current reaching definition for every
1069       new definition introduced in this block.  This is done so that when
1070       we return from the recursive call, all the current reaching
1071       definitions are restored to the names that were valid in the
1072       dominator parent of BB.  */
1073
1074 /* SSA Rewriting Step 1.  Initialization, create a block local stack
1075    of reaching definitions for new SSA names produced in this block
1076    (BLOCK_DEFS).  Register new definitions for every PHI node in the
1077    block.  */
1078
1079 static void
1080 rewrite_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1081                           basic_block bb)
1082 {
1083   tree phi;
1084
1085   if (dump_file && (dump_flags & TDF_DETAILS))
1086     fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
1087
1088   /* Mark the unwind point for this block.  */
1089   VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
1090
1091   /* Step 1.  Register new definitions for every PHI node in the block.
1092      Conceptually, all the PHI nodes are executed in parallel and each PHI
1093      node introduces a new version for the associated variable.  */
1094   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1095     {
1096       tree result = PHI_RESULT (phi);
1097       register_new_def (result, &block_defs_stack);
1098     }
1099 }
1100
1101
1102 /* Return the current definition for variable VAR.  If none is found,
1103    create a new SSA name to act as the zeroth definition for VAR.  If VAR
1104    is call clobbered and there exists a more recent definition of
1105    GLOBAL_VAR, return the definition for GLOBAL_VAR.  This means that VAR
1106    has been clobbered by a function call since its last assignment.  */
1107
1108 static tree
1109 get_reaching_def (tree var)
1110 {
1111   tree currdef_var, avar;
1112   
1113   /* Lookup the current reaching definition for VAR.  */
1114   currdef_var = get_current_def (var);
1115
1116   /* If there is no reaching definition for VAR, create and register a
1117      default definition for it (if needed).  */
1118   if (currdef_var == NULL_TREE)
1119     {
1120       avar = DECL_P (var) ? var : SSA_NAME_VAR (var);
1121       currdef_var = get_default_def_for (avar);
1122       set_current_def (var, currdef_var);
1123     }
1124
1125   /* Return the current reaching definition for VAR, or the default
1126      definition, if we had to create one.  */
1127   return currdef_var;
1128 }
1129
1130
1131 /* SSA Rewriting Step 2.  Rewrite every variable used in each statement in
1132    the block with its immediate reaching definitions.  Update the current
1133    definition of a variable when a new real or virtual definition is found.  */
1134
1135 static void
1136 rewrite_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1137               basic_block bb ATTRIBUTE_UNUSED,
1138               block_stmt_iterator si)
1139 {
1140   tree stmt;
1141   use_operand_p use_p;
1142   def_operand_p def_p;
1143   ssa_op_iter iter;
1144
1145   stmt = bsi_stmt (si);
1146
1147   /* If mark_def_sites decided that we don't need to rewrite this
1148      statement, ignore it.  */
1149   gcc_assert (blocks_to_update == NULL);
1150   if (!REWRITE_THIS_STMT (stmt) && !REGISTER_DEFS_IN_THIS_STMT (stmt))
1151     return;
1152
1153   if (dump_file && (dump_flags & TDF_DETAILS))
1154     {
1155       fprintf (dump_file, "Renaming statement ");
1156       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1157       fprintf (dump_file, "\n");
1158     }
1159
1160   /* Step 1.  Rewrite USES and VUSES in the statement.  */
1161   if (REWRITE_THIS_STMT (stmt))
1162     FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
1163                               SSA_OP_ALL_USES|SSA_OP_ALL_KILLS)
1164       {
1165         tree var = USE_FROM_PTR (use_p);
1166         gcc_assert (DECL_P (var));
1167         SET_USE (use_p, get_reaching_def (var));
1168       }
1169
1170   /* Step 2.  Register the statement's DEF and VDEF operands.  */
1171   if (REGISTER_DEFS_IN_THIS_STMT (stmt))
1172     FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
1173       {
1174         tree var = DEF_FROM_PTR (def_p);
1175         gcc_assert (DECL_P (var));
1176         SET_DEF (def_p, make_ssa_name (var, stmt));
1177         register_new_def (DEF_FROM_PTR (def_p), &block_defs_stack);
1178       }
1179 }
1180
1181
1182 /* SSA Rewriting Step 3.  Visit all the successor blocks of BB looking for
1183    PHI nodes.  For every PHI node found, add a new argument containing the
1184    current reaching definition for the variable and the edge through which
1185    that definition is reaching the PHI node.  */
1186
1187 static void
1188 rewrite_add_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1189                            basic_block bb)
1190 {
1191   edge e;
1192   edge_iterator ei;
1193
1194   FOR_EACH_EDGE (e, ei, bb->succs)
1195     {
1196       tree phi;
1197
1198       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
1199         {
1200           tree currdef;
1201           currdef = get_reaching_def (SSA_NAME_VAR (PHI_RESULT (phi)));
1202           add_phi_arg (phi, currdef, e);
1203         }
1204     }
1205 }
1206
1207
1208 /* Called after visiting basic block BB.  Restore CURRDEFS to its
1209    original value.  */
1210
1211 static void
1212 rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1213                         basic_block bb ATTRIBUTE_UNUSED)
1214 {
1215   /* Restore CURRDEFS to its original state.  */
1216   while (VEC_length (tree, block_defs_stack) > 0)
1217     {
1218       tree tmp = VEC_pop (tree, block_defs_stack);
1219       tree saved_def, var;
1220
1221       if (tmp == NULL_TREE)
1222         break;
1223
1224       /* If we recorded an SSA_NAME, then make the SSA_NAME the current
1225          definition of its underlying variable.  If we recorded anything
1226          else, it must have been an _DECL node and its current reaching
1227          definition must have been NULL.  */
1228       if (TREE_CODE (tmp) == SSA_NAME)
1229         {
1230           saved_def = tmp;
1231           var = SSA_NAME_VAR (saved_def);
1232         }
1233       else
1234         {
1235           saved_def = NULL;
1236           var = tmp;
1237         }
1238                                                                                 
1239       set_current_def (var, saved_def);
1240     }
1241 }
1242
1243
1244 /* Dump SSA information to FILE.  */
1245
1246 void
1247 dump_tree_ssa (FILE *file)
1248 {
1249   basic_block bb;
1250   const char *funcname
1251     = lang_hooks.decl_printable_name (current_function_decl, 2);
1252
1253   fprintf (file, "SSA information for %s\n\n", funcname);
1254
1255   FOR_EACH_BB (bb)
1256     {
1257       dump_bb (bb, file, 0);
1258       fputs ("    ", file);
1259       print_generic_stmt (file, phi_nodes (bb), dump_flags);
1260       fputs ("\n\n", file);
1261     }
1262 }
1263
1264
1265 /* Dump SSA information to stderr.  */
1266
1267 void
1268 debug_tree_ssa (void)
1269 {
1270   dump_tree_ssa (stderr);
1271 }
1272
1273
1274 /* Dump statistics for the hash table HTAB.  */
1275
1276 static void
1277 htab_statistics (FILE *file, htab_t htab)
1278 {
1279   fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1280            (long) htab_size (htab),
1281            (long) htab_elements (htab),
1282            htab_collisions (htab));
1283 }
1284
1285
1286 /* Dump SSA statistics on FILE.  */
1287
1288 void
1289 dump_tree_ssa_stats (FILE *file)
1290 {
1291   fprintf (file, "\nHash table statistics:\n");
1292
1293   fprintf (file, "    def_blocks: ");
1294   htab_statistics (file, def_blocks);
1295
1296   fprintf (file, "\n");
1297 }
1298
1299
1300 /* Dump SSA statistics on stderr.  */
1301
1302 void
1303 debug_tree_ssa_stats (void)
1304 {
1305   dump_tree_ssa_stats (stderr);
1306 }
1307
1308
1309 /* Hashing and equality functions for DEF_BLOCKS.  */
1310
1311 static hashval_t
1312 def_blocks_hash (const void *p)
1313 {
1314   return htab_hash_pointer
1315         ((const void *)((const struct def_blocks_d *)p)->var);
1316 }
1317
1318 static int
1319 def_blocks_eq (const void *p1, const void *p2)
1320 {
1321   return ((const struct def_blocks_d *)p1)->var
1322          == ((const struct def_blocks_d *)p2)->var;
1323 }
1324
1325
1326 /* Free memory allocated by one entry in DEF_BLOCKS.  */
1327
1328 static void
1329 def_blocks_free (void *p)
1330 {
1331   struct def_blocks_d *entry = (struct def_blocks_d *) p;
1332   BITMAP_FREE (entry->def_blocks);
1333   BITMAP_FREE (entry->phi_blocks);
1334   BITMAP_FREE (entry->livein_blocks);
1335   free (entry);
1336 }
1337
1338
1339 /* Callback for htab_traverse to dump the DEF_BLOCKS hash table.  */
1340
1341 static int
1342 debug_def_blocks_r (void **slot, void *data ATTRIBUTE_UNUSED)
1343 {
1344   struct def_blocks_d *db_p = (struct def_blocks_d *) *slot;
1345   
1346   fprintf (stderr, "VAR: ");
1347   print_generic_expr (stderr, db_p->var, dump_flags);
1348   bitmap_print (stderr, db_p->def_blocks, ", DEF_BLOCKS: { ", "}");
1349   bitmap_print (stderr, db_p->livein_blocks, ", LIVEIN_BLOCKS: { ", "}\n");
1350
1351   return 1;
1352 }
1353
1354
1355 /* Dump the DEF_BLOCKS hash table on stderr.  */
1356
1357 void
1358 debug_def_blocks (void)
1359 {
1360   htab_traverse (def_blocks, debug_def_blocks_r, NULL);
1361 }
1362
1363
1364 /* Register NEW_NAME to be the new reaching definition for OLD_NAME.  */
1365
1366 static inline void
1367 register_new_update_single (tree new_name, tree old_name)
1368 {
1369   tree currdef = get_current_def (old_name);
1370
1371   /* Push the current reaching definition into *BLOCK_DEFS_P.
1372      This stack is later used by the dominator tree callbacks to
1373      restore the reaching definitions for all the variables
1374      defined in the block after a recursive visit to all its
1375      immediately dominated blocks.  */
1376   VEC_reserve (tree, heap, block_defs_stack, 2);
1377   VEC_quick_push (tree, block_defs_stack, currdef);
1378   VEC_quick_push (tree, block_defs_stack, old_name);
1379
1380   /* Set the current reaching definition for OLD_NAME to be
1381      NEW_NAME.  */
1382   set_current_def (old_name, new_name);
1383 }
1384
1385
1386 /* Register NEW_NAME to be the new reaching definition for all the
1387    names in OLD_NAMES.  Used by the incremental SSA update routines to
1388    replace old SSA names with new ones.  */
1389
1390 static inline void
1391 register_new_update_set (tree new_name, bitmap old_names)
1392 {
1393   bitmap_iterator bi;
1394   unsigned i;
1395
1396   EXECUTE_IF_SET_IN_BITMAP (old_names, 0, i, bi)
1397     register_new_update_single (new_name, ssa_name (i));
1398 }
1399
1400
1401 /* Initialization of block data structures for the incremental SSA
1402    update pass.  Create a block local stack of reaching definitions
1403    for new SSA names produced in this block (BLOCK_DEFS).  Register
1404    new definitions for every PHI node in the block.  */
1405
1406 static void
1407 rewrite_update_init_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1408                            basic_block bb)
1409 {
1410   edge e;
1411   edge_iterator ei;
1412   tree phi;
1413   bool is_abnormal_phi;
1414
1415   if (dump_file && (dump_flags & TDF_DETAILS))
1416     fprintf (dump_file, "\n\nRegistering new PHI nodes in block #%d\n\n",
1417              bb->index);
1418
1419   /* Mark the unwind point for this block.  */
1420   VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
1421
1422   if (!bitmap_bit_p (blocks_to_update, bb->index))
1423     return;
1424
1425   /* Mark the LHS if any of the arguments flows through an abnormal
1426      edge.  */
1427   is_abnormal_phi = false;
1428   FOR_EACH_EDGE (e, ei, bb->preds)
1429     if (e->flags & EDGE_ABNORMAL)
1430       {
1431         is_abnormal_phi = true;
1432         break;
1433       }
1434
1435   /* If any of the PHI nodes is a replacement for a name in
1436      OLD_SSA_NAMES or it's one of the names in NEW_SSA_NAMES, then
1437      register it as a new definition for its corresponding name.  Also
1438      register definitions for names whose underlying symbols are
1439      marked for renaming.  */
1440
1441   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1442     {
1443       tree lhs, lhs_sym;
1444
1445       if (!REGISTER_DEFS_IN_THIS_STMT (phi))
1446         continue;
1447       
1448       lhs = PHI_RESULT (phi);
1449       lhs_sym = SSA_NAME_VAR (lhs);
1450
1451       if (symbol_marked_for_renaming (lhs_sym))
1452         register_new_update_single (lhs, lhs_sym);
1453       else
1454         {
1455           /* If LHS is a new name, register a new definition for all
1456              the names replaced by LHS.  */
1457           if (is_new_name (lhs))
1458             register_new_update_set (lhs, names_replaced_by (lhs));
1459           
1460           /* If LHS is an OLD name, register it as a new definition
1461              for itself.  */
1462           if (is_old_name (lhs))
1463             register_new_update_single (lhs, lhs);
1464         }
1465
1466       if (is_abnormal_phi)
1467         SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs) = 1;
1468     }
1469 }
1470
1471
1472 /* Called after visiting block BB.  Unwind BLOCK_DEFS_STACK to restore
1473    the current reaching definition of every name re-written in BB to
1474    the original reaching definition before visiting BB.  This
1475    unwinding must be done in the opposite order to what is done in
1476    register_new_update_set.  */
1477
1478 static void
1479 rewrite_update_fini_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1480                            basic_block bb ATTRIBUTE_UNUSED)
1481 {
1482   while (VEC_length (tree, block_defs_stack) > 0)
1483     {
1484       tree var = VEC_pop (tree, block_defs_stack);
1485       tree saved_def;
1486       
1487       /* NULL indicates the unwind stop point for this block (see
1488          rewrite_update_init_block).  */
1489       if (var == NULL)
1490         return;
1491
1492       saved_def = VEC_pop (tree, block_defs_stack);
1493       set_current_def (var, saved_def);
1494     }
1495 }
1496
1497
1498 /* If the operand pointed to by USE_P is a name in OLD_SSA_NAMES or
1499    it is a symbol marked for renaming, replace it with USE_P's current
1500    reaching definition.  */
1501
1502 static inline void
1503 maybe_replace_use (use_operand_p use_p)
1504 {
1505   tree rdef = NULL_TREE;
1506   tree use = USE_FROM_PTR (use_p);
1507   tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
1508
1509   if (symbol_marked_for_renaming (sym))
1510     rdef = get_reaching_def (sym);
1511   else if (is_old_name (use))
1512     rdef = get_reaching_def (use);
1513
1514   if (rdef && rdef != use)
1515     SET_USE (use_p, rdef);
1516 }
1517
1518
1519 /* If the operand pointed to by DEF_P is an SSA name in NEW_SSA_NAMES
1520    or OLD_SSA_NAMES, or if it is a symbol marked for renaming,
1521    register it as the current definition for the names replaced by
1522    DEF_P.  */
1523
1524 static inline void
1525 maybe_register_def (def_operand_p def_p, tree stmt)
1526 {
1527   tree def = DEF_FROM_PTR (def_p);
1528   tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);
1529
1530   /* If DEF is a naked symbol that needs renaming, create a
1531      new name for it.  */
1532   if (symbol_marked_for_renaming (sym))
1533     {
1534       if (DECL_P (def))
1535         {
1536           def = make_ssa_name (def, stmt);
1537           SET_DEF (def_p, def);
1538         }
1539
1540       register_new_update_single (def, sym);
1541     }
1542   else
1543     {
1544       /* If DEF is a new name, register it as a new definition
1545          for all the names replaced by DEF.  */
1546       if (is_new_name (def))
1547         register_new_update_set (def, names_replaced_by (def));
1548
1549       /* If DEF is an old name, register DEF as a new
1550          definition for itself.  */
1551       if (is_old_name (def))
1552         register_new_update_single (def, def);
1553     }
1554 }
1555
1556
1557 /* Update every variable used in the statement pointed-to by SI.  The
1558    statement is assumed to be in SSA form already.  Names in
1559    OLD_SSA_NAMES used by SI will be updated to their current reaching
1560    definition.  Names in OLD_SSA_NAMES or NEW_SSA_NAMES defined by SI
1561    will be registered as a new definition for their corresponding name
1562    in OLD_SSA_NAMES.  */
1563
1564 static void
1565 rewrite_update_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1566                      basic_block bb ATTRIBUTE_UNUSED,
1567                      block_stmt_iterator si)
1568 {
1569   stmt_ann_t ann;
1570   tree stmt;
1571   use_operand_p use_p;
1572   def_operand_p def_p;
1573   ssa_op_iter iter;
1574
1575   stmt = bsi_stmt (si);
1576   ann = stmt_ann (stmt);
1577
1578   gcc_assert (bitmap_bit_p (blocks_to_update, bb->index));
1579
1580   /* Only update marked statements.  */
1581   if (!REWRITE_THIS_STMT (stmt) && !REGISTER_DEFS_IN_THIS_STMT (stmt))
1582     return;
1583
1584   if (dump_file && (dump_flags & TDF_DETAILS))
1585     {
1586       fprintf (dump_file, "Updating SSA information for statement ");
1587       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1588       fprintf (dump_file, "\n");
1589     }
1590
1591   /* Rewrite USES included in OLD_SSA_NAMES and USES whose underlying
1592      symbol is marked for renaming.  */
1593   if (REWRITE_THIS_STMT (stmt))
1594     {
1595       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1596         maybe_replace_use (use_p);
1597
1598       if (need_to_update_vops_p)
1599         FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter,
1600                                   SSA_OP_VIRTUAL_USES | SSA_OP_VIRTUAL_KILLS)
1601           maybe_replace_use (use_p);
1602     }
1603
1604   /* Register definitions of names in NEW_SSA_NAMES and OLD_SSA_NAMES.
1605      Also register definitions for names whose underlying symbol is
1606      marked for renaming.  */
1607   if (REGISTER_DEFS_IN_THIS_STMT (stmt))
1608     {
1609       FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_DEF)
1610         maybe_register_def (def_p, stmt);
1611
1612       if (need_to_update_vops_p)
1613         FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_VIRTUAL_DEFS)
1614           maybe_register_def (def_p, stmt);
1615     }
1616 }
1617
1618
1619 /* Replace the operand pointed to by USE_P with USE's current reaching
1620    definition.  */
1621
1622 static inline void
1623 replace_use (use_operand_p use_p, tree use)
1624 {
1625   tree rdef = get_reaching_def (use);
1626   if (rdef != use)
1627     SET_USE (use_p, rdef);
1628 }
1629
1630
1631 /* Visit all the successor blocks of BB looking for PHI nodes.  For
1632    every PHI node found, check if any of its arguments is in
1633    OLD_SSA_NAMES.  If so, and if the argument has a current reaching
1634    definition, replace it.  */
1635
1636 static void
1637 rewrite_update_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1638                               basic_block bb)
1639 {
1640   edge e;
1641   edge_iterator ei;
1642   unsigned i;
1643
1644   FOR_EACH_EDGE (e, ei, bb->succs)
1645     {
1646       tree phi;
1647       tree_vec phis;
1648
1649       if (!bitmap_bit_p (blocks_with_phis_to_rewrite, e->dest->index))
1650         continue;
1651      
1652       phis = VEC_index (tree_vec, phis_to_rewrite, e->dest->index);
1653       for (i = 0; VEC_iterate (tree, phis, i, phi); i++)
1654         {
1655           tree arg;
1656           use_operand_p arg_p;
1657
1658           gcc_assert (REWRITE_THIS_STMT (phi));
1659
1660           arg_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
1661           arg = USE_FROM_PTR (arg_p);
1662
1663           if (arg && !DECL_P (arg) && TREE_CODE (arg) != SSA_NAME)
1664             continue;
1665
1666           if (arg == NULL_TREE)
1667             {
1668               /* When updating a PHI node for a recently introduced
1669                  symbol we may find NULL arguments.  That's why we
1670                  take the symbol from the LHS of the PHI node.  */
1671               replace_use (arg_p, SSA_NAME_VAR (PHI_RESULT (phi)));
1672             }
1673           else
1674             {
1675               tree sym = DECL_P (arg) ? arg : SSA_NAME_VAR (arg);
1676
1677               if (symbol_marked_for_renaming (sym))
1678                 replace_use (arg_p, sym);
1679               else if (is_old_name (arg))
1680                 replace_use (arg_p, arg);
1681             }
1682
1683           if (e->flags & EDGE_ABNORMAL)
1684             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (arg_p)) = 1;
1685         }
1686     }
1687 }
1688
1689
1690 /* Rewrite the actual blocks, statements, and PHI arguments, to be in SSA
1691    form.  
1692
1693    ENTRY indicates the block where to start.  Every block dominated by
1694       ENTRY will be rewritten.
1695
1696    WHAT indicates what actions will be taken by the renamer (see enum
1697       rewrite_mode).
1698
1699    BLOCKS are the set of interesting blocks for the dominator walker
1700       to process.  If this set is NULL, then all the nodes dominated
1701       by ENTRY are walked.  Otherwise, blocks dominated by ENTRY that
1702       are not present in BLOCKS are ignored.  */
1703
1704 static void
1705 rewrite_blocks (basic_block entry, enum rewrite_mode what, sbitmap blocks)
1706 {
1707   struct dom_walk_data walk_data;
1708   
1709   /* Rewrite all the basic blocks in the program.  */
1710   timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);
1711
1712   /* Setup callbacks for the generic dominator tree walker.  */
1713   memset (&walk_data, 0, sizeof (walk_data));
1714
1715   walk_data.dom_direction = CDI_DOMINATORS;
1716   walk_data.interesting_blocks = blocks;
1717
1718   if (what == REWRITE_UPDATE)
1719     walk_data.before_dom_children_before_stmts = rewrite_update_init_block;
1720   else
1721     walk_data.before_dom_children_before_stmts = rewrite_initialize_block;
1722
1723   if (what == REWRITE_ALL)
1724     walk_data.before_dom_children_walk_stmts = rewrite_stmt;
1725   else if (what == REWRITE_UPDATE)
1726     walk_data.before_dom_children_walk_stmts = rewrite_update_stmt;
1727   else
1728     gcc_unreachable ();
1729
1730   if (what == REWRITE_ALL)
1731     walk_data.before_dom_children_after_stmts = rewrite_add_phi_arguments;
1732   else if (what == REWRITE_UPDATE)
1733     walk_data.before_dom_children_after_stmts = rewrite_update_phi_arguments;
1734   else
1735     gcc_unreachable ();
1736   
1737   if (what == REWRITE_ALL)
1738     walk_data.after_dom_children_after_stmts =  rewrite_finalize_block;
1739   else if (what == REWRITE_UPDATE)
1740     walk_data.after_dom_children_after_stmts = rewrite_update_fini_block;
1741   else
1742     gcc_unreachable ();
1743
1744   block_defs_stack = VEC_alloc (tree, heap, 10);
1745
1746   /* Initialize the dominator walker.  */
1747   init_walk_dominator_tree (&walk_data);
1748
1749   /* Recursively walk the dominator tree rewriting each statement in
1750      each basic block.  */
1751   walk_dominator_tree (&walk_data, entry);
1752
1753   /* Finalize the dominator walker.  */
1754   fini_walk_dominator_tree (&walk_data);
1755
1756   /* Debugging dumps.  */
1757   if (dump_file && (dump_flags & TDF_STATS))
1758     {
1759       dump_dfa_stats (dump_file);
1760       if (def_blocks)
1761         dump_tree_ssa_stats (dump_file);
1762     }
1763
1764   if (def_blocks)
1765     {
1766       htab_delete (def_blocks);
1767       def_blocks = NULL;
1768     }
1769   
1770   VEC_free (tree, heap, block_defs_stack);
1771
1772   timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
1773 }
1774
1775
1776 /* Block initialization routine for mark_def_sites.  Clear the 
1777    KILLS bitmap at the start of each block.  */
1778
1779 static void
1780 mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
1781                                  basic_block bb ATTRIBUTE_UNUSED)
1782 {
1783   struct mark_def_sites_global_data *gd =
1784      (struct mark_def_sites_global_data *) walk_data->global_data;
1785   bitmap kills = gd->kills;
1786   bitmap_clear (kills);
1787 }
1788
1789
1790 /* Mark the definition site blocks for each variable, so that we know
1791    where the variable is actually live.
1792
1793    INTERESTING_BLOCKS will be filled in with all the blocks that
1794       should be processed by the renamer.  It is assumed to be
1795       initialized and zeroed by the caller.  */
1796
1797 static void
1798 mark_def_site_blocks (sbitmap interesting_blocks)
1799 {
1800   struct dom_walk_data walk_data;
1801   struct mark_def_sites_global_data mark_def_sites_global_data;
1802   referenced_var_iterator rvi;
1803   tree var;
1804
1805   /* Allocate memory for the DEF_BLOCKS hash table.  */
1806   def_blocks = htab_create (num_referenced_vars,
1807                             def_blocks_hash, def_blocks_eq, def_blocks_free);
1808   FOR_EACH_REFERENCED_VAR(var, rvi)
1809     set_current_def (var, NULL_TREE);
1810
1811   /* Setup callbacks for the generic dominator tree walker to find and
1812      mark definition sites.  */
1813   walk_data.walk_stmts_backward = false;
1814   walk_data.dom_direction = CDI_DOMINATORS;
1815   walk_data.initialize_block_local_data = NULL;
1816   walk_data.before_dom_children_before_stmts = mark_def_sites_initialize_block;
1817   walk_data.before_dom_children_walk_stmts = mark_def_sites;
1818   walk_data.before_dom_children_after_stmts = NULL; 
1819   walk_data.after_dom_children_before_stmts =  NULL;
1820   walk_data.after_dom_children_walk_stmts =  NULL;
1821   walk_data.after_dom_children_after_stmts =  NULL;
1822   walk_data.interesting_blocks = NULL;
1823
1824   /* Notice that this bitmap is indexed using variable UIDs, so it must be
1825      large enough to accommodate all the variables referenced in the
1826      function, not just the ones we are renaming.  */
1827   mark_def_sites_global_data.kills = BITMAP_ALLOC (NULL);
1828
1829   /* Create the set of interesting blocks that will be filled by
1830      mark_def_sites.  */
1831   mark_def_sites_global_data.interesting_blocks = interesting_blocks;
1832   walk_data.global_data = &mark_def_sites_global_data;
1833
1834   /* We do not have any local data.  */
1835   walk_data.block_local_data_size = 0;
1836
1837   /* Initialize the dominator walker.  */
1838   init_walk_dominator_tree (&walk_data);
1839
1840   /* Recursively walk the dominator tree.  */
1841   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1842
1843   /* Finalize the dominator walker.  */
1844   fini_walk_dominator_tree (&walk_data);
1845
1846   /* We no longer need this bitmap, clear and free it.  */
1847   BITMAP_FREE (mark_def_sites_global_data.kills);
1848 }
1849
1850
1851 /* Main entry point into the SSA builder.  The renaming process
1852    proceeds in four main phases:
1853
1854    1- Compute dominance frontier and immediate dominators, needed to
1855       insert PHI nodes and rename the function in dominator tree
1856       order.
1857
1858    2- Find and mark all the blocks that define variables
1859       (mark_def_site_blocks).
1860
1861    3- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
1862
1863    4- Rename all the blocks (rewrite_blocks) and statements in the program.
1864
1865    Steps 3 and 4 are done using the dominator tree walker
1866    (walk_dominator_tree).  */
1867
1868 static unsigned int
1869 rewrite_into_ssa (void)
1870 {
1871   bitmap *dfs;
1872   basic_block bb;
1873   sbitmap interesting_blocks;
1874   
1875   timevar_push (TV_TREE_SSA_OTHER);
1876
1877   /* Initialize operand data structures.  */
1878   init_ssa_operands ();
1879
1880   /* Initialize the set of interesting blocks.  The callback
1881      mark_def_sites will add to this set those blocks that the renamer
1882      should process.  */
1883   interesting_blocks = sbitmap_alloc (last_basic_block);
1884   sbitmap_zero (interesting_blocks);
1885
1886   /* Initialize dominance frontier.  */
1887   dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap));
1888   FOR_EACH_BB (bb)
1889     dfs[bb->index] = BITMAP_ALLOC (NULL);
1890
1891   /* 1- Compute dominance frontiers.  */
1892   calculate_dominance_info (CDI_DOMINATORS);
1893   compute_dominance_frontiers (dfs);
1894
1895   /* 2- Find and mark definition sites.  */
1896   mark_def_site_blocks (interesting_blocks);
1897
1898   /* 3- Insert PHI nodes at dominance frontiers of definition blocks.  */
1899   insert_phi_nodes (dfs);
1900
1901   /* 4- Rename all the blocks.  */
1902   rewrite_blocks (ENTRY_BLOCK_PTR, REWRITE_ALL, interesting_blocks);
1903
1904   /* Free allocated memory.  */
1905   FOR_EACH_BB (bb)
1906     BITMAP_FREE (dfs[bb->index]);
1907   free (dfs);
1908   sbitmap_free (interesting_blocks);
1909
1910   timevar_pop (TV_TREE_SSA_OTHER);
1911   in_ssa_p = true;
1912   return 0;
1913 }
1914
1915
1916 struct tree_opt_pass pass_build_ssa = 
1917 {
1918   "ssa",                                /* name */
1919   NULL,                                 /* gate */
1920   rewrite_into_ssa,                     /* execute */
1921   NULL,                                 /* sub */
1922   NULL,                                 /* next */
1923   0,                                    /* static_pass_number */
1924   0,                                    /* tv_id */
1925   PROP_cfg | PROP_referenced_vars,      /* properties_required */
1926   PROP_ssa,                             /* properties_provided */
1927   0,                                    /* properties_destroyed */
1928   0,                                    /* todo_flags_start */
1929   TODO_dump_func
1930     | TODO_verify_ssa
1931     | TODO_remove_unused_locals,        /* todo_flags_finish */
1932   0                                     /* letter */
1933 };
1934
1935
1936 /* Mark the definition of VAR at STMT and BB as interesting for the
1937    renamer.  BLOCKS is the set of blocks that need updating.  */
1938
1939 static void
1940 mark_def_interesting (tree var, tree stmt, basic_block bb, bool insert_phi_p)
1941 {
1942   gcc_assert (bitmap_bit_p (blocks_to_update, bb->index));
1943   REGISTER_DEFS_IN_THIS_STMT (stmt) = 1;
1944
1945   if (insert_phi_p)
1946     {
1947       bool is_phi_p = TREE_CODE (stmt) == PHI_NODE;
1948
1949       set_def_block (var, bb, is_phi_p);
1950
1951       /* If VAR is an SSA name in NEW_SSA_NAMES, this is a definition
1952          site for both itself and all the old names replaced by it.  */
1953       if (TREE_CODE (var) == SSA_NAME && is_new_name (var))
1954         {
1955           bitmap_iterator bi;
1956           unsigned i;
1957           bitmap set = names_replaced_by (var);
1958           if (set)
1959             EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
1960               set_def_block (ssa_name (i), bb, is_phi_p);
1961         }
1962     }
1963 }
1964
1965
1966 /* Mark the use of VAR at STMT and BB as interesting for the
1967    renamer.  INSERT_PHI_P is true if we are going to insert new PHI
1968    nodes.  */
1969
1970 static inline void
1971 mark_use_interesting (tree var, tree stmt, basic_block bb, bool insert_phi_p)
1972 {
1973   basic_block def_bb = bb_for_stmt (stmt);
1974
1975   mark_block_for_update (def_bb);
1976   mark_block_for_update (bb);
1977
1978   if (TREE_CODE (stmt) == PHI_NODE)
1979     mark_phi_for_rewrite (def_bb, stmt);
1980   else
1981     REWRITE_THIS_STMT (stmt) = 1;
1982
1983   /* If VAR has not been defined in BB, then it is live-on-entry
1984      to BB.  Note that we cannot just use the block holding VAR's
1985      definition because if VAR is one of the names in OLD_SSA_NAMES,
1986      it will have several definitions (itself and all the names that
1987      replace it).  */
1988   if (insert_phi_p)
1989     {
1990       struct def_blocks_d *db_p = get_def_blocks_for (var);
1991       if (!bitmap_bit_p (db_p->def_blocks, bb->index))
1992         set_livein_block (var, bb);
1993     }
1994 }
1995
1996
1997 /* Do a dominator walk starting at BB processing statements that
1998    reference symbols in SYMS_TO_RENAME.  This is very similar to
1999    mark_def_sites, but the scan handles statements whose operands may
2000    already be SSA names.
2001
2002    If INSERT_PHI_P is true, mark those uses as live in the
2003    corresponding block.  This is later used by the PHI placement
2004    algorithm to make PHI pruning decisions.  */
2005
2006 static void
2007 prepare_block_for_update (basic_block bb, bool insert_phi_p)
2008 {
2009   basic_block son;
2010   block_stmt_iterator si;
2011   tree phi;
2012
2013   mark_block_for_update (bb);
2014
2015   /* Process PHI nodes marking interesting those that define or use
2016      the symbols that we are interested in.  */
2017   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2018     {
2019       tree lhs_sym, lhs = PHI_RESULT (phi);
2020
2021       lhs_sym = DECL_P (lhs) ? lhs : SSA_NAME_VAR (lhs);
2022
2023       if (symbol_marked_for_renaming (lhs_sym))
2024         {
2025           mark_use_interesting (lhs_sym, phi, bb, insert_phi_p);
2026           mark_def_interesting (lhs_sym, phi, bb, insert_phi_p);
2027         }
2028     }
2029
2030   /* Process the statements.  */
2031   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2032     {
2033       tree stmt;
2034       ssa_op_iter i;
2035       use_operand_p use_p;
2036       def_operand_p def_p;
2037       
2038       stmt = bsi_stmt (si);
2039
2040       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_USE)
2041         {
2042           tree use = USE_FROM_PTR (use_p);
2043           tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
2044           if (symbol_marked_for_renaming (sym))
2045             mark_use_interesting (use, stmt, bb, insert_phi_p);
2046         }
2047
2048       FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, i, SSA_OP_DEF)
2049         {
2050           tree def = DEF_FROM_PTR (def_p);
2051           tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);
2052
2053           if (symbol_marked_for_renaming (sym))
2054             mark_def_interesting (def, stmt, bb, insert_phi_p);
2055         }
2056
2057       FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, i, SSA_OP_VIRTUAL_DEFS)
2058         {
2059           tree def = DEF_FROM_PTR (def_p);
2060           tree sym = DECL_P (def) ? def : SSA_NAME_VAR (def);
2061
2062           if (symbol_marked_for_renaming (sym))
2063             {
2064               mark_use_interesting (sym, stmt, bb, insert_phi_p);
2065               mark_def_interesting (sym, stmt, bb, insert_phi_p);
2066             }
2067         }
2068
2069       FOR_EACH_SSA_USE_OPERAND (use_p, stmt, i, SSA_OP_VUSE)
2070         {
2071           tree use = USE_FROM_PTR (use_p);
2072           tree sym = DECL_P (use) ? use : SSA_NAME_VAR (use);
2073
2074           if (symbol_marked_for_renaming (sym))
2075             mark_use_interesting (sym, stmt, bb, insert_phi_p);
2076         }
2077     }
2078
2079   /* Now visit all the blocks dominated by BB.  */
2080   for (son = first_dom_son (CDI_DOMINATORS, bb);
2081       son;
2082       son = next_dom_son (CDI_DOMINATORS, son))
2083     prepare_block_for_update (son, insert_phi_p);
2084 }
2085
2086
2087 /* Helper for prepare_names_to_update.  Mark all the use sites for
2088    NAME as interesting.  BLOCKS and INSERT_PHI_P are as in
2089    prepare_names_to_update.  */
2090
2091 static void
2092 prepare_use_sites_for (tree name, bool insert_phi_p)
2093 {
2094   use_operand_p use_p;
2095   imm_use_iterator iter;
2096
2097   FOR_EACH_IMM_USE_FAST (use_p, iter, name)
2098     {
2099       tree stmt = USE_STMT (use_p);
2100       basic_block bb = bb_for_stmt (stmt);
2101
2102       if (TREE_CODE (stmt) == PHI_NODE)
2103         {
2104           /* Mark this use of NAME interesting for the renamer.
2105              Notice that we explicitly call mark_use_interesting with
2106              INSERT_PHI_P == false.
2107
2108              This is to avoid marking NAME as live-in in this block
2109              BB. If we were to mark NAME live-in to BB, then NAME
2110              would be considered live-in through ALL incoming edges to
2111              BB which is not what we want.  Since we are updating the
2112              SSA form for NAME, we don't really know what other names
2113              of NAME are coming in through other edges into BB.
2114
2115              If we considered NAME live-in at BB, then the PHI
2116              placement algorithm may try to insert PHI nodes in blocks
2117              that are not only unnecessary but also the renamer would
2118              not know how to fill in.  */
2119           mark_use_interesting (name, stmt, bb, false);
2120
2121           /* As discussed above, we only want to mark NAME live-in
2122              through the edge corresponding to its slot inside the PHI
2123              argument list.  So, we look for the block BB1 where NAME
2124              is flowing through.  If BB1 does not contain a definition
2125              of NAME, then consider NAME live-in at BB1.  */
2126           if (insert_phi_p)
2127             {
2128               int ix = PHI_ARG_INDEX_FROM_USE (use_p);
2129               edge e = PHI_ARG_EDGE (stmt, ix);
2130               basic_block bb1 = e->src;
2131               struct def_blocks_d *db = get_def_blocks_for (name);
2132
2133               if (!bitmap_bit_p (db->def_blocks, bb1->index))
2134                 set_livein_block (name, bb1);
2135             }
2136         }
2137       else
2138         {
2139           /* For regular statements, mark this as an interesting use
2140              for NAME.  */
2141           mark_use_interesting (name, stmt, bb, insert_phi_p);
2142         }
2143     }
2144 }
2145
2146
2147 /* Helper for prepare_names_to_update.  Mark the definition site for
2148    NAME as interesting.  BLOCKS and INSERT_PHI_P are as in
2149    prepare_names_to_update.  */
2150
2151 static void
2152 prepare_def_site_for (tree name, bool insert_phi_p)
2153 {
2154   tree stmt;
2155   basic_block bb;
2156
2157   gcc_assert (names_to_release == NULL
2158               || !bitmap_bit_p (names_to_release, SSA_NAME_VERSION (name)));
2159
2160   stmt = SSA_NAME_DEF_STMT (name);
2161   bb = bb_for_stmt (stmt);
2162   if (bb)
2163     {
2164       gcc_assert (bb->index < last_basic_block);
2165       mark_block_for_update (bb);
2166       mark_def_interesting (name, stmt, bb, insert_phi_p);
2167     }
2168 }
2169
2170
2171 /* Mark definition and use sites of names in NEW_SSA_NAMES and
2172    OLD_SSA_NAMES.  INSERT_PHI_P is true if the caller wants to insert
2173    PHI nodes for newly created names.  */
2174
2175 static void
2176 prepare_names_to_update (bool insert_phi_p)
2177 {
2178   unsigned i = 0;
2179   bitmap_iterator bi;
2180   sbitmap_iterator sbi;
2181
2182   /* If a name N from NEW_SSA_NAMES is also marked to be released,
2183      remove it from NEW_SSA_NAMES so that we don't try to visit its
2184      defining basic block (which most likely doesn't exist).  Notice
2185      that we cannot do the same with names in OLD_SSA_NAMES because we
2186      want to replace existing instances.  */
2187   if (names_to_release)
2188     EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2189       RESET_BIT (new_ssa_names, i);
2190
2191   /* First process names in NEW_SSA_NAMES.  Otherwise, uses of old
2192      names may be considered to be live-in on blocks that contain
2193      definitions for their replacements.  */
2194   EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
2195     prepare_def_site_for (ssa_name (i), insert_phi_p);
2196
2197   /* If an old name is in NAMES_TO_RELEASE, we cannot remove it from
2198      OLD_SSA_NAMES, but we have to ignore its definition site.  */
2199   EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
2200     {
2201       if (names_to_release == NULL || !bitmap_bit_p (names_to_release, i))
2202         prepare_def_site_for (ssa_name (i), insert_phi_p);
2203       prepare_use_sites_for (ssa_name (i), insert_phi_p);
2204     }
2205 }
2206
2207
2208 /* Dump all the names replaced by NAME to FILE.  */
2209
2210 void
2211 dump_names_replaced_by (FILE *file, tree name)
2212 {
2213   unsigned i;
2214   bitmap old_set;
2215   bitmap_iterator bi;
2216
2217   print_generic_expr (file, name, 0);
2218   fprintf (file, " -> { ");
2219
2220   old_set = names_replaced_by (name);
2221   EXECUTE_IF_SET_IN_BITMAP (old_set, 0, i, bi)
2222     {
2223       print_generic_expr (file, ssa_name (i), 0);
2224       fprintf (file, " ");
2225     }
2226
2227   fprintf (file, "}\n");
2228 }
2229
2230
2231 /* Dump all the names replaced by NAME to stderr.  */
2232
2233 void
2234 debug_names_replaced_by (tree name)
2235 {
2236   dump_names_replaced_by (stderr, name);
2237 }
2238
2239
2240 /* Dump SSA update information to FILE.  */
2241
2242 void
2243 dump_update_ssa (FILE *file)
2244 {
2245   unsigned i = 0;
2246   bitmap_iterator bi;
2247
2248   if (!need_ssa_update_p ())
2249     return;
2250
2251   if (new_ssa_names && sbitmap_first_set_bit (new_ssa_names) >= 0)
2252     {
2253       sbitmap_iterator sbi;
2254
2255       fprintf (file, "\nSSA replacement table\n");
2256       fprintf (file, "N_i -> { O_1 ... O_j } means that N_i replaces "
2257                      "O_1, ..., O_j\n\n");
2258
2259       EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
2260         dump_names_replaced_by (file, ssa_name (i));
2261
2262       fprintf (file, "\n");
2263       fprintf (file, "Number of virtual NEW -> OLD mappings: %7u\n",
2264                update_ssa_stats.num_virtual_mappings);
2265       fprintf (file, "Number of real NEW -> OLD mappings:    %7u\n",
2266                update_ssa_stats.num_total_mappings
2267                - update_ssa_stats.num_virtual_mappings);
2268       fprintf (file, "Number of total NEW -> OLD mappings:   %7u\n",
2269                update_ssa_stats.num_total_mappings);
2270
2271       fprintf (file, "\nNumber of virtual symbols: %u\n",
2272                update_ssa_stats.num_virtual_symbols);
2273     }
2274
2275   if (syms_to_rename && !bitmap_empty_p (syms_to_rename))
2276     {
2277       fprintf (file, "\n\nSymbols to be put in SSA form\n\n");
2278       EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
2279         {
2280           print_generic_expr (file, referenced_var (i), 0);
2281           fprintf (file, " ");
2282         }
2283     }
2284
2285   if (names_to_release && !bitmap_empty_p (names_to_release))
2286     {
2287       fprintf (file, "\n\nSSA names to release after updating the SSA web\n\n");
2288       EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2289         {
2290           print_generic_expr (file, ssa_name (i), 0);
2291           fprintf (file, " ");
2292         }
2293     }
2294
2295   fprintf (file, "\n\n");
2296 }
2297
2298
2299 /* Dump SSA update information to stderr.  */
2300
2301 void
2302 debug_update_ssa (void)
2303 {
2304   dump_update_ssa (stderr);
2305 }
2306
2307
2308 /* Initialize data structures used for incremental SSA updates.  */
2309
2310 static void
2311 init_update_ssa (void)
2312 {
2313   /* Reserve more space than the current number of names.  The calls to
2314      add_new_name_mapping are typically done after creating new SSA
2315      names, so we'll need to reallocate these arrays.  */
2316   old_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
2317   sbitmap_zero (old_ssa_names);
2318
2319   new_ssa_names = sbitmap_alloc (num_ssa_names + NAME_SETS_GROWTH_FACTOR);
2320   sbitmap_zero (new_ssa_names);
2321
2322   repl_tbl = htab_create (20, repl_map_hash, repl_map_eq, repl_map_free);
2323   need_to_initialize_update_ssa_p = false;
2324   need_to_update_vops_p = false;
2325   syms_to_rename = BITMAP_ALLOC (NULL);
2326   names_to_release = NULL;
2327   memset (&update_ssa_stats, 0, sizeof (update_ssa_stats));
2328   update_ssa_stats.virtual_symbols = BITMAP_ALLOC (NULL);
2329 }
2330
2331
2332 /* Deallocate data structures used for incremental SSA updates.  */
2333
2334 void
2335 delete_update_ssa (void)
2336 {
2337   unsigned i;
2338   bitmap_iterator bi;
2339
2340   sbitmap_free (old_ssa_names);
2341   old_ssa_names = NULL;
2342
2343   sbitmap_free (new_ssa_names);
2344   new_ssa_names = NULL;
2345
2346   htab_delete (repl_tbl);
2347   repl_tbl = NULL;
2348
2349   need_to_initialize_update_ssa_p = true;
2350   need_to_update_vops_p = false;
2351   BITMAP_FREE (syms_to_rename);
2352   BITMAP_FREE (update_ssa_stats.virtual_symbols);
2353
2354   if (names_to_release)
2355     {
2356       EXECUTE_IF_SET_IN_BITMAP (names_to_release, 0, i, bi)
2357         release_ssa_name (ssa_name (i));
2358       BITMAP_FREE (names_to_release);
2359     }
2360
2361   clear_ssa_name_info ();
2362 }
2363
2364
2365 /* Create a new name for OLD_NAME in statement STMT and replace the
2366    operand pointed to by DEF_P with the newly created name.  Return
2367    the new name and register the replacement mapping <NEW, OLD> in
2368    update_ssa's tables.  */
2369
2370 tree
2371 create_new_def_for (tree old_name, tree stmt, def_operand_p def)
2372 {
2373   tree new_name = duplicate_ssa_name (old_name, stmt);
2374
2375   SET_DEF (def, new_name);
2376
2377   if (TREE_CODE (stmt) == PHI_NODE)
2378     {
2379       edge e;
2380       edge_iterator ei;
2381       basic_block bb = bb_for_stmt (stmt);
2382
2383       /* If needed, mark NEW_NAME as occurring in an abnormal PHI node. */
2384       FOR_EACH_EDGE (e, ei, bb->preds)
2385         if (e->flags & EDGE_ABNORMAL)
2386           {
2387             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_name) = 1;
2388             break;
2389           }
2390     }
2391
2392   register_new_name_mapping (new_name, old_name);
2393
2394   /* For the benefit of passes that will be updating the SSA form on
2395      their own, set the current reaching definition of OLD_NAME to be
2396      NEW_NAME.  */
2397   set_current_def (old_name, new_name);
2398
2399   return new_name;
2400 }
2401
2402
2403 /* Register name NEW to be a replacement for name OLD.  This function
2404    must be called for every replacement that should be performed by
2405    update_ssa.  */
2406
2407 void
2408 register_new_name_mapping (tree new, tree old)
2409 {
2410   if (need_to_initialize_update_ssa_p)
2411     init_update_ssa ();
2412
2413   add_new_name_mapping (new, old);
2414 }
2415
2416
2417 /* Register symbol SYM to be renamed by update_ssa.  */
2418
2419 void
2420 mark_sym_for_renaming (tree sym)
2421 {
2422   if (need_to_initialize_update_ssa_p)
2423     init_update_ssa ();
2424
2425   bitmap_set_bit (syms_to_rename, DECL_UID (sym));
2426
2427   if (!is_gimple_reg (sym))
2428     need_to_update_vops_p = true;
2429 }
2430
2431
2432 /* Register all the symbols in SET to be renamed by update_ssa.  */
2433
2434 void
2435 mark_set_for_renaming (bitmap set)
2436 {
2437   bitmap_iterator bi;
2438   unsigned i;
2439
2440   if (bitmap_empty_p (set))
2441     return;
2442
2443   if (need_to_initialize_update_ssa_p)
2444     init_update_ssa ();
2445
2446   bitmap_ior_into (syms_to_rename, set);
2447
2448   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
2449     if (!is_gimple_reg (referenced_var (i)))
2450       {
2451         need_to_update_vops_p = true;
2452         break;
2453       }
2454 }
2455
2456
2457 /* Return true if there is any work to be done by update_ssa.  */
2458
2459 bool
2460 need_ssa_update_p (void)
2461 {
2462   return syms_to_rename || old_ssa_names || new_ssa_names;
2463 }
2464
2465
2466 /* Return true if name N has been registered in the replacement table.  */
2467
2468 bool
2469 name_registered_for_update_p (tree n)
2470 {
2471   if (!need_ssa_update_p ())
2472     return false;
2473
2474   return is_new_name (n)
2475          || is_old_name (n)
2476          || symbol_marked_for_renaming (SSA_NAME_VAR (n));
2477 }
2478
2479
2480 /* Return the set of all the SSA names marked to be replaced.  */
2481
2482 bitmap
2483 ssa_names_to_replace (void)
2484 {
2485   unsigned i = 0;
2486   bitmap ret;
2487   sbitmap_iterator sbi;
2488   
2489   ret = BITMAP_ALLOC (NULL);
2490   EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
2491     bitmap_set_bit (ret, i);
2492
2493   return ret;
2494 }
2495
2496
2497 /* Mark NAME to be released after update_ssa has finished.  */
2498
2499 void
2500 release_ssa_name_after_update_ssa (tree name)
2501 {
2502   gcc_assert (!need_to_initialize_update_ssa_p);
2503
2504   if (names_to_release == NULL)
2505     names_to_release = BITMAP_ALLOC (NULL);
2506
2507   bitmap_set_bit (names_to_release, SSA_NAME_VERSION (name));
2508 }
2509
2510
2511 /* Insert new PHI nodes to replace VAR.  DFS contains dominance
2512    frontier information.  BLOCKS is the set of blocks to be updated.
2513
2514    This is slightly different than the regular PHI insertion
2515    algorithm.  The value of UPDATE_FLAGS controls how PHI nodes for
2516    real names (i.e., GIMPLE registers) are inserted:
2517  
2518    - If UPDATE_FLAGS == TODO_update_ssa, we are only interested in PHI
2519      nodes inside the region affected by the block that defines VAR
2520      and the blocks that define all its replacements.  All these
2521      definition blocks are stored in DEF_BLOCKS[VAR]->DEF_BLOCKS.
2522
2523      First, we compute the entry point to the region (ENTRY).  This is
2524      given by the nearest common dominator to all the definition
2525      blocks. When computing the iterated dominance frontier (IDF), any
2526      block not strictly dominated by ENTRY is ignored.
2527
2528      We then call the standard PHI insertion algorithm with the pruned
2529      IDF.
2530
2531    - If UPDATE_FLAGS == TODO_update_ssa_full_phi, the IDF for real
2532      names is not pruned.  PHI nodes are inserted at every IDF block.  */
2533
2534 static void
2535 insert_updated_phi_nodes_for (tree var, bitmap *dfs, bitmap blocks,
2536                               unsigned update_flags)
2537 {
2538   basic_block entry;
2539   struct def_blocks_d *db;
2540   bitmap idf, pruned_idf;
2541   bitmap_iterator bi;
2542   unsigned i;
2543
2544 #if defined ENABLE_CHECKING
2545   if (TREE_CODE (var) == SSA_NAME)
2546     gcc_assert (is_old_name (var));
2547   else
2548     gcc_assert (symbol_marked_for_renaming (var));
2549 #endif
2550
2551   /* Get all the definition sites for VAR.  */
2552   db = find_def_blocks_for (var);
2553
2554   /* No need to do anything if there were no definitions to VAR.  */
2555   if (db == NULL || bitmap_empty_p (db->def_blocks))
2556     return;
2557
2558   /* Compute the initial iterated dominance frontier.  */
2559   idf = find_idf (db->def_blocks, dfs);
2560   pruned_idf = BITMAP_ALLOC (NULL);
2561
2562   if (TREE_CODE (var) == SSA_NAME)
2563     {
2564       if (update_flags == TODO_update_ssa)
2565         {
2566           /* If doing regular SSA updates for GIMPLE registers, we are
2567              only interested in IDF blocks dominated by the nearest
2568              common dominator of all the definition blocks.  */
2569           entry = nearest_common_dominator_for_set (CDI_DOMINATORS,
2570                                                     db->def_blocks);
2571
2572           if (entry != ENTRY_BLOCK_PTR)
2573             EXECUTE_IF_SET_IN_BITMAP (idf, 0, i, bi)
2574               if (BASIC_BLOCK (i) != entry
2575                   && dominated_by_p (CDI_DOMINATORS, BASIC_BLOCK (i), entry))
2576                 bitmap_set_bit (pruned_idf, i);
2577         }
2578       else
2579         {
2580           /* Otherwise, do not prune the IDF for VAR.  */
2581           gcc_assert (update_flags == TODO_update_ssa_full_phi);
2582           bitmap_copy (pruned_idf, idf);
2583         }
2584     }
2585   else
2586     {
2587       /* Otherwise, VAR is a symbol that needs to be put into SSA form
2588          for the first time, so we need to compute the full IDF for
2589          it.  */
2590       bitmap_copy (pruned_idf, idf);
2591     }
2592
2593   if (!bitmap_empty_p (pruned_idf))
2594     {
2595       /* Make sure that PRUNED_IDF blocks and all their feeding blocks
2596          are included in the region to be updated.  The feeding blocks
2597          are important to guarantee that the PHI arguments are renamed
2598          properly.  */
2599       bitmap_ior_into (blocks, pruned_idf);
2600       EXECUTE_IF_SET_IN_BITMAP (pruned_idf, 0, i, bi)
2601         {
2602           edge e;
2603           edge_iterator ei;
2604           basic_block bb = BASIC_BLOCK (i);
2605
2606           FOR_EACH_EDGE (e, ei, bb->preds)
2607             if (e->src->index >= 0)
2608               bitmap_set_bit (blocks, e->src->index);
2609         }
2610
2611       insert_phi_nodes_for (var, pruned_idf, true);
2612     }
2613
2614   BITMAP_FREE (pruned_idf);
2615   BITMAP_FREE (idf);
2616 }
2617
2618
2619 /* Heuristic to determine whether SSA name mappings for virtual names
2620    should be discarded and their symbols rewritten from scratch.  When
2621    there is a large number of mappings for virtual names, the
2622    insertion of PHI nodes for the old names in the mappings takes
2623    considerable more time than if we inserted PHI nodes for the
2624    symbols instead.
2625
2626    Currently the heuristic takes these stats into account:
2627
2628         - Number of mappings for virtual SSA names.
2629         - Number of distinct virtual symbols involved in those mappings.
2630
2631    If the number of virtual mappings is much larger than the number of
2632    virtual symbols, then it will be faster to compute PHI insertion
2633    spots for the symbols.  Even if this involves traversing the whole
2634    CFG, which is what happens when symbols are renamed from scratch.  */
2635
2636 static bool
2637 switch_virtuals_to_full_rewrite_p (void)
2638 {
2639   if (update_ssa_stats.num_virtual_mappings < (unsigned) MIN_VIRTUAL_MAPPINGS)
2640     return false;
2641
2642   if (update_ssa_stats.num_virtual_mappings
2643       > (unsigned) VIRTUAL_MAPPINGS_TO_SYMS_RATIO
2644         * update_ssa_stats.num_virtual_symbols)
2645     return true;
2646
2647   return false;
2648 }
2649
2650
2651 /* Remove every virtual mapping and mark all the affected virtual
2652    symbols for renaming.  */
2653
2654 static void
2655 switch_virtuals_to_full_rewrite (void)
2656 {
2657   unsigned i = 0;
2658   sbitmap_iterator sbi;
2659
2660   if (dump_file)
2661     {
2662       fprintf (dump_file, "\nEnabled virtual name mapping heuristic.\n");
2663       fprintf (dump_file, "\tNumber of virtual mappings:       %7u\n",
2664                update_ssa_stats.num_virtual_mappings);
2665       fprintf (dump_file, "\tNumber of unique virtual symbols: %7u\n",
2666                update_ssa_stats.num_virtual_symbols);
2667       fprintf (dump_file, "Updating FUD-chains from top of CFG will be "
2668                           "faster than processing\nthe name mappings.\n\n");
2669     }
2670
2671   /* Remove all virtual names from NEW_SSA_NAMES and OLD_SSA_NAMES.
2672      Note that it is not really necessary to remove the mappings from
2673      REPL_TBL, that would only waste time.  */
2674   EXECUTE_IF_SET_IN_SBITMAP (new_ssa_names, 0, i, sbi)
2675     if (!is_gimple_reg (ssa_name (i)))
2676       RESET_BIT (new_ssa_names, i);
2677
2678   EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
2679     if (!is_gimple_reg (ssa_name (i)))
2680       RESET_BIT (old_ssa_names, i);
2681
2682   bitmap_ior_into (syms_to_rename, update_ssa_stats.virtual_symbols);
2683 }
2684
2685
2686 /* Given a set of newly created SSA names (NEW_SSA_NAMES) and a set of
2687    existing SSA names (OLD_SSA_NAMES), update the SSA form so that:
2688
2689    1- The names in OLD_SSA_NAMES dominated by the definitions of
2690       NEW_SSA_NAMES are all re-written to be reached by the
2691       appropriate definition from NEW_SSA_NAMES.
2692
2693    2- If needed, new PHI nodes are added to the iterated dominance
2694       frontier of the blocks where each of NEW_SSA_NAMES are defined.
2695
2696    The mapping between OLD_SSA_NAMES and NEW_SSA_NAMES is setup by
2697    calling register_new_name_mapping for every pair of names that the
2698    caller wants to replace.
2699
2700    The caller identifies the new names that have been inserted and the
2701    names that need to be replaced by calling register_new_name_mapping
2702    for every pair <NEW, OLD>.  Note that the function assumes that the
2703    new names have already been inserted in the IL.
2704
2705    For instance, given the following code:
2706
2707      1  L0:
2708      2  x_1 = PHI (0, x_5)
2709      3  if (x_1 < 10)
2710      4    if (x_1 > 7)
2711      5      y_2 = 0
2712      6    else
2713      7      y_3 = x_1 + x_7
2714      8    endif
2715      9    x_5 = x_1 + 1
2716      10   goto L0;
2717      11 endif
2718
2719    Suppose that we insert new names x_10 and x_11 (lines 4 and 8).
2720
2721      1  L0:
2722      2  x_1 = PHI (0, x_5)
2723      3  if (x_1 < 10)
2724      4    x_10 = ...
2725      5    if (x_1 > 7)
2726      6      y_2 = 0
2727      7    else
2728      8      x_11 = ...
2729      9      y_3 = x_1 + x_7
2730      10   endif
2731      11   x_5 = x_1 + 1
2732      12   goto L0;
2733      13 endif
2734
2735    We want to replace all the uses of x_1 with the new definitions of
2736    x_10 and x_11.  Note that the only uses that should be replaced are
2737    those at lines 5, 9 and 11.  Also, the use of x_7 at line 9 should
2738    *not* be replaced (this is why we cannot just mark symbol 'x' for
2739    renaming).
2740
2741    Additionally, we may need to insert a PHI node at line 11 because
2742    that is a merge point for x_10 and x_11.  So the use of x_1 at line
2743    11 will be replaced with the new PHI node.  The insertion of PHI
2744    nodes is optional.  They are not strictly necessary to preserve the
2745    SSA form, and depending on what the caller inserted, they may not
2746    even be useful for the optimizers.  UPDATE_FLAGS controls various
2747    aspects of how update_ssa operates, see the documentation for
2748    TODO_update_ssa*.  */
2749
2750 void
2751 update_ssa (unsigned update_flags)
2752 {
2753   basic_block bb, start_bb;
2754   bitmap_iterator bi;
2755   unsigned i = 0;
2756   sbitmap tmp;
2757   bool insert_phi_p;
2758   sbitmap_iterator sbi;
2759
2760   if (!need_ssa_update_p ())
2761     return;
2762
2763   timevar_push (TV_TREE_SSA_INCREMENTAL);
2764
2765   blocks_with_phis_to_rewrite = BITMAP_ALLOC (NULL);
2766   if (!phis_to_rewrite)
2767     phis_to_rewrite = VEC_alloc (tree_vec, heap, last_basic_block);
2768   blocks_to_update = BITMAP_ALLOC (NULL);
2769
2770   /* Ensure that the dominance information is up-to-date.  */
2771   calculate_dominance_info (CDI_DOMINATORS);
2772
2773   /* Only one update flag should be set.  */
2774   gcc_assert (update_flags == TODO_update_ssa
2775               || update_flags == TODO_update_ssa_no_phi
2776               || update_flags == TODO_update_ssa_full_phi
2777               || update_flags == TODO_update_ssa_only_virtuals);
2778
2779   /* If we only need to update virtuals, remove all the mappings for
2780      real names before proceeding.  The caller is responsible for
2781      having dealt with the name mappings before calling update_ssa.  */
2782   if (update_flags == TODO_update_ssa_only_virtuals)
2783     {
2784       sbitmap_zero (old_ssa_names);
2785       sbitmap_zero (new_ssa_names);
2786       htab_empty (repl_tbl);
2787     }
2788
2789   insert_phi_p = (update_flags != TODO_update_ssa_no_phi);
2790
2791   if (insert_phi_p)
2792     {
2793       /* If the caller requested PHI nodes to be added, initialize
2794          live-in information data structures (DEF_BLOCKS).  */
2795
2796       /* For each SSA name N, the DEF_BLOCKS table describes where the
2797          name is defined, which blocks have PHI nodes for N, and which
2798          blocks have uses of N (i.e., N is live-on-entry in those
2799          blocks).  */
2800       def_blocks = htab_create (num_ssa_names, def_blocks_hash,
2801                                 def_blocks_eq, def_blocks_free);
2802     }
2803   else
2804     {
2805       def_blocks = NULL;
2806     }
2807
2808   /* Heuristic to avoid massive slow downs when the replacement
2809      mappings include lots of virtual names.  */
2810   if (insert_phi_p && switch_virtuals_to_full_rewrite_p ())
2811     switch_virtuals_to_full_rewrite ();
2812
2813   /* If there are names defined in the replacement table, prepare
2814      definition and use sites for all the names in NEW_SSA_NAMES and
2815      OLD_SSA_NAMES.  */
2816   if (sbitmap_first_set_bit (new_ssa_names) >= 0)
2817     {
2818       prepare_names_to_update (insert_phi_p);
2819
2820       /* If all the names in NEW_SSA_NAMES had been marked for
2821          removal, and there are no symbols to rename, then there's
2822          nothing else to do.  */
2823       if (sbitmap_first_set_bit (new_ssa_names) < 0
2824           && bitmap_empty_p (syms_to_rename))
2825         goto done;
2826     }
2827
2828   /* Next, determine the block at which to start the renaming process.  */
2829   if (!bitmap_empty_p (syms_to_rename))
2830     {
2831       /* If we have to rename some symbols from scratch, we need to
2832          start the process at the root of the CFG.  FIXME, it should
2833          be possible to determine the nearest block that had a
2834          definition for each of the symbols that are marked for
2835          updating.  For now this seems more work than it's worth.  */
2836       start_bb = ENTRY_BLOCK_PTR;
2837
2838       /* Traverse the CFG looking for definitions and uses of symbols
2839          in SYMS_TO_RENAME.  Mark interesting blocks and statements
2840          and set local live-in information for the PHI placement
2841          heuristics.  */
2842       prepare_block_for_update (start_bb, insert_phi_p);
2843     }
2844   else
2845     {
2846       /* Otherwise, the entry block to the region is the nearest
2847          common dominator for the blocks in BLOCKS.  */
2848       start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS,
2849                                                    blocks_to_update);
2850     }
2851
2852   /* If requested, insert PHI nodes at the iterated dominance frontier
2853      of every block, creating new definitions for names in OLD_SSA_NAMES
2854      and for symbols in SYMS_TO_RENAME.  */
2855   if (insert_phi_p)
2856     {
2857       bitmap *dfs;
2858
2859       /* If the caller requested PHI nodes to be added, compute
2860          dominance frontiers.  */
2861       dfs = XNEWVEC (bitmap, last_basic_block);
2862       FOR_EACH_BB (bb)
2863         dfs[bb->index] = BITMAP_ALLOC (NULL);
2864       compute_dominance_frontiers (dfs);
2865
2866       if (sbitmap_first_set_bit (old_ssa_names) >= 0)
2867         {
2868           sbitmap_iterator sbi;
2869
2870           /* insert_update_phi_nodes_for will call add_new_name_mapping
2871              when inserting new PHI nodes, so the set OLD_SSA_NAMES
2872              will grow while we are traversing it (but it will not
2873              gain any new members).  Copy OLD_SSA_NAMES to a temporary
2874              for traversal.  */
2875           sbitmap tmp = sbitmap_alloc (old_ssa_names->n_bits);
2876           sbitmap_copy (tmp, old_ssa_names);
2877           EXECUTE_IF_SET_IN_SBITMAP (tmp, 0, i, sbi)
2878             insert_updated_phi_nodes_for (ssa_name (i), dfs, blocks_to_update,
2879                                           update_flags);
2880           sbitmap_free (tmp);
2881         }
2882
2883       EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
2884         insert_updated_phi_nodes_for (referenced_var (i), dfs,
2885                                       blocks_to_update, update_flags);
2886
2887       FOR_EACH_BB (bb)
2888         BITMAP_FREE (dfs[bb->index]);
2889       free (dfs);
2890
2891       /* Insertion of PHI nodes may have added blocks to the region.
2892          We need to re-compute START_BB to include the newly added
2893          blocks.  */
2894       if (start_bb != ENTRY_BLOCK_PTR)
2895         start_bb = nearest_common_dominator_for_set (CDI_DOMINATORS,
2896                                                      blocks_to_update);
2897     }
2898
2899   /* Reset the current definition for name and symbol before renaming
2900      the sub-graph.  */
2901   EXECUTE_IF_SET_IN_SBITMAP (old_ssa_names, 0, i, sbi)
2902     set_current_def (ssa_name (i), NULL_TREE);
2903
2904   EXECUTE_IF_SET_IN_BITMAP (syms_to_rename, 0, i, bi)
2905     set_current_def (referenced_var (i), NULL_TREE);
2906
2907   /* Now start the renaming process at START_BB.  */
2908   tmp = sbitmap_alloc (last_basic_block);
2909   sbitmap_zero (tmp);
2910   EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
2911     SET_BIT (tmp, i);
2912
2913   rewrite_blocks (start_bb, REWRITE_UPDATE, tmp);
2914
2915   sbitmap_free (tmp);
2916
2917   /* Debugging dumps.  */
2918   if (dump_file)
2919     {
2920       int c;
2921       unsigned i;
2922
2923       dump_update_ssa (dump_file);
2924
2925       fprintf (dump_file, "Incremental SSA update started at block: %d\n\n",
2926                start_bb->index);
2927
2928       c = 0;
2929       EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
2930         c++;
2931       fprintf (dump_file, "Number of blocks in CFG: %d\n", last_basic_block);
2932       fprintf (dump_file, "Number of blocks to update: %d (%3.0f%%)\n\n",
2933                c, PERCENT (c, last_basic_block));
2934
2935       if (dump_flags & TDF_DETAILS)
2936         {
2937           fprintf (dump_file, "Affected blocks: ");
2938           EXECUTE_IF_SET_IN_BITMAP (blocks_to_update, 0, i, bi)
2939             fprintf (dump_file, "%u ", i);
2940           fprintf (dump_file, "\n");
2941         }
2942
2943       fprintf (dump_file, "\n\n");
2944     }
2945
2946   /* Free allocated memory.  */
2947 done:
2948   EXECUTE_IF_SET_IN_BITMAP (blocks_with_phis_to_rewrite, 0, i, bi)
2949     {
2950       tree_vec phis = VEC_index (tree_vec, phis_to_rewrite, i);
2951
2952       VEC_free (tree, heap, phis);
2953       VEC_replace (tree_vec, phis_to_rewrite, i, NULL);
2954     }
2955   BITMAP_FREE (blocks_with_phis_to_rewrite);
2956   BITMAP_FREE (blocks_to_update);
2957   delete_update_ssa ();
2958
2959   timevar_pop (TV_TREE_SSA_INCREMENTAL);
2960 }