OSDN Git Service

* README.SCO: Update per FSF instructions.
[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 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, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "langhooks.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "errors.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "bitmap.h"
39 #include "tree-flow.h"
40 #include "tree-gimple.h"
41 #include "tree-inline.h"
42 #include "varray.h"
43 #include "timevar.h"
44 #include "hashtab.h"
45 #include "tree-dump.h"
46 #include "tree-pass.h"
47 #include "cfgloop.h"
48 #include "domwalk.h"
49 #include "ggc.h"
50
51 /* This file builds the SSA form for a function as described in:
52    R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and K. Zadeck. Efficiently
53    Computing Static Single Assignment Form and the Control Dependence
54    Graph. ACM Transactions on Programming Languages and Systems,
55    13(4):451-490, October 1991.  */
56
57
58 /* Structure to map a variable VAR to the set of blocks that contain
59    definitions for VAR.  */
60 struct def_blocks_d
61 {
62   /* The variable.  */
63   tree var;
64
65   /* Blocks that contain definitions of VAR.  Bit I will be set if the
66      Ith block contains a definition of VAR.  */
67   bitmap def_blocks;
68
69   /* Blocks that contain a phi node for VAR.  */
70   bitmap phi_blocks;
71
72   /* Blocks where VAR is live-on-entry.  Similar semantics as
73      DEF_BLOCKS.  */
74   bitmap livein_blocks;
75 };
76
77 /* Each entry in DEF_BLOCKS contains an element of type STRUCT
78    DEF_BLOCKS_D, mapping a variable VAR to a bitmap describing all the
79    basic blocks where VAR is defined (assigned a new value).  It also
80    contains a bitmap of all the blocks where VAR is live-on-entry
81    (i.e., there is a use of VAR in block B without a preceding
82    definition in B).  The live-on-entry information is used when
83    computing PHI pruning heuristics.  */
84 static htab_t def_blocks;
85
86 /* Stack of trees used to restore the global currdefs to its original
87    state after completing rewriting of a block and its dominator children.
88
89    This varray is used in two contexts.  The first is rewriting of _DECL
90    nodes into SSA_NAMEs.  In that context it's elements have the
91    following properties:
92
93      An SSA_NAME indicates that the current definition of the underlying
94      variable should be set to the given SSA_NAME.
95                                                                                 
96      A _DECL node indicates that the underlying variable has no current
97      definition.
98                                                                                 
99      A NULL node is used to mark the last node associated with the
100      current block. 
101
102
103    This varray is also used when rewriting an SSA_NAME which has multiple
104    definition sites into multiple SSA_NAMEs.  In that context entries come
105    in pairs.
106
107      The top entry is an SSA_NAME and the top-1 entry is the
108      current value for that SSA_NAME. 
109
110      A NULL node at the top entry is used to mark the last node associated
111      with the current block.  */
112 static varray_type block_defs_stack;
113
114 /* Global data to attach to the main dominator walk structure.  */
115 struct mark_def_sites_global_data
116 {
117   /* This sbitmap contains the variables which are set before they
118      are used in a basic block.  We keep it as a global variable
119      solely to avoid the overhead of allocating and deallocating
120      the bitmap.  */
121   sbitmap kills;
122
123   /* Bitmap of names to rename.  */
124   sbitmap names_to_rename;
125 };
126
127 /* Information stored for ssa names.  */
128
129 struct ssa_name_info
130 {
131   /* This field indicates whether or not the variable may need PHI nodes.
132      See the enum's definition for more detailed information about the
133      states.  */
134   ENUM_BITFIELD (need_phi_state) need_phi_state : 2;
135
136   /* The actual definition of the ssa name.  */
137   tree current_def;
138 };
139
140 /* Local functions.  */
141 static void rewrite_finalize_block (struct dom_walk_data *, basic_block);
142 static void rewrite_initialize_block (struct dom_walk_data *, basic_block);
143 static void rewrite_add_phi_arguments (struct dom_walk_data *, basic_block);
144 static void mark_def_sites (struct dom_walk_data *walk_data,
145                             basic_block bb, block_stmt_iterator);
146 static void mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
147                                              basic_block bb);
148 static void set_def_block (tree, basic_block, bool, bool);
149 static void set_livein_block (tree, basic_block);
150 static bool prepare_use_operand_for_rename (use_operand_p, size_t *uid_p);
151 static bool prepare_def_operand_for_rename (tree def, size_t *uid_p);
152 static void insert_phi_nodes (bitmap *, bitmap);
153 static void rewrite_stmt (struct dom_walk_data *, basic_block,
154                           block_stmt_iterator);
155 static inline void rewrite_operand (use_operand_p);
156 static void insert_phi_nodes_for (tree, bitmap *, varray_type *);
157 static tree get_reaching_def (tree);
158 static hashval_t def_blocks_hash (const void *);
159 static int def_blocks_eq (const void *, const void *);
160 static void def_blocks_free (void *);
161 static int debug_def_blocks_r (void **, void *);
162 static inline struct def_blocks_d *get_def_blocks_for (tree);
163 static inline struct def_blocks_d *find_def_blocks_for (tree);
164 static void htab_statistics (FILE *, htab_t);
165
166 /* Get the information associated with NAME.  */
167
168 static inline struct ssa_name_info *
169 get_ssa_name_ann (tree name)
170 {
171   if (!SSA_NAME_AUX (name))
172     SSA_NAME_AUX (name) = xcalloc (1, sizeof (struct ssa_name_info));
173
174   return SSA_NAME_AUX (name);
175 }
176
177 /* Gets phi_state field for VAR.  */
178
179 static inline enum need_phi_state
180 get_phi_state (tree var)
181 {
182   if (TREE_CODE (var) == SSA_NAME)
183     return get_ssa_name_ann (var)->need_phi_state;
184   else
185     return var_ann (var)->need_phi_state;
186 }
187
188 /* Sets phi_state field for VAR to STATE.  */
189
190 static inline void
191 set_phi_state (tree var, enum need_phi_state state)
192 {
193   if (TREE_CODE (var) == SSA_NAME)
194     get_ssa_name_ann (var)->need_phi_state = state;
195   else
196     var_ann (var)->need_phi_state = state;
197 }
198
199 /* Return the current definition for VAR.  */
200
201 static inline tree
202 get_current_def (tree var)
203 {
204   if (TREE_CODE (var) == SSA_NAME)
205     return get_ssa_name_ann (var)->current_def;
206   else
207     return var_ann (var)->current_def;
208 }
209
210 /* Sets current definition of VAR to DEF.  */
211
212 static inline void
213 set_current_def (tree var, tree def)
214 {
215   if (TREE_CODE (var) == SSA_NAME)
216     get_ssa_name_ann (var)->current_def = def;
217   else
218     var_ann (var)->current_def = def;
219 }
220
221 /* Compute global livein information given the set of blockx where
222    an object is locally live at the start of the block (LIVEIN)
223    and the set of blocks where the object is defined (DEF_BLOCKS).
224
225    Note: This routine augments the existing local livein information
226    to include global livein (i.e., it modifies the underlying bitmap
227    for LIVEIN).  */
228
229 void
230 compute_global_livein (bitmap livein, bitmap def_blocks)
231 {
232   basic_block bb, *worklist, *tos;
233   int i;
234   bitmap_iterator bi;
235
236   tos = worklist
237     = (basic_block *) xmalloc (sizeof (basic_block) * (n_basic_blocks + 1));
238
239   EXECUTE_IF_SET_IN_BITMAP (livein, 0, i, bi)
240     {
241       *tos++ = BASIC_BLOCK (i);
242     }
243
244   /* Iterate until the worklist is empty.  */
245   while (tos != worklist)
246     {
247       edge e;
248       edge_iterator ei;
249
250       /* Pull a block off the worklist.  */
251       bb = *--tos;
252
253       /* For each predecessor block.  */
254       FOR_EACH_EDGE (e, ei, bb->preds)
255         {
256           basic_block pred = e->src;
257           int pred_index = pred->index;
258
259           /* None of this is necessary for the entry block.  */
260           if (pred != ENTRY_BLOCK_PTR
261               && ! bitmap_bit_p (livein, pred_index)
262               && ! bitmap_bit_p (def_blocks, pred_index))
263             {
264               *tos++ = pred;
265               bitmap_set_bit (livein, pred_index);
266             }
267         }
268     }
269
270   free (worklist);
271 }
272
273
274 /* Block initialization routine for mark_def_sites.  Clear the 
275    KILLS bitmap at the start of each block.  */
276
277 static void
278 mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
279                                  basic_block bb ATTRIBUTE_UNUSED)
280 {
281   struct mark_def_sites_global_data *gd = walk_data->global_data;
282   sbitmap kills = gd->kills;
283
284   sbitmap_zero (kills);
285 }
286
287 /* Block initialization routine for mark_def_sites.  Clear the 
288    KILLS bitmap at the start of each block.  */
289
290 static void
291 ssa_mark_def_sites_initialize_block (struct dom_walk_data *walk_data,
292                                      basic_block bb)
293 {
294   struct mark_def_sites_global_data *gd = walk_data->global_data;
295   sbitmap kills = gd->kills;
296   tree phi, def;
297   unsigned def_uid;
298
299   sbitmap_zero (kills);
300
301   for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
302     {
303       def = PHI_RESULT (phi);
304       def_uid = SSA_NAME_VERSION (def);
305
306       if (!TEST_BIT (gd->names_to_rename, def_uid))
307         continue;
308
309       set_def_block (def, bb, true, true);
310       SET_BIT (kills, def_uid);
311     }
312 }
313
314 /* Marks ssa names used as arguments of phis at the end of BB.  */
315
316 static void
317 ssa_mark_phi_uses (struct dom_walk_data *walk_data, basic_block bb)
318 {
319   struct mark_def_sites_global_data *gd = walk_data->global_data;
320   sbitmap kills = gd->kills;
321   edge e;
322   tree phi, use;
323   unsigned uid;
324   edge_iterator ei;
325
326   FOR_EACH_EDGE (e, ei, bb->succs)
327     {
328       if (e->dest == EXIT_BLOCK_PTR)
329         continue;
330
331       for (phi = phi_nodes (e->dest); phi; phi = TREE_CHAIN (phi))
332         {
333           use = PHI_ARG_DEF_FROM_EDGE (phi, e);
334           if (TREE_CODE (use) != SSA_NAME)
335             continue;
336
337           uid = SSA_NAME_VERSION (use);
338
339           if (TEST_BIT (gd->names_to_rename, uid)
340               && !TEST_BIT (kills, uid))
341             set_livein_block (use, bb);
342         }
343     }
344 }
345
346 /* Call back for walk_dominator_tree used to collect definition sites
347    for every variable in the function.  For every statement S in block
348    BB:
349
350    1- Variables defined by S in DEF_OPS(S) are marked in the bitmap
351       WALK_DATA->GLOBAL_DATA->KILLS.
352
353    2- If S uses a variable VAR and there is no preceding kill of VAR,
354       then it is marked in marked in the LIVEIN_BLOCKS bitmap
355       associated with VAR.
356
357    This information is used to determine which variables are live
358    across block boundaries to reduce the number of PHI nodes
359    we create.  */
360
361 static void
362 mark_def_sites (struct dom_walk_data *walk_data,
363                 basic_block bb,
364                 block_stmt_iterator bsi)
365 {
366   struct mark_def_sites_global_data *gd = walk_data->global_data;
367   sbitmap kills = gd->kills;
368   size_t uid;
369   tree stmt, def;
370   use_operand_p use_p;
371   def_operand_p def_p;
372   ssa_op_iter iter;
373
374   /* Mark all the blocks that have definitions for each variable in the
375      VARS_TO_RENAME bitmap.  */
376   stmt = bsi_stmt (bsi);
377   get_stmt_operands (stmt);
378
379   /* If a variable is used before being set, then the variable is live
380      across a block boundary, so mark it live-on-entry to BB.  */
381
382   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE | SSA_OP_VMUSTDEFKILL)
383     {
384       if (prepare_use_operand_for_rename (use_p, &uid)
385           && !TEST_BIT (kills, uid))
386         set_livein_block (USE_FROM_PTR (use_p), bb);
387     }
388   
389   /* Note that virtual definitions are irrelevant for computing KILLS
390      because a V_MAY_DEF does not constitute a killing definition of the
391      variable.  However, the operand of a virtual definitions is a use
392      of the variable, so it may cause the variable to be considered
393      live-on-entry.  */
394
395   FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
396     {
397       if (prepare_use_operand_for_rename (use_p, &uid))
398         {
399           /* If we do not already have an SSA_NAME for our destination,
400              then set the destination to the source.  */
401           if (TREE_CODE (DEF_FROM_PTR (def_p)) != SSA_NAME)
402             SET_DEF (def_p, USE_FROM_PTR (use_p));
403             
404           set_livein_block (USE_FROM_PTR (use_p), bb);
405           set_def_block (DEF_FROM_PTR (def_p), bb, false, false);
406         }
407     }
408
409   /* Now process the virtual must-defs made by this statement.  */
410   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF | SSA_OP_VMUSTDEF)
411     {
412       if (prepare_def_operand_for_rename (def, &uid))
413         {
414           set_def_block (def, bb, false, false);
415           SET_BIT (kills, uid);
416         }
417     }
418
419 }
420
421 /* Ditto, but works over ssa names.  */
422
423 static void
424 ssa_mark_def_sites (struct dom_walk_data *walk_data,
425                     basic_block bb,
426                     block_stmt_iterator bsi)
427 {
428   struct mark_def_sites_global_data *gd = walk_data->global_data;
429   sbitmap kills = gd->kills;
430   size_t uid, def_uid;
431   tree stmt, use, def;
432   ssa_op_iter iter;
433
434   /* Mark all the blocks that have definitions for each variable in the
435      names_to_rename bitmap.  */
436   stmt = bsi_stmt (bsi);
437   get_stmt_operands (stmt);
438
439   /* If a variable is used before being set, then the variable is live
440      across a block boundary, so mark it live-on-entry to BB.  */
441   FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
442     {
443       uid = SSA_NAME_VERSION (use);
444
445       if (TEST_BIT (gd->names_to_rename, uid)
446           && !TEST_BIT (kills, uid))
447         set_livein_block (use, bb);
448     }
449           
450   /* Now process the definition made by this statement.  Mark the
451      variables in KILLS.  */
452   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
453     {
454       def_uid = SSA_NAME_VERSION (def);
455
456       if (TEST_BIT (gd->names_to_rename, def_uid))
457         {
458           set_def_block (def, bb, false, true);
459           SET_BIT (kills, def_uid);
460         }
461     }
462 }
463
464 /* Mark block BB as the definition site for variable VAR.  PHI_P is true if
465    VAR is defined by a phi node.  SSA_P is true if we are called from
466    rewrite_ssa_into_ssa.  */
467
468 static void
469 set_def_block (tree var, basic_block bb, bool phi_p, bool ssa_p)
470 {
471   struct def_blocks_d *db_p;
472   enum need_phi_state state;
473
474   if (!ssa_p
475       && TREE_CODE (var) == SSA_NAME)
476     var = SSA_NAME_VAR (var);
477
478   state = get_phi_state (var);
479   db_p = get_def_blocks_for (var);
480
481   /* Set the bit corresponding to the block where VAR is defined.  */
482   bitmap_set_bit (db_p->def_blocks, bb->index);
483   if (phi_p)
484     bitmap_set_bit (db_p->phi_blocks, bb->index);
485
486   /* Keep track of whether or not we may need to insert phi nodes.
487
488      If we are in the UNKNOWN state, then this is the first definition
489      of VAR.  Additionally, we have not seen any uses of VAR yet, so
490      we do not need a phi node for this variable at this time (i.e.,
491      transition to NEED_PHI_STATE_NO).
492
493      If we are in any other state, then we either have multiple definitions
494      of this variable occurring in different blocks or we saw a use of the
495      variable which was not dominated by the block containing the
496      definition(s).  In this case we may need a PHI node, so enter
497      state NEED_PHI_STATE_MAYBE.  */
498   if (state == NEED_PHI_STATE_UNKNOWN)
499     set_phi_state (var, NEED_PHI_STATE_NO);
500   else
501     set_phi_state (var, NEED_PHI_STATE_MAYBE);
502 }
503
504
505 /* Mark block BB as having VAR live at the entry to BB.  */
506
507 static void
508 set_livein_block (tree var, basic_block bb)
509 {
510   struct def_blocks_d *db_p;
511   enum need_phi_state state = get_phi_state (var);
512
513   db_p = get_def_blocks_for (var);
514
515   /* Set the bit corresponding to the block where VAR is live in.  */
516   bitmap_set_bit (db_p->livein_blocks, bb->index);
517
518   /* Keep track of whether or not we may need to insert phi nodes.
519
520      If we reach here in NEED_PHI_STATE_NO, see if this use is dominated
521      by the single block containing the definition(s) of this variable.  If
522      it is, then we remain in NEED_PHI_STATE_NO, otherwise we transition to
523      NEED_PHI_STATE_MAYBE.  */
524   if (state == NEED_PHI_STATE_NO)
525     {
526       int def_block_index = bitmap_first_set_bit (db_p->def_blocks);
527
528       if (def_block_index == -1
529           || ! dominated_by_p (CDI_DOMINATORS, bb,
530                                BASIC_BLOCK (def_block_index)))
531         set_phi_state (var, NEED_PHI_STATE_MAYBE);
532     }
533   else
534     set_phi_state (var, NEED_PHI_STATE_MAYBE);
535 }
536
537
538 /* If the use operand pointed to by OP_P needs to be renamed, then strip away 
539    any SSA_NAME wrapping the operand, set *UID_P to the underlying variable's 
540    uid, and return true.  Otherwise return false.  If the operand was an 
541    SSA_NAME, change it to the stripped name.  */
542
543 static bool
544 prepare_use_operand_for_rename (use_operand_p op_p, size_t *uid_p)
545 {
546   tree use = USE_FROM_PTR (op_p);
547   tree var = (TREE_CODE (use) != SSA_NAME) ? use : SSA_NAME_VAR (use);
548   *uid_p = var_ann (var)->uid;
549
550   /* Ignore variables that don't need to be renamed.  */
551   if (vars_to_rename && !bitmap_bit_p (vars_to_rename, *uid_p))
552     return false;
553
554   /* The variable needs to be renamed.  If this is a use which already
555      has an SSA_NAME, then strip it off.
556
557      By not throwing away SSA_NAMEs on assignments, we avoid a lot of 
558      useless churn of SSA_NAMEs without having to overly complicate the
559      renamer.  */
560   if (TREE_CODE (use) == SSA_NAME)
561     SET_USE (op_p, var);
562
563   return true;
564 }
565
566 /* If the def variable DEF needs to be renamed, then strip away any SSA_NAME 
567    wrapping the operand, set *UID_P to the underlying variable's uid and return
568    true.  Otherwise return false.  */
569
570 static bool
571 prepare_def_operand_for_rename (tree def, size_t *uid_p)
572 {
573   tree var = (TREE_CODE (def) != SSA_NAME) ? def : SSA_NAME_VAR (def);
574   *uid_p = var_ann (var)->uid;
575
576   /* Ignore variables that don't need to be renamed.  */
577   if (vars_to_rename && !bitmap_bit_p (vars_to_rename, *uid_p))
578     return false;
579
580   return true;
581 }
582
583 /* Helper for insert_phi_nodes.  If VAR needs PHI nodes, insert them
584    at the dominance frontier (DFS) of blocks defining VAR.
585    WORK_STACK is the varray used to implement the worklist of basic
586    blocks.  */
587
588 static inline
589 void insert_phi_nodes_1 (tree var, bitmap *dfs, varray_type *work_stack)
590 {
591   if (get_phi_state (var) != NEED_PHI_STATE_NO)
592     insert_phi_nodes_for (var, dfs, work_stack);
593 }
594
595 /* Insert PHI nodes at the dominance frontier of blocks with variable
596    definitions.  DFS contains the dominance frontier information for
597    the flowgraph.  PHI nodes will only be inserted at the dominance
598    frontier of definition blocks for variables whose NEED_PHI_STATE
599    annotation is marked as ``maybe'' or ``unknown'' (computed by
600    mark_def_sites).  If NAMES_TO_RENAME is not NULL, do the same but
601    for ssa name rewriting.  */
602
603 static void
604 insert_phi_nodes (bitmap *dfs, bitmap names_to_rename)
605 {
606   size_t i;
607   varray_type work_stack;
608   bitmap_iterator bi;
609
610   timevar_push (TV_TREE_INSERT_PHI_NODES);
611
612   /* Array WORK_STACK is a stack of CFG blocks.  Each block that contains
613      an assignment or PHI node will be pushed to this stack.  */
614   VARRAY_GENERIC_PTR_NOGC_INIT (work_stack, last_basic_block, "work_stack");
615
616   /* Iterate over all variables in VARS_TO_RENAME.  For each variable, add
617      to the work list all the blocks that have a definition for the
618      variable.  PHI nodes will be added to the dominance frontier blocks of
619      each definition block.  */
620   if (names_to_rename)
621     {
622       EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
623         {
624           if (ssa_name (i))
625             insert_phi_nodes_1 (ssa_name (i), dfs, &work_stack);
626         }
627     }
628   else if (vars_to_rename)
629     EXECUTE_IF_SET_IN_BITMAP (vars_to_rename, 0, i, bi)
630       {
631         insert_phi_nodes_1 (referenced_var (i), dfs, &work_stack);
632       }
633   else
634     for (i = 0; i < num_referenced_vars; i++)
635       insert_phi_nodes_1 (referenced_var (i), dfs, &work_stack);
636
637   VARRAY_FREE (work_stack);
638
639   timevar_pop (TV_TREE_INSERT_PHI_NODES);
640 }
641
642
643 /* Perform a depth-first traversal of the dominator tree looking for
644    variables to rename.  BB is the block where to start searching.
645    Renaming is a five step process:
646
647    1- Every definition made by PHI nodes at the start of the blocks is
648       registered as the current definition for the corresponding variable.
649
650    2- Every statement in BB is rewritten.  USE and VUSE operands are
651       rewritten with their corresponding reaching definition.  DEF and
652       VDEF targets are registered as new definitions.
653       
654    3- All the PHI nodes in successor blocks of BB are visited.  The
655       argument corresponding to BB is replaced with its current reaching
656       definition.
657
658    4- Recursively rewrite every dominator child block of BB.
659
660    5- Restore (in reverse order) the current reaching definition for every
661       new definition introduced in this block.  This is done so that when
662       we return from the recursive call, all the current reaching
663       definitions are restored to the names that were valid in the
664       dominator parent of BB.  */
665
666 /* SSA Rewriting Step 1.  Initialization, create a block local stack
667    of reaching definitions for new SSA names produced in this block
668    (BLOCK_DEFS).  Register new definitions for every PHI node in the
669    block.  */
670
671 static void
672 rewrite_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
673                           basic_block bb)
674 {
675   tree phi;
676
677   if (dump_file && (dump_flags & TDF_DETAILS))
678     fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
679
680   /* Mark the unwind point for this block.  */
681   VARRAY_PUSH_TREE (block_defs_stack, NULL_TREE);
682
683   /* Step 1.  Register new definitions for every PHI node in the block.
684      Conceptually, all the PHI nodes are executed in parallel and each PHI
685      node introduces a new version for the associated variable.  */
686   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
687     {
688       tree result = PHI_RESULT (phi);
689
690       register_new_def (result, &block_defs_stack);
691     }
692 }
693
694 /* Register DEF (an SSA_NAME) to be a new definition for the original
695    ssa name VAR and push VAR's current reaching definition
696    into the stack pointed by BLOCK_DEFS_P.  */
697
698 static void
699 ssa_register_new_def (tree var, tree def)
700 {
701   tree currdef;
702    
703   /* If this variable is set in a single basic block and all uses are
704      dominated by the set(s) in that single basic block, then there is
705      nothing to do.  TODO we should not be called at all, and just
706      keep the original name.  */
707   if (get_phi_state (var) == NEED_PHI_STATE_NO)
708     {
709       set_current_def (var, def);
710       return;
711     }
712
713   currdef = get_current_def (var);
714
715   /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
716      later used by the dominator tree callbacks to restore the reaching
717      definitions for all the variables defined in the block after a recursive
718      visit to all its immediately dominated blocks.  */
719   VARRAY_PUSH_TREE (block_defs_stack, currdef);
720   VARRAY_PUSH_TREE (block_defs_stack, var);
721
722   /* Set the current reaching definition for VAR to be DEF.  */
723   set_current_def (var, def);
724 }
725
726 /* Ditto, for rewriting ssa names.  */
727
728 static void
729 ssa_rewrite_initialize_block (struct dom_walk_data *walk_data, basic_block bb)
730 {
731   tree phi, new_name;
732   sbitmap names_to_rename = walk_data->global_data;
733   edge e;
734   bool abnormal_phi;
735   edge_iterator ei;
736
737   if (dump_file && (dump_flags & TDF_DETAILS))
738     fprintf (dump_file, "\n\nRenaming block #%d\n\n", bb->index);
739
740   /* Mark the unwind point for this block.  */
741   VARRAY_PUSH_TREE (block_defs_stack, NULL_TREE);
742
743   FOR_EACH_EDGE (e, ei, bb->preds)
744     if (e->flags & EDGE_ABNORMAL)
745       break;
746   abnormal_phi = (e != NULL);
747
748   /* Step 1.  Register new definitions for every PHI node in the block.
749      Conceptually, all the PHI nodes are executed in parallel and each PHI
750      node introduces a new version for the associated variable.  */
751   for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
752     {
753       tree result = PHI_RESULT (phi);
754
755       if (TEST_BIT (names_to_rename, SSA_NAME_VERSION (result)))
756         {
757           new_name = duplicate_ssa_name (result, phi);
758           SET_PHI_RESULT (phi, new_name);
759
760           if (abnormal_phi)
761             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_name) = 1;
762         }
763       else
764         new_name = result;
765
766       ssa_register_new_def (result, new_name);
767     }
768 }
769
770 /* SSA Rewriting Step 3.  Visit all the successor blocks of BB looking for
771    PHI nodes.  For every PHI node found, add a new argument containing the
772    current reaching definition for the variable and the edge through which
773    that definition is reaching the PHI node.  */
774
775 static void
776 rewrite_add_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
777                            basic_block bb)
778 {
779   edge e;
780   edge_iterator ei;
781
782   FOR_EACH_EDGE (e, ei, bb->succs)
783     {
784       tree phi;
785
786       for (phi = phi_nodes (e->dest); phi; phi = TREE_CHAIN (phi))
787         {
788           tree currdef;
789
790           /* If this PHI node has already been rewritten, then there is
791              nothing to do for this PHI or any following PHIs since we
792              always add new PHI nodes at the start of the PHI chain.  */
793           if (PHI_REWRITTEN (phi))
794             break;
795
796           currdef = get_reaching_def (SSA_NAME_VAR (PHI_RESULT (phi)));
797           add_phi_arg (&phi, currdef, e);
798         }
799     }
800 }
801
802 /*  Rewrite existing virtual PHI arguments so that they have the correct
803     reaching definitions.  BB is the basic block whose successors contain the
804     phi nodes we want to add arguments for.  */
805
806 static void
807 rewrite_virtual_phi_arguments (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED, 
808                                basic_block bb)
809 {
810   edge e;
811   use_operand_p op;
812   edge_iterator ei;
813
814   FOR_EACH_EDGE (e, ei, bb->succs)
815     {
816       tree phi;
817
818       if (e->dest == EXIT_BLOCK_PTR)
819         continue;
820
821       for (phi = phi_nodes (e->dest); phi; phi = TREE_CHAIN (phi))
822         {
823           tree result = PHI_RESULT (phi);
824           op = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
825           
826           if (is_gimple_reg (result) 
827               || !bitmap_bit_p (vars_to_rename, 
828                                 var_ann (SSA_NAME_VAR (result))->uid))
829             continue;
830
831           SET_USE (op, get_reaching_def (SSA_NAME_VAR (result)));
832           if (e->flags & EDGE_ABNORMAL)
833             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (op)) = 1;
834         }
835     }
836 }
837
838 /* Ditto, for ssa name rewriting.  */
839
840 static void
841 ssa_rewrite_phi_arguments (struct dom_walk_data *walk_data, basic_block bb)
842 {
843   edge e;
844   sbitmap names_to_rename = walk_data->global_data;
845   use_operand_p op;
846   edge_iterator ei;
847
848   FOR_EACH_EDGE (e, ei, bb->succs)
849     {
850       tree phi;
851
852       if (e->dest == EXIT_BLOCK_PTR)
853         continue;
854
855       for (phi = phi_nodes (e->dest); phi; phi = TREE_CHAIN (phi))
856         {
857           op = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
858           if (TREE_CODE (USE_FROM_PTR (op)) != SSA_NAME)
859             continue;
860           
861           if (!TEST_BIT (names_to_rename, SSA_NAME_VERSION (USE_FROM_PTR (op))))
862             continue; 
863
864           SET_USE (op, get_reaching_def (USE_FROM_PTR (op)));
865           if (e->flags & EDGE_ABNORMAL)
866             SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (op)) = 1;
867         }
868     }
869 }
870
871
872 /* Similar to restore_vars_to_original_value, except that it restores 
873    CURRDEFS to its original value.  */
874 static void
875 rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
876                         basic_block bb ATTRIBUTE_UNUSED)
877 {
878   /* Restore CURRDEFS to its original state.  */
879   while (VARRAY_ACTIVE_SIZE (block_defs_stack) > 0)
880     {
881       tree tmp = VARRAY_TOP_TREE (block_defs_stack);
882       tree saved_def, var;
883
884       VARRAY_POP (block_defs_stack);
885
886       if (tmp == NULL_TREE)
887         break;
888
889       /* If we recorded an SSA_NAME, then make the SSA_NAME the current
890          definition of its underlying variable.  If we recorded anything
891          else, it must have been an _DECL node and its current reaching
892          definition must have been NULL.  */
893       if (TREE_CODE (tmp) == SSA_NAME)
894         {
895           saved_def = tmp;
896           var = SSA_NAME_VAR (saved_def);
897         }
898       else
899         {
900           saved_def = NULL;
901           var = tmp;
902         }
903                                                                                 
904       set_current_def (var, saved_def);
905     }
906 }
907
908 /* Ditto, for rewriting ssa names.  */
909
910 static void
911 ssa_rewrite_finalize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
912                             basic_block bb ATTRIBUTE_UNUSED)
913 {
914
915   /* Step 5.  Restore the current reaching definition for each variable
916      referenced in the block (in reverse order).  */
917   while (VARRAY_ACTIVE_SIZE (block_defs_stack) > 0)
918     {
919       tree var = VARRAY_TOP_TREE (block_defs_stack);
920       tree saved_def;
921
922       VARRAY_POP (block_defs_stack);
923       
924       if (var == NULL)
925         break;
926
927       saved_def = VARRAY_TOP_TREE (block_defs_stack);
928       VARRAY_POP (block_defs_stack);
929
930       set_current_def (var, saved_def);
931     }
932 }
933
934 /* Dump SSA information to FILE.  */
935
936 void
937 dump_tree_ssa (FILE *file)
938 {
939   basic_block bb;
940   const char *funcname
941     = lang_hooks.decl_printable_name (current_function_decl, 2);
942
943   fprintf (file, "SSA information for %s\n\n", funcname);
944
945   FOR_EACH_BB (bb)
946     {
947       dump_bb (bb, file, 0);
948       fputs ("    ", file);
949       print_generic_stmt (file, phi_nodes (bb), dump_flags);
950       fputs ("\n\n", file);
951     }
952 }
953
954
955 /* Dump SSA information to stderr.  */
956
957 void
958 debug_tree_ssa (void)
959 {
960   dump_tree_ssa (stderr);
961 }
962
963
964 /* Dump SSA statistics on FILE.  */
965
966 void
967 dump_tree_ssa_stats (FILE *file)
968 {
969   fprintf (file, "\nHash table statistics:\n");
970
971   fprintf (file, "    def_blocks: ");
972   htab_statistics (file, def_blocks);
973
974   fprintf (file, "\n");
975 }
976
977
978 /* Dump SSA statistics on stderr.  */
979
980 void
981 debug_tree_ssa_stats (void)
982 {
983   dump_tree_ssa_stats (stderr);
984 }
985
986
987 /* Dump statistics for the hash table HTAB.  */
988
989 static void
990 htab_statistics (FILE *file, htab_t htab)
991 {
992   fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
993            (long) htab_size (htab),
994            (long) htab_elements (htab),
995            htab_collisions (htab));
996 }
997
998
999 /* Insert PHI nodes for variable VAR using the dominance frontier
1000    information given in DFS.  WORK_STACK is the varray used to
1001    implement the worklist of basic blocks.  */
1002
1003 static void
1004 insert_phi_nodes_for (tree var, bitmap *dfs, varray_type *work_stack)
1005 {
1006   struct def_blocks_d *def_map;
1007   bitmap phi_insertion_points;
1008   int bb_index;
1009   edge e;
1010   tree phi;
1011   basic_block bb;
1012   bitmap_iterator bi;
1013
1014   def_map = find_def_blocks_for (var);
1015   if (def_map == NULL)
1016     return;
1017
1018   phi_insertion_points = BITMAP_XMALLOC ();
1019
1020   EXECUTE_IF_SET_IN_BITMAP (def_map->def_blocks, 0, bb_index, bi)
1021     {
1022       VARRAY_PUSH_GENERIC_PTR_NOGC (*work_stack, BASIC_BLOCK (bb_index));
1023     }
1024
1025   /* Pop a block off the worklist, add every block that appears in
1026      the original block's dfs that we have not already processed to
1027      the worklist.  Iterate until the worklist is empty.   Blocks
1028      which are added to the worklist are potential sites for
1029      PHI nodes. 
1030
1031      The iteration step could be done during PHI insertion just as
1032      easily.  We do it here for historical reasons -- we used to have
1033      a heuristic which used the potential PHI insertion points to
1034      determine if fully pruned or semi pruned SSA form was appropriate.
1035
1036      We now always use fully pruned SSA form.  */
1037   while (VARRAY_ACTIVE_SIZE (*work_stack) > 0)
1038     {
1039       int dfs_index;
1040       bitmap_iterator bi;
1041
1042       bb = VARRAY_TOP_GENERIC_PTR_NOGC (*work_stack);
1043       bb_index = bb->index;
1044
1045       VARRAY_POP (*work_stack);
1046       
1047       EXECUTE_IF_AND_COMPL_IN_BITMAP (dfs[bb_index],
1048                                       phi_insertion_points,
1049                                       0, dfs_index, bi)
1050         {
1051           basic_block bb = BASIC_BLOCK (dfs_index);
1052
1053           VARRAY_PUSH_GENERIC_PTR_NOGC (*work_stack, bb);
1054           bitmap_set_bit (phi_insertion_points, dfs_index);
1055         }
1056     }
1057
1058   /* Remove the blocks where we already have the phis.  */
1059   bitmap_and_compl_into (phi_insertion_points, def_map->phi_blocks);
1060
1061   /* Now compute global livein for this variable.  Note this modifies
1062      def_map->livein_blocks.  */
1063   compute_global_livein (def_map->livein_blocks, def_map->def_blocks);
1064
1065   /* And insert the PHI nodes.  */
1066   EXECUTE_IF_AND_IN_BITMAP (phi_insertion_points, def_map->livein_blocks,
1067                             0, bb_index, bi)
1068     {
1069       bb = BASIC_BLOCK (bb_index);
1070
1071       phi = create_phi_node (var, bb);
1072
1073       /* If we are rewriting ssa names, add also the phi arguments.  */
1074       if (TREE_CODE (var) == SSA_NAME)
1075         {
1076           edge_iterator ei;
1077           FOR_EACH_EDGE (e, ei, bb->preds)
1078             add_phi_arg (&phi, var, e);
1079         }
1080     }
1081
1082   BITMAP_XFREE (phi_insertion_points);
1083 }
1084
1085 /* SSA Rewriting Step 2.  Rewrite every variable used in each statement in
1086    the block with its immediate reaching definitions.  Update the current
1087    definition of a variable when a new real or virtual definition is found.  */
1088
1089 static void
1090 rewrite_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1091               basic_block bb ATTRIBUTE_UNUSED,
1092               block_stmt_iterator si)
1093 {
1094   stmt_ann_t ann;
1095   tree stmt;
1096   use_operand_p use_p;
1097   def_operand_p def_p;
1098   ssa_op_iter iter;
1099
1100   stmt = bsi_stmt (si);
1101   ann = stmt_ann (stmt);
1102
1103   if (dump_file && (dump_flags & TDF_DETAILS))
1104     {
1105       fprintf (dump_file, "Renaming statement ");
1106       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1107       fprintf (dump_file, "\n");
1108     }
1109
1110   /* We have just scanned the code for operands.  No statement should
1111      be modified.  */
1112   gcc_assert (!ann->modified);
1113
1114   /* Step 1.  Rewrite USES and VUSES in the statement.  */
1115   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
1116     rewrite_operand (use_p);
1117
1118   /* Step 2.  Register the statement's DEF and VDEF operands.  */
1119   FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
1120     {
1121       if (TREE_CODE (DEF_FROM_PTR (def_p)) != SSA_NAME)
1122         SET_DEF (def_p, make_ssa_name (DEF_FROM_PTR (def_p), stmt));
1123
1124       /* FIXME: We shouldn't be registering new defs if the variable
1125          doesn't need to be renamed.  */
1126       register_new_def (DEF_FROM_PTR (def_p), &block_defs_stack);
1127     }
1128 }
1129
1130 /* Ditto, for rewriting ssa names.  */
1131
1132 static void
1133 ssa_rewrite_stmt (struct dom_walk_data *walk_data,
1134                   basic_block bb ATTRIBUTE_UNUSED,
1135                   block_stmt_iterator si)
1136 {
1137   stmt_ann_t ann;
1138   tree stmt, var;
1139   ssa_op_iter iter;
1140   use_operand_p use_p;
1141   def_operand_p def_p;
1142   sbitmap names_to_rename = walk_data->global_data;
1143
1144   stmt = bsi_stmt (si);
1145   ann = stmt_ann (stmt);
1146
1147   if (dump_file && (dump_flags & TDF_DETAILS))
1148     {
1149       fprintf (dump_file, "Renaming statement ");
1150       print_generic_stmt (dump_file, stmt, TDF_SLIM);
1151       fprintf (dump_file, "\n");
1152     }
1153
1154   /* We have just scanned the code for operands.  No statement should
1155      be modified.  */
1156   gcc_assert (!ann->modified);
1157
1158   /* Step 1.  Rewrite USES and VUSES in the statement.  */
1159   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES | SSA_OP_ALL_KILLS)
1160     {
1161       if (TEST_BIT (names_to_rename, SSA_NAME_VERSION (USE_FROM_PTR (use_p))))
1162         SET_USE (use_p, get_reaching_def (USE_FROM_PTR (use_p)));
1163     }
1164
1165   /* Step 2.  Register the statement's DEF and VDEF operands.  */
1166   FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_ALL_DEFS)
1167     {
1168       var = DEF_FROM_PTR (def_p);
1169
1170       if (!TEST_BIT (names_to_rename, SSA_NAME_VERSION (var)))
1171         continue;
1172
1173       SET_DEF (def_p, duplicate_ssa_name (var, stmt));
1174       ssa_register_new_def (var, DEF_FROM_PTR (def_p));
1175     }
1176 }
1177
1178 /* Replace the operand pointed by OP_P with its immediate reaching
1179    definition.  */
1180
1181 static inline void
1182 rewrite_operand (use_operand_p op_p)
1183 {
1184   if (TREE_CODE (USE_FROM_PTR (op_p)) != SSA_NAME)
1185     SET_USE (op_p, get_reaching_def (USE_FROM_PTR (op_p)));
1186 }
1187
1188 /* Register DEF (an SSA_NAME) to be a new definition for its underlying
1189    variable (SSA_NAME_VAR (DEF)) and push VAR's current reaching definition
1190    into the stack pointed by BLOCK_DEFS_P.  */
1191
1192 void
1193 register_new_def (tree def, varray_type *block_defs_p)
1194 {
1195   tree var = SSA_NAME_VAR (def);
1196   tree currdef;
1197    
1198   /* If this variable is set in a single basic block and all uses are
1199      dominated by the set(s) in that single basic block, then there is
1200      no reason to record anything for this variable in the block local
1201      definition stacks.  Doing so just wastes time and memory.
1202
1203      This is the same test to prune the set of variables which may
1204      need PHI nodes.  So we just use that information since it's already
1205      computed and available for us to use.  */
1206   if (get_phi_state (var) == NEED_PHI_STATE_NO)
1207     {
1208       set_current_def (var, def);
1209       return;
1210     }
1211
1212   currdef = get_current_def (var);
1213
1214   /* Push the current reaching definition into *BLOCK_DEFS_P.  This stack is
1215      later used by the dominator tree callbacks to restore the reaching
1216      definitions for all the variables defined in the block after a recursive
1217      visit to all its immediately dominated blocks.  If there is no current
1218      reaching definition, then just record the underlying _DECL node.  */
1219   VARRAY_PUSH_TREE (*block_defs_p, currdef ? currdef : var);
1220
1221   /* Set the current reaching definition for VAR to be DEF.  */
1222   set_current_def (var, def);
1223 }
1224
1225 /* Return the current definition for variable VAR.  If none is found,
1226    create a new SSA name to act as the zeroth definition for VAR.  If VAR
1227    is call clobbered and there exists a more recent definition of
1228    GLOBAL_VAR, return the definition for GLOBAL_VAR.  This means that VAR
1229    has been clobbered by a function call since its last assignment.  */
1230
1231 static tree
1232 get_reaching_def (tree var)
1233 {
1234   tree default_d, currdef_var, avar;
1235   
1236   /* Lookup the current reaching definition for VAR.  */
1237   default_d = NULL_TREE;
1238   currdef_var = get_current_def (var);
1239
1240   /* If there is no reaching definition for VAR, create and register a
1241      default definition for it (if needed).  */
1242   if (currdef_var == NULL_TREE)
1243     {
1244       if (TREE_CODE (var) == SSA_NAME)
1245         avar = SSA_NAME_VAR (var);
1246       else
1247         avar = var;
1248
1249       default_d = default_def (avar);
1250       if (default_d == NULL_TREE)
1251         {
1252           default_d = make_ssa_name (avar, build_empty_stmt ());
1253           set_default_def (avar, default_d);
1254         }
1255       set_current_def (var, default_d);
1256     }
1257
1258   /* Return the current reaching definition for VAR, or the default
1259      definition, if we had to create one.  */
1260   return (currdef_var) ? currdef_var : default_d;
1261 }
1262
1263
1264 /* Hashing and equality functions for DEF_BLOCKS.  */
1265
1266 static hashval_t
1267 def_blocks_hash (const void *p)
1268 {
1269   return htab_hash_pointer
1270         ((const void *)((const struct def_blocks_d *)p)->var);
1271 }
1272
1273 static int
1274 def_blocks_eq (const void *p1, const void *p2)
1275 {
1276   return ((const struct def_blocks_d *)p1)->var
1277          == ((const struct def_blocks_d *)p2)->var;
1278 }
1279
1280 /* Free memory allocated by one entry in DEF_BLOCKS.  */
1281
1282 static void
1283 def_blocks_free (void *p)
1284 {
1285   struct def_blocks_d *entry = p;
1286   BITMAP_XFREE (entry->def_blocks);
1287   BITMAP_XFREE (entry->phi_blocks);
1288   BITMAP_XFREE (entry->livein_blocks);
1289   free (entry);
1290 }
1291
1292
1293 /* Dump the DEF_BLOCKS hash table on stderr.  */
1294
1295 void
1296 debug_def_blocks (void)
1297 {
1298   htab_traverse (def_blocks, debug_def_blocks_r, NULL);
1299 }
1300
1301 /* Callback for htab_traverse to dump the DEF_BLOCKS hash table.  */
1302
1303 static int
1304 debug_def_blocks_r (void **slot, void *data ATTRIBUTE_UNUSED)
1305 {
1306   unsigned long i;
1307   struct def_blocks_d *db_p = (struct def_blocks_d *) *slot;
1308   bitmap_iterator bi;
1309   
1310   fprintf (stderr, "VAR: ");
1311   print_generic_expr (stderr, db_p->var, dump_flags);
1312   fprintf (stderr, ", DEF_BLOCKS: { ");
1313   EXECUTE_IF_SET_IN_BITMAP (db_p->def_blocks, 0, i, bi)
1314     {
1315       fprintf (stderr, "%ld ", i);
1316     }
1317   fprintf (stderr, "}");
1318   fprintf (stderr, ", LIVEIN_BLOCKS: { ");
1319   EXECUTE_IF_SET_IN_BITMAP (db_p->livein_blocks, 0, i, bi)
1320     {
1321       fprintf (stderr, "%ld ", i);
1322     }
1323   fprintf (stderr, "}\n");
1324
1325   return 1;
1326 }
1327
1328
1329 /* Return the set of blocks where variable VAR is defined and the blocks
1330    where VAR is live on entry (livein).  Return NULL, if no entry is
1331    found in DEF_BLOCKS.  */
1332
1333 static inline struct def_blocks_d *
1334 find_def_blocks_for (tree var)
1335 {
1336   struct def_blocks_d dm;
1337   dm.var = var;
1338   return (struct def_blocks_d *) htab_find (def_blocks, &dm);
1339 }
1340
1341
1342 /* Return the set of blocks where variable VAR is defined and the blocks
1343    where VAR is live on entry (livein).  If no entry is found in
1344    DEF_BLOCKS, a new one is created and returned.  */
1345
1346 static inline struct def_blocks_d *
1347 get_def_blocks_for (tree var)
1348 {
1349   struct def_blocks_d db, *db_p;
1350   void **slot;
1351
1352   db.var = var;
1353   slot = htab_find_slot (def_blocks, (void *) &db, INSERT);
1354   if (*slot == NULL)
1355     {
1356       db_p = xmalloc (sizeof (*db_p));
1357       db_p->var = var;
1358       db_p->def_blocks = BITMAP_XMALLOC ();
1359       db_p->phi_blocks = BITMAP_XMALLOC ();
1360       db_p->livein_blocks = BITMAP_XMALLOC ();
1361       *slot = (void *) db_p;
1362     }
1363   else
1364     db_p = (struct def_blocks_d *) *slot;
1365
1366   return db_p;
1367 }
1368
1369 /* If a variable V in VARS_TO_RENAME is a pointer, the renaming
1370    process will cause us to lose the name memory tags that may have
1371    been associated with the various SSA_NAMEs of V.  This means that
1372    the variables aliased to those name tags also need to be renamed
1373    again.
1374
1375    FIXME 1- We should either have a better scheme for renaming
1376             pointers that doesn't lose name tags or re-run alias
1377             analysis to recover points-to information.
1378
1379          2- Currently we just invalidate *all* the name tags.  This
1380             should be more selective.  */
1381
1382 static void
1383 invalidate_name_tags (bitmap vars_to_rename)
1384 {
1385   size_t i;
1386   bool rename_name_tags_p;
1387   bitmap_iterator bi;
1388
1389   rename_name_tags_p = false;
1390   EXECUTE_IF_SET_IN_BITMAP (vars_to_rename, 0, i, bi)
1391     {
1392       if (POINTER_TYPE_P (TREE_TYPE (referenced_var (i))))
1393         {
1394           rename_name_tags_p = true;
1395           break;
1396         }
1397     }
1398
1399   if (rename_name_tags_p)
1400     for (i = 0; i < num_referenced_vars; i++)
1401       {
1402         var_ann_t ann = var_ann (referenced_var (i));
1403
1404         if (ann->mem_tag_kind == NAME_TAG)
1405           {
1406             size_t j;
1407             varray_type may_aliases = ann->may_aliases;
1408
1409             bitmap_set_bit (vars_to_rename, ann->uid);
1410             if (ann->may_aliases)
1411               for (j = 0; j < VARRAY_ACTIVE_SIZE (may_aliases); j++)
1412                 {
1413                   tree var = VARRAY_TREE (may_aliases, j);
1414                   bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1415                 }
1416           }
1417       }
1418 }
1419
1420 /* Rewrite the actual blocks, statements, and phi arguments, to be in SSA
1421    form.  FIX_VIRTUAL_PHIS is true if we should only be fixing up virtual
1422    phi arguments, instead of adding new phi arguments for just added phi
1423    nodes.  */
1424
1425
1426 static void
1427 rewrite_blocks (bool fix_virtual_phis)
1428 {
1429   struct dom_walk_data walk_data;
1430   
1431   /* Rewrite all the basic blocks in the program.  */
1432   timevar_push (TV_TREE_SSA_REWRITE_BLOCKS);
1433
1434   /* Setup callbacks for the generic dominator tree walker.  */
1435   walk_data.walk_stmts_backward = false;
1436   walk_data.dom_direction = CDI_DOMINATORS;
1437   walk_data.initialize_block_local_data = NULL;
1438   walk_data.before_dom_children_before_stmts = rewrite_initialize_block;
1439   walk_data.before_dom_children_walk_stmts = rewrite_stmt;
1440   walk_data.before_dom_children_after_stmts = NULL;
1441   if (!fix_virtual_phis)
1442     walk_data.before_dom_children_after_stmts = rewrite_add_phi_arguments;
1443   else
1444     walk_data.before_dom_children_after_stmts = rewrite_virtual_phi_arguments;
1445   
1446   walk_data.after_dom_children_before_stmts =  NULL;
1447   walk_data.after_dom_children_walk_stmts =  NULL;
1448   walk_data.after_dom_children_after_stmts =  rewrite_finalize_block;
1449   walk_data.global_data = NULL;
1450   walk_data.block_local_data_size = 0;
1451
1452   VARRAY_TREE_INIT (block_defs_stack, 10, "Block DEFS Stack");
1453
1454   /* Initialize the dominator walker.  */
1455   init_walk_dominator_tree (&walk_data);
1456
1457   /* Recursively walk the dominator tree rewriting each statement in
1458      each basic block.  */
1459   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1460
1461   /* Finalize the dominator walker.  */
1462   fini_walk_dominator_tree (&walk_data);
1463
1464   htab_delete (def_blocks);
1465
1466   timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
1467 }
1468
1469 /* Mark the definition site blocks for each variable, so that we know where
1470    the variable is actually live.  */
1471
1472 static void 
1473 mark_def_site_blocks (void)
1474 {
1475   size_t i;
1476   struct dom_walk_data walk_data;
1477   struct mark_def_sites_global_data mark_def_sites_global_data;
1478
1479   /* Allocate memory for the DEF_BLOCKS hash table.  */
1480   def_blocks = htab_create (VARRAY_ACTIVE_SIZE (referenced_vars),
1481                             def_blocks_hash, def_blocks_eq, def_blocks_free);
1482
1483   for (i = 0; i < num_referenced_vars; i++)
1484     set_current_def (referenced_var (i), NULL_TREE);
1485
1486   /* Ensure that the dominance information is OK.  */
1487   calculate_dominance_info (CDI_DOMINATORS);
1488
1489
1490   /* Setup callbacks for the generic dominator tree walker to find and
1491      mark definition sites.  */
1492   walk_data.walk_stmts_backward = false;
1493   walk_data.dom_direction = CDI_DOMINATORS;
1494   walk_data.initialize_block_local_data = NULL;
1495   walk_data.before_dom_children_before_stmts = mark_def_sites_initialize_block;
1496   walk_data.before_dom_children_walk_stmts = mark_def_sites;
1497   walk_data.before_dom_children_after_stmts = NULL; 
1498   walk_data.after_dom_children_before_stmts =  NULL;
1499   walk_data.after_dom_children_walk_stmts =  NULL;
1500   walk_data.after_dom_children_after_stmts =  NULL;
1501
1502   /* Notice that this bitmap is indexed using variable UIDs, so it must be
1503      large enough to accommodate all the variables referenced in the
1504      function, not just the ones we are renaming.  */
1505   mark_def_sites_global_data.kills = sbitmap_alloc (num_referenced_vars);
1506   walk_data.global_data = &mark_def_sites_global_data;
1507
1508   /* We do not have any local data.  */
1509   walk_data.block_local_data_size = 0;
1510
1511   /* Initialize the dominator walker.  */
1512   init_walk_dominator_tree (&walk_data);
1513
1514   /* Recursively walk the dominator tree.  */
1515   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1516
1517   /* Finalize the dominator walker.  */
1518   fini_walk_dominator_tree (&walk_data);
1519
1520   /* We no longer need this bitmap, clear and free it.  */
1521   sbitmap_free (mark_def_sites_global_data.kills);
1522
1523 }
1524 /* Main entry point into the SSA builder.  The renaming process
1525    proceeds in five main phases:
1526
1527    1- If VARS_TO_RENAME has any entries, any existing PHI nodes for
1528       those variables are removed from the flow graph so that they can
1529       be computed again.
1530
1531    2- Compute dominance frontier and immediate dominators, needed to
1532       insert PHI nodes and rename the function in dominator tree
1533       order.
1534
1535    3- Find and mark all the blocks that define variables
1536       (mark_def_site_blocks).
1537
1538    4- Insert PHI nodes at dominance frontiers (insert_phi_nodes).
1539
1540    5- Rename all the blocks (rewrite_blocks) and statements in the program.
1541
1542    Steps 3 and 5 are done using the dominator tree walker
1543    (walk_dominator_tree).
1544
1545    ALL is true if all variables should be renamed (otherwise just those
1546    mentioned in vars_to_rename are taken into account).  */
1547
1548 void
1549 rewrite_into_ssa (bool all)
1550 {
1551   bitmap *dfs;
1552   basic_block bb;
1553   bitmap old_vars_to_rename = vars_to_rename;
1554   
1555   timevar_push (TV_TREE_SSA_OTHER);
1556
1557   if (all)
1558     vars_to_rename = NULL;
1559   else
1560     {
1561       /* Initialize the array of variables to rename.  */
1562       gcc_assert (vars_to_rename);
1563
1564       if (bitmap_empty_p (vars_to_rename))
1565         {
1566           timevar_pop (TV_TREE_SSA_OTHER);
1567           return;
1568         }
1569       
1570       invalidate_name_tags (vars_to_rename);
1571
1572       /* Now remove all the existing PHI nodes (if any) for the variables
1573          that we are about to rename into SSA.  */
1574       remove_all_phi_nodes_for (vars_to_rename);
1575     }
1576
1577   mark_def_site_blocks ();
1578
1579   /* Initialize dominance frontier and immediate dominator bitmaps. 
1580      Also count the number of predecessors for each block.  Doing so
1581      can save significant time during PHI insertion for large graphs.  */
1582   dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap *));
1583   FOR_EACH_BB (bb)
1584     dfs[bb->index] = BITMAP_XMALLOC ();
1585
1586   /* Compute dominance frontiers.  */
1587   compute_dominance_frontiers (dfs);
1588
1589   /* Insert PHI nodes at dominance frontiers of definition blocks.  */
1590   insert_phi_nodes (dfs, NULL);
1591
1592   rewrite_blocks (false);
1593
1594   /* Debugging dumps.  */
1595   if (dump_file && (dump_flags & TDF_STATS))
1596     {
1597       dump_dfa_stats (dump_file);
1598       dump_tree_ssa_stats (dump_file);
1599     }
1600
1601   /* Free allocated memory.  */
1602   FOR_EACH_BB (bb)
1603     BITMAP_XFREE (dfs[bb->index]);
1604   free (dfs);
1605
1606   vars_to_rename = old_vars_to_rename;
1607   timevar_pop (TV_TREE_SSA_OTHER);
1608 }
1609
1610 /* Rewrite the def-def chains so that they have the correct reaching
1611    definitions.  */
1612
1613 void
1614 rewrite_def_def_chains (void)
1615 {
1616   /* Ensure that the dominance information is OK.  */
1617   calculate_dominance_info (CDI_DOMINATORS);
1618   mark_def_site_blocks ();
1619   rewrite_blocks (true);
1620
1621 }
1622 /* The marked ssa names may have more than one definition;
1623    add phi nodes and rewrite them to fix this.  */
1624
1625 void
1626 rewrite_ssa_into_ssa (void)
1627 {
1628   bitmap *dfs;
1629   basic_block bb;
1630   struct dom_walk_data walk_data;
1631   struct mark_def_sites_global_data mark_def_sites_global_data;
1632   unsigned i;
1633   sbitmap snames_to_rename;
1634   tree name;
1635   bitmap to_rename;
1636   bitmap_iterator bi;
1637   
1638   if (!any_marked_for_rewrite_p ())
1639     return;
1640   to_rename = marked_ssa_names ();
1641
1642   timevar_push (TV_TREE_SSA_OTHER);
1643
1644   /* Allocate memory for the DEF_BLOCKS hash table.  */
1645   def_blocks = htab_create (num_ssa_names,
1646                             def_blocks_hash, def_blocks_eq, def_blocks_free);
1647
1648   /* Initialize dominance frontier and immediate dominator bitmaps. 
1649      Also count the number of predecessors for each block.  Doing so
1650      can save significant time during PHI insertion for large graphs.  */
1651   dfs = (bitmap *) xmalloc (last_basic_block * sizeof (bitmap *));
1652   FOR_EACH_BB (bb)
1653     dfs[bb->index] = BITMAP_XMALLOC ();
1654
1655   /* Ensure that the dominance information is OK.  */
1656   calculate_dominance_info (CDI_DOMINATORS);
1657
1658   /* Compute dominance frontiers.  */
1659   compute_dominance_frontiers (dfs);
1660
1661   /* Setup callbacks for the generic dominator tree walker to find and
1662      mark definition sites.  */
1663   walk_data.walk_stmts_backward = false;
1664   walk_data.dom_direction = CDI_DOMINATORS;
1665   walk_data.initialize_block_local_data = NULL;
1666   walk_data.before_dom_children_before_stmts
1667           = ssa_mark_def_sites_initialize_block;
1668   walk_data.before_dom_children_walk_stmts = ssa_mark_def_sites;
1669   walk_data.before_dom_children_after_stmts = ssa_mark_phi_uses; 
1670   walk_data.after_dom_children_before_stmts =  NULL;
1671   walk_data.after_dom_children_walk_stmts =  NULL;
1672   walk_data.after_dom_children_after_stmts =  NULL;
1673
1674   snames_to_rename = sbitmap_alloc (num_ssa_names);
1675   sbitmap_zero (snames_to_rename);
1676   EXECUTE_IF_SET_IN_BITMAP (to_rename, 0, i, bi)
1677     {
1678       SET_BIT (snames_to_rename, i);
1679     }
1680
1681   mark_def_sites_global_data.kills = sbitmap_alloc (num_ssa_names);
1682   mark_def_sites_global_data.names_to_rename = snames_to_rename;
1683   walk_data.global_data = &mark_def_sites_global_data;
1684
1685   VARRAY_TREE_INIT (block_defs_stack, 10, "Block DEFS Stack");
1686
1687   /* We do not have any local data.  */
1688   walk_data.block_local_data_size = 0;
1689
1690   /* Initialize the dominator walker.  */
1691   init_walk_dominator_tree (&walk_data);
1692
1693   /* Recursively walk the dominator tree.  */
1694   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1695
1696   /* Finalize the dominator walker.  */
1697   fini_walk_dominator_tree (&walk_data);
1698
1699   /* We no longer need this bitmap, clear and free it.  */
1700   sbitmap_free (mark_def_sites_global_data.kills);
1701
1702   for (i = 1; i < num_ssa_names; i++)
1703     if (ssa_name (i))
1704       set_current_def (ssa_name (i), NULL_TREE);
1705
1706   /* Insert PHI nodes at dominance frontiers of definition blocks.  */
1707   insert_phi_nodes (dfs, to_rename);
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   walk_data.walk_stmts_backward = false;
1714   walk_data.dom_direction = CDI_DOMINATORS;
1715   walk_data.initialize_block_local_data = NULL;
1716   walk_data.before_dom_children_before_stmts = ssa_rewrite_initialize_block;
1717   walk_data.before_dom_children_walk_stmts = ssa_rewrite_stmt;
1718   walk_data.before_dom_children_after_stmts = ssa_rewrite_phi_arguments;
1719   walk_data.after_dom_children_before_stmts = NULL;
1720   walk_data.after_dom_children_walk_stmts =  NULL;
1721   walk_data.after_dom_children_after_stmts =  ssa_rewrite_finalize_block;
1722   walk_data.global_data = snames_to_rename;
1723   walk_data.block_local_data_size = 0;
1724
1725   /* Initialize the dominator walker.  */
1726   init_walk_dominator_tree (&walk_data);
1727
1728   /* Recursively walk the dominator tree rewriting each statement in
1729      each basic block.  */
1730   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1731
1732   /* Finalize the dominator walker.  */
1733   fini_walk_dominator_tree (&walk_data);
1734
1735   unmark_all_for_rewrite ();
1736
1737   EXECUTE_IF_SET_IN_BITMAP (to_rename, 0, i, bi)
1738     {
1739       release_ssa_name (ssa_name (i));
1740     }
1741
1742   sbitmap_free (snames_to_rename);
1743
1744   timevar_pop (TV_TREE_SSA_REWRITE_BLOCKS);
1745
1746   /* Debugging dumps.  */
1747   if (dump_file && (dump_flags & TDF_STATS))
1748     {
1749       dump_dfa_stats (dump_file);
1750       dump_tree_ssa_stats (dump_file);
1751     }
1752
1753   /* Free allocated memory.  */
1754   FOR_EACH_BB (bb)
1755     BITMAP_XFREE (dfs[bb->index]);
1756   free (dfs);
1757
1758   htab_delete (def_blocks);
1759
1760   for (i = 1; i < num_ssa_names; i++)
1761     {
1762       name = ssa_name (i);
1763       if (!name || !SSA_NAME_AUX (name))
1764         continue;
1765
1766       free (SSA_NAME_AUX (name));
1767       SSA_NAME_AUX (name) = NULL;
1768     }
1769
1770   BITMAP_XFREE (to_rename);
1771   timevar_pop (TV_TREE_SSA_OTHER);
1772 }
1773
1774 /* Rewrites all variables into ssa.  */
1775
1776 static void
1777 rewrite_all_into_ssa (void)
1778 {
1779   rewrite_into_ssa (true);
1780 }
1781
1782 struct tree_opt_pass pass_build_ssa = 
1783 {
1784   "ssa",                                /* name */
1785   NULL,                                 /* gate */
1786   rewrite_all_into_ssa,                 /* execute */
1787   NULL,                                 /* sub */
1788   NULL,                                 /* next */
1789   0,                                    /* static_pass_number */
1790   0,                                    /* tv_id */
1791   PROP_cfg | PROP_referenced_vars,      /* properties_required */
1792   PROP_ssa,                             /* properties_provided */
1793   0,                                    /* properties_destroyed */
1794   0,                                    /* todo_flags_start */
1795   TODO_dump_func | TODO_verify_ssa,                     /* todo_flags_finish */
1796   0                                     /* letter */
1797 };