OSDN Git Service

2007-07-01 Daniel Berlin <dberlin@dberlin.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-sccvn.c
1 /* SCC value numbering for trees
2    Copyright (C) 2006
3    Free Software Foundation, Inc.
4    Contributed by Daniel Berlin <dan@dberlin.org>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "ggc.h"
28 #include "tree.h"
29 #include "basic-block.h"
30 #include "diagnostic.h"
31 #include "tree-inline.h"
32 #include "tree-flow.h"
33 #include "tree-gimple.h"
34 #include "tree-dump.h"
35 #include "timevar.h"
36 #include "fibheap.h"
37 #include "hashtab.h"
38 #include "tree-iterator.h"
39 #include "real.h"
40 #include "alloc-pool.h"
41 #include "tree-pass.h"
42 #include "flags.h"
43 #include "bitmap.h"
44 #include "langhooks.h"
45 #include "cfgloop.h"
46 #include "tree-ssa-sccvn.h"
47
48 /* This algorithm is based on the SCC algorithm presented by Keith
49    Cooper and L. Taylor Simpson in "SCC-Based Value numbering"
50    (http://citeseer.ist.psu.edu/41805.html).  In
51    straight line code, it is equivalent to a regular hash based value
52    numbering that is performed in reverse postorder.
53
54    For code with cycles, there are two alternatives, both of which
55    require keeping the hashtables separate from the actual list of
56    value numbers for SSA names.
57
58    1. Iterate value numbering in an RPO walk of the blocks, removing
59    all the entries from the hashtable after each iteration (but
60    keeping the SSA name->value number mapping between iterations).
61    Iterate until it does not change.
62
63    2. Perform value numbering as part of an SCC walk on the SSA graph,
64    iterating only the cycles in the SSA graph until they do not change
65    (using a separate, optimistic hashtable for value numbering the SCC
66    operands).
67
68    The second is not just faster in practice (because most SSA graph
69    cycles do not involve all the variables in the graph), it also has
70    some nice properties.
71
72    One of these nice properties is that when we pop an SCC off the
73    stack, we are guaranteed to have processed all the operands coming from
74    *outside of that SCC*, so we do not need to do anything special to
75    ensure they have value numbers.
76
77    Another nice property is that the SCC walk is done as part of a DFS
78    of the SSA graph, which makes it easy to perform combining and
79    simplifying operations at the same time.
80
81    The code below is deliberately written in a way that makes it easy
82    to separate the SCC walk from the other work it does.
83
84    In order to propagate constants through the code, we track which
85    expressions contain constants, and use those while folding.  In
86    theory, we could also track expressions whose value numbers are
87    replaced, in case we end up folding based on expression
88    identities.
89
90    In order to value number memory, we assign value numbers to vuses.
91    This enables us to note that, for example, stores to the same
92    address of the same value from the same starting memory states are
93    equivalent.  
94    TODO:
95
96    1. We can iterate only the changing portions of the SCC's, but
97    I have not seen an SCC big enough for this to be a win.
98    2. If you differentiate between phi nodes for loops and phi nodes
99    for if-then-else, you can properly consider phi nodes in different
100    blocks for equivalence.
101    3. We could value number vuses in more cases, particularly, whole
102    structure copies.
103 */
104
105 /* The set of hashtables and alloc_pool's for their items.  */
106
107 typedef struct vn_tables_s
108 {
109   htab_t unary;
110   htab_t binary;
111   htab_t phis;
112   htab_t references;
113   alloc_pool unary_op_pool;
114   alloc_pool binary_op_pool;
115   alloc_pool phis_pool;
116   alloc_pool references_pool;
117 } *vn_tables_t;
118
119 /* Binary operations in the hashtable consist of two operands, an
120    opcode, and a type.  Result is the value number of the operation,
121    and hashcode is stored to avoid having to calculate it
122    repeatedly.  */
123
124 typedef struct vn_binary_op_s
125 {
126   enum tree_code opcode;
127   tree type;
128   tree op0;
129   tree op1;
130   hashval_t hashcode;
131   tree result;
132 } *vn_binary_op_t;
133
134 /* Unary operations in the hashtable consist of a single operand, an
135    opcode, and a type.  Result is the value number of the operation,
136    and hashcode is stored to avoid having to calculate it repeatedly. */
137
138 typedef struct vn_unary_op_s
139 {
140   enum tree_code opcode;
141   tree type;
142   tree op0;
143   hashval_t hashcode;
144   tree result;
145 } *vn_unary_op_t;
146
147 /* Phi nodes in the hashtable consist of their non-VN_TOP phi
148    arguments, and the basic block the phi is in. Result is the value
149    number of the operation, and hashcode is stored to avoid having to
150    calculate it repeatedly.  Phi nodes not in the same block are never
151    considered equivalent.  */
152
153 typedef struct vn_phi_s
154 {
155   VEC (tree, heap) *phiargs;
156   basic_block block;
157   hashval_t hashcode;
158   tree result;
159 } *vn_phi_t;
160
161 /* Reference operands only exist in reference operations structures.
162    They consist of an opcode, type, and some number of operands.  For
163    a given opcode, some, all, or none of the operands may be used.
164    The operands are there to store the information that makes up the
165    portion of the addressing calculation that opcode performs.  */
166
167 typedef struct vn_reference_op_struct
168 {
169   enum tree_code opcode;
170   tree type;
171   tree op0;
172   tree op1;
173   tree op2;
174 } vn_reference_op_s;
175 typedef vn_reference_op_s *vn_reference_op_t;
176
177 DEF_VEC_O(vn_reference_op_s);
178 DEF_VEC_ALLOC_O(vn_reference_op_s, heap);
179
180 /* A reference operation in the hashtable is representation as a
181    collection of vuses, representing the memory state at the time of
182    the operation, and a collection of operands that make up the
183    addressing calculation.  If two vn_reference_t's have the same set
184    of operands, they access the same memory location. We also store
185    the resulting value number, and the hashcode.  The vuses are
186    always stored in order sorted by ssa name version.  */
187
188 typedef struct vn_reference_s
189 {
190   VEC (tree, gc) *vuses;
191   VEC (vn_reference_op_s, heap) *operands;
192   hashval_t hashcode;
193   tree result;
194 } *vn_reference_t;
195
196 /* Valid hashtables storing information we have proven to be
197    correct.  */
198
199 static vn_tables_t valid_info;
200
201 /* Optimistic hashtables storing information we are making assumptions about
202    during iterations.  */
203
204 static vn_tables_t optimistic_info;
205
206 /* PRE hashtables storing information about mapping from expressions to
207    value handles.  */
208
209 static vn_tables_t pre_info;
210
211 /* Pointer to the set of hashtables that is currently being used.
212    Should always point to either the optimistic_info, or the
213    valid_info.  */
214
215 static vn_tables_t current_info;
216
217
218 /* Reverse post order index for each basic block.  */
219
220 static int *rpo_numbers;
221
222 #define SSA_VAL(x) (VN_INFO ((x))->valnum)
223
224 /* This represents the top of the VN lattice, which is the universal
225    value.  */
226
227 tree VN_TOP;
228
229 /* Next DFS number and the stack for strongly connected component
230    detection. */
231
232 static unsigned int next_dfs_num;
233 static VEC (tree, heap) *sccstack;
234
235 DEF_VEC_P(vn_ssa_aux_t);
236 DEF_VEC_ALLOC_P(vn_ssa_aux_t, heap);
237
238 /* Table of vn_ssa_aux_t's, one per ssa_name.  */
239
240 static VEC (vn_ssa_aux_t, heap) *vn_ssa_aux_table;
241
242 /* Return the value numbering information for a given SSA name.  */
243
244 vn_ssa_aux_t
245 VN_INFO (tree name)
246 {
247   return VEC_index (vn_ssa_aux_t, vn_ssa_aux_table,
248                     SSA_NAME_VERSION (name));
249 }
250
251 /* Set the value numbering info for a given SSA name to a given
252    value.  */
253
254 static inline void
255 VN_INFO_SET (tree name, vn_ssa_aux_t value)
256 {
257   VEC_replace (vn_ssa_aux_t, vn_ssa_aux_table,
258                SSA_NAME_VERSION (name), value);
259 }
260
261 /* Get the value numbering info for a given SSA name, creating it if
262    it does not exist.  */ 
263
264 vn_ssa_aux_t
265 VN_INFO_GET (tree name)
266 {
267   vn_ssa_aux_t newinfo = XCNEW (struct vn_ssa_aux);
268   if (SSA_NAME_VERSION (name) >= VEC_length (vn_ssa_aux_t, vn_ssa_aux_table))
269     VEC_safe_grow (vn_ssa_aux_t, heap, vn_ssa_aux_table,
270                    SSA_NAME_VERSION (name) + 1);
271   VEC_replace (vn_ssa_aux_t, vn_ssa_aux_table,
272                SSA_NAME_VERSION (name), newinfo);
273   return newinfo;
274 }
275
276
277 /* Compare two reference operands P1 and P2 for equality.  return true if
278    they are equal, and false otherwise.  */
279
280 static int
281 vn_reference_op_eq (const void *p1, const void *p2)
282 {
283   const vn_reference_op_t vro1 = (vn_reference_op_t) p1;
284   const vn_reference_op_t vro2 = (vn_reference_op_t) p2;
285   return vro1->opcode == vro2->opcode
286     && vro1->type == vro2->type
287     && expressions_equal_p (vro1->op0, vro2->op0)
288     && expressions_equal_p (vro1->op1, vro2->op1)
289     && expressions_equal_p (vro1->op2, vro2->op2);
290 }
291
292 /* Compute the hash for a reference operand VRO1  */
293
294 static hashval_t
295 vn_reference_op_compute_hash (const vn_reference_op_t vro1)
296 {
297   return iterative_hash_expr (vro1->op0, vro1->opcode)
298     + iterative_hash_expr (vro1->op1, vro1->opcode)
299     + iterative_hash_expr (vro1->op2, vro1->opcode);
300 }
301
302 /* Return the hashcode for a given reference operation P1.  */
303
304 static hashval_t
305 vn_reference_hash (const void *p1)
306 {
307   const vn_reference_t vr1 = (vn_reference_t) p1;
308   return vr1->hashcode;
309 }
310
311 /* Compute a hash for the reference operation VR1 and return it.  */
312
313 static inline hashval_t
314 vn_reference_compute_hash (const vn_reference_t vr1)
315 {
316   hashval_t result = 0;
317   tree v;
318   int i;
319   vn_reference_op_t vro;
320
321   for (i = 0; VEC_iterate (tree, vr1->vuses, i, v); i++)
322     result += iterative_hash_expr (v, 0);
323   for (i = 0; VEC_iterate (vn_reference_op_s, vr1->operands, i, vro); i++)
324     result += vn_reference_op_compute_hash (vro);
325
326   return result;
327 }
328
329 /* Return true if reference operations P1 and P2 are equivalent.  This
330    means they have the same set of operands and vuses.  */
331
332 static int
333 vn_reference_eq (const void *p1, const void *p2)
334 {
335   tree v;
336   int i;
337   vn_reference_op_t vro;
338
339   const vn_reference_t vr1 = (vn_reference_t) p1;
340   const vn_reference_t vr2 = (vn_reference_t) p2;
341
342   if (vr1->vuses == vr2->vuses
343       && vr1->operands == vr2->operands)
344     return true;
345
346   /* Impossible for them to be equivalent if they have different
347      number of vuses.  */
348   if (VEC_length (tree, vr1->vuses) != VEC_length (tree, vr2->vuses))
349     return false;
350
351   /* We require that address operands be canonicalized in a way that
352      two memory references will have the same operands if they are
353      equivalent.  */
354   if (VEC_length (vn_reference_op_s, vr1->operands)
355       != VEC_length (vn_reference_op_s, vr2->operands))
356     return false;
357
358   /* The memory state is more often different than the address of the
359      store/load, so check it first.  */
360   for (i = 0; VEC_iterate (tree, vr1->vuses, i, v); i++)
361     {
362       if (VEC_index (tree, vr2->vuses, i) != v)
363         return false;
364     }
365   
366   for (i = 0; VEC_iterate (vn_reference_op_s, vr1->operands, i, vro); i++)
367     {
368       if (!vn_reference_op_eq (VEC_index (vn_reference_op_s, vr2->operands, i),
369                                vro))
370         return false;
371     }
372   return true;
373 }
374
375 /* Place the vuses from STMT into *result */
376
377 static inline void
378 vuses_to_vec (tree stmt, VEC (tree, gc) **result)
379 {
380   ssa_op_iter iter;
381   tree vuse;
382
383   if (!stmt)
384     return;
385
386   FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VIRTUAL_USES)
387     VEC_safe_push (tree, gc, *result, vuse);
388
389   if (VEC_length (tree, *result) > 1)
390     sort_vuses (*result);
391 }
392
393
394 /* Copy the VUSE names in STMT into a vector, and return
395    the vector.  */
396
397 VEC (tree, gc) *
398 copy_vuses_from_stmt (tree stmt)
399 {
400   VEC (tree, gc) *vuses = NULL;
401
402   vuses_to_vec (stmt, &vuses);
403
404   return vuses;
405 }
406
407 /* Place the vdefs from STMT into *result */
408
409 static inline void
410 vdefs_to_vec (tree stmt, VEC (tree, gc) **result)
411 {
412   ssa_op_iter iter;
413   tree vdef;
414
415   if (!stmt)
416     return;
417
418   FOR_EACH_SSA_TREE_OPERAND (vdef, stmt, iter, SSA_OP_VIRTUAL_DEFS)
419     VEC_safe_push (tree, gc, *result, vdef);
420
421   if (VEC_length (tree, *result) > 1)
422     sort_vuses (*result);
423 }
424
425 /* Copy the names of vdef results in STMT into a vector, and return
426    the vector.  */
427
428 static VEC (tree, gc) *
429 copy_vdefs_from_stmt (tree stmt)
430 {
431   VEC (tree, gc) *vdefs = NULL;
432
433   vdefs_to_vec (stmt, &vdefs);
434
435   return vdefs;
436 }
437
438 /* Place for shared_v{uses/defs}_from_stmt to shove vuses/vdefs.  */
439 static VEC (tree, gc) *shared_lookup_vops;
440
441 /* Copy the virtual uses from STMT into SHARED_LOOKUP_VOPS.
442    This function will overwrite the current SHARED_LOOKUP_VOPS
443    variable.  */
444
445 VEC (tree, gc) *
446 shared_vuses_from_stmt (tree stmt)
447 {
448   VEC_truncate (tree, shared_lookup_vops, 0);
449   vuses_to_vec (stmt, &shared_lookup_vops);
450
451   return shared_lookup_vops;
452 }
453
454 /* Copy the operations present in load/store/call REF into RESULT, a vector of
455    vn_reference_op_s's.  */
456
457 static void
458 copy_reference_ops_from_ref (tree ref, VEC(vn_reference_op_s, heap) **result)
459 {
460   /* Calls are different from all other reference operations.  */
461   if (TREE_CODE (ref) == CALL_EXPR)
462     {
463       vn_reference_op_s temp;
464       tree callfn;
465       call_expr_arg_iterator iter;
466       tree callarg;
467
468       /* Copy the call_expr opcode, type, function being called, and
469          arguments.  */
470       memset (&temp, 0, sizeof (temp));
471       temp.type = TREE_TYPE (ref);
472       temp.opcode = CALL_EXPR;
473       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
474
475       callfn = get_callee_fndecl (ref);
476       if (!callfn)
477         callfn = CALL_EXPR_FN (ref);
478       temp.type = TREE_TYPE (callfn);
479       temp.opcode = TREE_CODE (callfn);
480       temp.op0 = callfn;
481       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
482
483       FOR_EACH_CALL_EXPR_ARG (callarg, iter, ref)
484         {
485           memset (&temp, 0, sizeof (temp));
486           temp.type = TREE_TYPE (callarg);
487           temp.opcode = TREE_CODE (callarg);
488           temp.op0 = callarg;
489           VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
490         }
491       return;
492     }
493
494   /* For non-calls, store the information that makes up the address.  */
495
496   while (ref)
497     {
498       vn_reference_op_s temp;
499
500       memset (&temp, 0, sizeof (temp));
501       temp.type = TREE_TYPE (ref);
502       temp.opcode = TREE_CODE (ref);
503
504       switch (temp.opcode)
505         {
506         case ALIGN_INDIRECT_REF:
507         case MISALIGNED_INDIRECT_REF:
508         case INDIRECT_REF:
509           /* The only operand is the address, which gets its own
510              vn_reference_op_s structure.  */
511           break;
512         case BIT_FIELD_REF:
513           /* Record bits and position.  */
514           temp.op0 = TREE_OPERAND (ref, 1);
515           temp.op1 = TREE_OPERAND (ref, 2);
516           break;
517         case COMPONENT_REF:
518           /* Record field as operand.  */
519           temp.op0 = TREE_OPERAND (ref, 1);
520           break;
521         case ARRAY_RANGE_REF:
522         case ARRAY_REF:
523           /* Record index as operand.  */
524           temp.op0 = TREE_OPERAND (ref, 1);
525           temp.op1 = TREE_OPERAND (ref, 3);
526           break;
527         case STRING_CST:
528         case INTEGER_CST:
529         case COMPLEX_CST:
530         case VECTOR_CST:
531         case VALUE_HANDLE:
532         case VAR_DECL:
533         case PARM_DECL:
534         case CONST_DECL:
535         case RESULT_DECL:
536         case SSA_NAME:
537           temp.op0 = ref;
538           break;
539           /* These are only interesting for their operands, their
540              existence, and their type.  They will never be the last
541              ref in the chain of references (IE they require an
542              operand), so we don't have to put anything
543              for op* as it will be handled by the iteration  */
544         case IMAGPART_EXPR:
545         case REALPART_EXPR:
546         case VIEW_CONVERT_EXPR:
547         case ADDR_EXPR:
548           break;
549         default:
550           gcc_unreachable ();
551           
552         }
553       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
554
555       if (REFERENCE_CLASS_P (ref) || TREE_CODE (ref) == ADDR_EXPR)
556         ref = TREE_OPERAND (ref, 0);
557       else
558         ref = NULL_TREE;
559     }
560 }
561
562 /* Create a vector of vn_reference_op_s structures from REF, a
563    REFERENCE_CLASS_P tree.  The vector is not shared. */
564
565 static VEC(vn_reference_op_s, heap) *
566 create_reference_ops_from_ref (tree ref)
567 {
568   VEC (vn_reference_op_s, heap) *result = NULL;
569
570   copy_reference_ops_from_ref (ref, &result);
571   return result;
572 }
573
574 static VEC(vn_reference_op_s, heap) *shared_lookup_references;
575
576 /* Create a vector of vn_reference_op_s structures from REF, a
577    REFERENCE_CLASS_P tree.  The vector is shared among all callers of
578    this function.  */
579
580 static VEC(vn_reference_op_s, heap) *
581 shared_reference_ops_from_ref (tree ref)
582 {
583   if (!ref)
584     return NULL;
585   VEC_truncate (vn_reference_op_s, shared_lookup_references, 0);
586   copy_reference_ops_from_ref (ref, &shared_lookup_references);
587   return shared_lookup_references;
588 }
589
590
591 /* Transform any SSA_NAME's in a vector of vn_reference_op_s
592    structures into their value numbers.  This is done in-place, and
593    the vector passed in is returned.  */
594
595 static VEC (vn_reference_op_s, heap) *
596 valueize_refs (VEC (vn_reference_op_s, heap) *orig)
597 {
598   vn_reference_op_t vro;
599   int i;
600
601   for (i = 0; VEC_iterate (vn_reference_op_s, orig, i, vro); i++)
602     {
603       if (vro->opcode == SSA_NAME
604           || (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME))
605         vro->op0 = SSA_VAL (vro->op0);
606     }
607
608   return orig;
609 }
610
611 /* Transform any SSA_NAME's in ORIG, a vector of vuse trees, into
612    their value numbers. This is done in-place, and the vector passed
613    in is returned.  */
614
615 static VEC (tree, gc) *
616 valueize_vuses (VEC (tree, gc) *orig)
617 {
618   bool made_replacement = false;
619   tree vuse;
620   int i;
621
622   for (i = 0; VEC_iterate (tree, orig, i, vuse); i++)
623     {
624       if (vuse != SSA_VAL (vuse))
625         {
626           made_replacement = true;
627           VEC_replace (tree, orig, i, SSA_VAL (vuse));
628         }
629     }
630
631   if (made_replacement && VEC_length (tree, orig) > 1)
632     sort_vuses (orig);
633
634   return orig;
635 }
636
637 /* Lookup OP in the current hash table, and return the resulting
638    value number if it exists in the hash table.  Return NULL_TREE if
639    it does not exist in the hash table. */
640
641 tree
642 vn_reference_lookup (tree op, VEC (tree, gc) *vuses)
643 {
644   void **slot;
645   struct vn_reference_s vr1;
646
647   vr1.vuses = valueize_vuses (vuses);
648   vr1.operands = valueize_refs (shared_reference_ops_from_ref (op));
649   vr1.hashcode = vn_reference_compute_hash (&vr1);
650   slot = htab_find_slot_with_hash (current_info->references, &vr1, vr1.hashcode,
651                                    NO_INSERT);
652   if (!slot)
653     return NULL_TREE;
654
655   return ((vn_reference_t)*slot)->result;
656 }
657
658 /* Insert OP into the current hash table with a value number of
659    RESULT.  */
660
661 void
662 vn_reference_insert (tree op, tree result, VEC (tree, gc) *vuses)
663 {
664   void **slot;
665   vn_reference_t vr1;
666
667   vr1 = (vn_reference_t) pool_alloc (current_info->references_pool);
668
669   vr1->vuses = valueize_vuses (vuses);
670   vr1->operands = valueize_refs (create_reference_ops_from_ref (op));
671   vr1->hashcode = vn_reference_compute_hash (vr1);
672   vr1->result = TREE_CODE (result) == SSA_NAME ? SSA_VAL (result) : result;
673
674   slot = htab_find_slot_with_hash (current_info->references, vr1, vr1->hashcode,
675                                    INSERT);
676
677   /* Because we lookup stores using vuses, and value number failures
678      using the vdefs (see visit_reference_op_store for how and why),
679      it's possible that on failure we may try to insert an already
680      inserted store.  This is not wrong, there is no ssa name for a
681      store that we could use as a differentiator anyway.  Thus, unlike
682      the other lookup functions, you cannot gcc_assert (!*slot)
683      here.  */
684
685
686   *slot = vr1;
687 }
688
689
690 /* Return the stored hashcode for a unary operation.  */
691
692 static hashval_t
693 vn_unary_op_hash (const void *p1)
694 {
695   const vn_unary_op_t vuo1 = (vn_unary_op_t) p1;
696   return vuo1->hashcode;
697 }
698
699 /* Hash a unary operation P1 and return the result.  */
700
701 static inline hashval_t
702 vn_unary_op_compute_hash (const vn_unary_op_t vuo1)
703 {
704   return iterative_hash_expr (vuo1->op0, vuo1->opcode);
705 }
706
707 /* Return true if P1 and P2, two unary operations, are equivalent.  */
708
709 static int
710 vn_unary_op_eq (const void *p1, const void *p2)
711 {
712   const vn_unary_op_t vuo1 = (vn_unary_op_t) p1;
713   const vn_unary_op_t vuo2 = (vn_unary_op_t) p2;
714   return vuo1->opcode == vuo2->opcode
715     && vuo1->type == vuo2->type
716     && expressions_equal_p (vuo1->op0, vuo2->op0);
717 }
718
719 /* Lookup OP in the current hash table, and return the resulting
720    value number if it exists in the hash table.  Return NULL_TREE if
721    it does not exist in the hash table. */
722
723 tree
724 vn_unary_op_lookup (tree op)
725 {
726   void **slot;
727   struct vn_unary_op_s vuo1;
728
729   vuo1.opcode = TREE_CODE (op);
730   vuo1.type = TREE_TYPE (op);
731   vuo1.op0 = TREE_OPERAND (op, 0);
732
733   if (TREE_CODE (vuo1.op0) == SSA_NAME)
734     vuo1.op0 = SSA_VAL (vuo1.op0);
735
736   vuo1.hashcode = vn_unary_op_compute_hash (&vuo1);
737   slot = htab_find_slot_with_hash (current_info->unary, &vuo1, vuo1.hashcode,
738                                    NO_INSERT);
739   if (!slot)
740     return NULL_TREE;
741   return ((vn_unary_op_t)*slot)->result;
742 }
743
744 /* Insert OP into the current hash table with a value number of
745    RESULT.  */
746
747 void
748 vn_unary_op_insert (tree op, tree result)
749 {
750   void **slot;
751   vn_unary_op_t vuo1 = (vn_unary_op_t) pool_alloc (current_info->unary_op_pool);
752
753   vuo1->opcode = TREE_CODE (op);
754   vuo1->type = TREE_TYPE (op);
755   vuo1->op0 = TREE_OPERAND (op, 0);
756   vuo1->result = result;
757
758   if (TREE_CODE (vuo1->op0) == SSA_NAME)
759     vuo1->op0 = SSA_VAL (vuo1->op0);
760
761   vuo1->hashcode = vn_unary_op_compute_hash (vuo1);
762   slot = htab_find_slot_with_hash (current_info->unary, vuo1, vuo1->hashcode,
763                                    INSERT);
764   gcc_assert (!*slot);
765   *slot = vuo1;
766 }
767
768 /* Compute and return the hash value for binary operation VBO1.  */
769
770 static inline hashval_t
771 vn_binary_op_compute_hash (const vn_binary_op_t vbo1)
772 {
773   return iterative_hash_expr (vbo1->op0, vbo1->opcode)
774     + iterative_hash_expr (vbo1->op1, vbo1->opcode);
775 }
776
777 /* Return the computed hashcode for binary operation P1.  */
778
779 static hashval_t
780 vn_binary_op_hash (const void *p1)
781 {
782   const vn_binary_op_t vbo1 = (vn_binary_op_t) p1;
783   return vbo1->hashcode;
784 }
785
786 /* Compare binary operations P1 and P2 and return true if they are
787    equivalent.  */
788
789 static int
790 vn_binary_op_eq (const void *p1, const void *p2)
791 {
792   const vn_binary_op_t vbo1 = (vn_binary_op_t) p1;
793   const vn_binary_op_t vbo2 = (vn_binary_op_t) p2;
794   return vbo1->opcode == vbo2->opcode
795     && vbo1->type == vbo2->type
796     && expressions_equal_p (vbo1->op0, vbo2->op0)
797     && expressions_equal_p (vbo1->op1, vbo2->op1);
798 }
799
800 /* Lookup OP in the current hash table, and return the resulting
801    value number if it exists in the hash table.  Return NULL_TREE if
802    it does not exist in the hash table. */
803
804 tree
805 vn_binary_op_lookup (tree op)
806 {
807   void **slot;
808   struct vn_binary_op_s vbo1;
809
810   vbo1.opcode = TREE_CODE (op);
811   vbo1.type = TREE_TYPE (op);
812   vbo1.op0 = TREE_OPERAND (op, 0);
813   vbo1.op1 = TREE_OPERAND (op, 1);
814
815   if (TREE_CODE (vbo1.op0) == SSA_NAME)
816     vbo1.op0 = SSA_VAL (vbo1.op0);
817   if (TREE_CODE (vbo1.op1) == SSA_NAME)
818     vbo1.op1 = SSA_VAL (vbo1.op1);
819
820   if (tree_swap_operands_p (vbo1.op0, vbo1.op1, false)
821       && commutative_tree_code (vbo1.opcode))
822     {
823       tree temp = vbo1.op0;
824       vbo1.op0 = vbo1.op1;
825       vbo1.op1 = temp;
826     }
827
828   vbo1.hashcode = vn_binary_op_compute_hash (&vbo1);
829   slot = htab_find_slot_with_hash (current_info->binary, &vbo1, vbo1.hashcode,
830                                    NO_INSERT);
831   if (!slot)
832     return NULL_TREE;
833   return ((vn_binary_op_t)*slot)->result;
834 }
835
836 /* Insert OP into the current hash table with a value number of
837    RESULT.  */
838
839 void
840 vn_binary_op_insert (tree op, tree result)
841 {
842   void **slot;
843   vn_binary_op_t vbo1;
844   vbo1 = (vn_binary_op_t) pool_alloc (current_info->binary_op_pool);
845
846   vbo1->opcode = TREE_CODE (op);
847   vbo1->type = TREE_TYPE (op);
848   vbo1->op0 = TREE_OPERAND (op, 0);
849   vbo1->op1 = TREE_OPERAND (op, 1);
850   vbo1->result = result;
851
852   if (TREE_CODE (vbo1->op0) == SSA_NAME)
853     vbo1->op0 = SSA_VAL (vbo1->op0);
854   if (TREE_CODE (vbo1->op1) == SSA_NAME)
855     vbo1->op1 = SSA_VAL (vbo1->op1);
856
857   if (tree_swap_operands_p (vbo1->op0, vbo1->op1, false)
858       && commutative_tree_code (vbo1->opcode))
859     {
860       tree temp = vbo1->op0;
861       vbo1->op0 = vbo1->op1;
862       vbo1->op1 = temp;
863     }
864   vbo1->hashcode = vn_binary_op_compute_hash (vbo1);
865   slot = htab_find_slot_with_hash (current_info->binary, vbo1, vbo1->hashcode,
866                                    INSERT);
867   gcc_assert (!*slot);
868
869   *slot = vbo1;
870 }
871
872 /* Compute a hashcode for PHI operation VP1 and return it.  */
873
874 static inline hashval_t
875 vn_phi_compute_hash (vn_phi_t vp1)
876 {
877   hashval_t result = 0;
878   int i;
879   tree phi1op;
880
881   result = vp1->block->index;
882
883   for (i = 0; VEC_iterate (tree, vp1->phiargs, i, phi1op); i++)
884     {
885       if (phi1op == VN_TOP)
886         continue;
887       result += iterative_hash_expr (phi1op, result);
888     }
889
890   return result;
891 }
892
893 /* Return the computed hashcode for phi operation P1.  */
894
895 static hashval_t
896 vn_phi_hash (const void *p1)
897 {
898   const vn_phi_t vp1 = (vn_phi_t) p1;
899   return vp1->hashcode;
900 }
901
902 /* Compare two phi entries for equality, ignoring VN_TOP arguments.  */
903
904 static int
905 vn_phi_eq (const void *p1, const void *p2)
906 {
907   const vn_phi_t vp1 = (vn_phi_t) p1;
908   const vn_phi_t vp2 = (vn_phi_t) p2;
909
910   if (vp1->block == vp2->block)
911     {
912       int i;
913       tree phi1op;
914
915       /* Any phi in the same block will have it's arguments in the
916          same edge order, because of how we store phi nodes.  */
917       for (i = 0; VEC_iterate (tree, vp1->phiargs, i, phi1op); i++)
918         {
919           tree phi2op = VEC_index (tree, vp2->phiargs, i);
920           if (phi1op == VN_TOP || phi2op == VN_TOP)
921             continue;
922           if (!expressions_equal_p (phi1op, phi2op))
923             return false;
924         }
925       return true;
926     }
927   return false;
928 }
929
930 static VEC(tree, heap) *shared_lookup_phiargs;
931
932 /* Lookup PHI in the current hash table, and return the resulting
933    value number if it exists in the hash table.  Return NULL_TREE if
934    it does not exist in the hash table. */
935
936 static tree
937 vn_phi_lookup (tree phi)
938 {
939   void **slot;
940   struct vn_phi_s vp1;
941   int i;
942
943   VEC_truncate (tree, shared_lookup_phiargs, 0);
944
945   /* Canonicalize the SSA_NAME's to their value number.  */
946   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
947     {
948       tree def = PHI_ARG_DEF (phi, i);
949       def = TREE_CODE (def) == SSA_NAME ? SSA_VAL (def) : def;
950       VEC_safe_push (tree, heap, shared_lookup_phiargs, def);
951     }
952   vp1.phiargs = shared_lookup_phiargs;
953   vp1.block = bb_for_stmt (phi);
954   vp1.hashcode = vn_phi_compute_hash (&vp1);
955   slot = htab_find_slot_with_hash (current_info->phis, &vp1, vp1.hashcode,
956                                    NO_INSERT);
957   if (!slot)
958     return NULL_TREE;
959   return ((vn_phi_t)*slot)->result;
960 }
961
962 /* Insert PHI into the current hash table with a value number of
963    RESULT.  */
964
965 static void
966 vn_phi_insert (tree phi, tree result)
967 {
968   void **slot;
969   vn_phi_t vp1 = (vn_phi_t) pool_alloc (current_info->phis_pool);
970   int i;
971   VEC (tree, heap) *args = NULL;
972
973   /* Canonicalize the SSA_NAME's to their value number.  */
974   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
975     {
976       tree def = PHI_ARG_DEF (phi, i);
977       def = TREE_CODE (def) == SSA_NAME ? SSA_VAL (def) : def;
978       VEC_safe_push (tree, heap, args, def);
979     }
980   vp1->phiargs = args;
981   vp1->block = bb_for_stmt (phi);
982   vp1->result = result;
983   vp1->hashcode = vn_phi_compute_hash (vp1);
984
985   slot = htab_find_slot_with_hash (current_info->phis, vp1, vp1->hashcode,
986                                    INSERT);
987
988   /* Because we iterate over phi operations more than once, it's
989      possible the slot might already exist here, hence no assert.*/
990   *slot = vp1;
991 }
992
993
994 /* Print set of components in strongly connected component SCC to OUT. */
995
996 static void
997 print_scc (FILE *out, VEC (tree, heap) *scc)
998 {
999   tree var;
1000   unsigned int i;
1001
1002   fprintf (out, "SCC consists of: ");
1003   for (i = 0; VEC_iterate (tree, scc, i, var); i++)
1004     {
1005       print_generic_expr (out, var, 0);
1006       fprintf (out, " ");
1007     }
1008   fprintf (out, "\n");
1009 }
1010
1011 /* Set the value number of FROM to TO, return true if it has changed
1012    as a result.  */
1013
1014 static inline bool
1015 set_ssa_val_to (tree from, tree to)
1016 {
1017   gcc_assert (to != NULL);
1018
1019   /* Make sure we don't create chains of copies, so that we get the
1020      best value numbering.  visit_copy has code to make sure this doesn't
1021      happen, we are doing this here to assert that nothing else breaks
1022      this.  */
1023   gcc_assert (TREE_CODE (to) != SSA_NAME
1024               || TREE_CODE (SSA_VAL (to)) != SSA_NAME
1025               || SSA_VAL (to) == to
1026               || to == from);
1027   /* The only thing we allow as value numbers are ssa_names and
1028      invariants.  So assert that here.  */
1029   gcc_assert (TREE_CODE (to) == SSA_NAME || is_gimple_min_invariant (to));
1030
1031   if (dump_file && (dump_flags & TDF_DETAILS))
1032     {
1033       fprintf (dump_file, "Setting value number of ");
1034       print_generic_expr (dump_file, from, 0);
1035       fprintf (dump_file, " to ");
1036       print_generic_expr (dump_file, to, 0);
1037       fprintf (dump_file, "\n");
1038     }
1039
1040   if (SSA_VAL (from) != to)
1041     {
1042       SSA_VAL (from) = to;
1043       return true;
1044     }
1045   return false;
1046 }
1047
1048 /* Set all definitions in STMT to value number to themselves.
1049    Return true if a value number changed. */
1050
1051 static bool
1052 defs_to_varying (tree stmt)
1053 {
1054   bool changed = false;
1055   ssa_op_iter iter;
1056   def_operand_p defp;
1057
1058   FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_ALL_DEFS)
1059     {
1060       tree def = DEF_FROM_PTR (defp);
1061
1062       VN_INFO (def)->use_processed = true;
1063       changed |= set_ssa_val_to (def, def);
1064     }
1065   return changed;
1066 }
1067
1068 /* Visit a copy between LHS and RHS, return true if the value number
1069    changed.  */
1070
1071 static bool
1072 visit_copy (tree lhs, tree rhs)
1073 {
1074
1075   /* Follow chains of copies to their destination.  */
1076   while (SSA_VAL (rhs) != rhs && TREE_CODE (SSA_VAL (rhs)) == SSA_NAME)
1077     rhs = SSA_VAL (rhs);
1078   
1079   /* The copy may have a more interesting constant filled expression
1080      (we don't, since we know our RHS is just an SSA name).  */
1081   VN_INFO (lhs)->has_constants = VN_INFO (rhs)->has_constants;
1082   VN_INFO (lhs)->expr = VN_INFO (rhs)->expr;
1083
1084   return set_ssa_val_to (lhs, rhs);
1085 }
1086
1087 /* Visit a unary operator RHS, value number it, and return true if the
1088    value number of LHS has changed as a result.  */
1089
1090 static bool
1091 visit_unary_op (tree lhs, tree op)
1092 {
1093   bool changed = false;
1094   tree result = vn_unary_op_lookup (op);
1095
1096   if (result)
1097     {
1098       changed = set_ssa_val_to (lhs, result);
1099     }
1100   else
1101     {
1102       changed = set_ssa_val_to (lhs, lhs);
1103       vn_unary_op_insert (op, lhs);
1104     }
1105
1106   return changed;
1107 }
1108
1109 /* Visit a binary operator RHS, value number it, and return true if the
1110    value number of LHS has changed as a result.  */
1111
1112 static bool
1113 visit_binary_op (tree lhs, tree op)
1114 {
1115   bool changed = false;
1116   tree result = vn_binary_op_lookup (op);
1117
1118   if (result)
1119     {
1120       changed = set_ssa_val_to (lhs, result);
1121     }
1122   else
1123     {
1124       changed = set_ssa_val_to (lhs, lhs);
1125       vn_binary_op_insert (op, lhs);
1126     }
1127
1128   return changed;
1129 }
1130
1131 /* Visit a load from a reference operator RHS, part of STMT, value number it,
1132    and return true if the value number of the LHS has changed as a result.  */
1133
1134 static bool
1135 visit_reference_op_load (tree lhs, tree op, tree stmt)
1136 {
1137   bool changed = false;
1138   tree result = vn_reference_lookup (op, shared_vuses_from_stmt (stmt));
1139
1140   if (result)
1141     {
1142       changed = set_ssa_val_to (lhs, result);
1143     }
1144   else
1145     {
1146       changed = set_ssa_val_to (lhs, lhs);
1147       vn_reference_insert (op, lhs, copy_vuses_from_stmt (stmt));
1148     }
1149
1150   return changed;
1151 }
1152
1153
1154 /* Visit a store to a reference operator LHS, part of STMT, value number it,
1155    and return true if the value number of the LHS has changed as a result.  */
1156
1157 static bool
1158 visit_reference_op_store (tree lhs, tree op, tree stmt)
1159 {
1160   bool changed = false;
1161   tree result;
1162   bool resultsame = false;
1163
1164   /* First we want to lookup using the *vuses* from the store and see
1165      if there the last store to this location with the same address
1166      had the same value.
1167
1168      The vuses represent the memory state before the store.  If the
1169      memory state, address, and value of the store is the same as the
1170      last store to this location, then this store will produce the
1171      same memory state as that store.
1172
1173      In this case the vdef versions for this store are value numbered to those
1174      vuse versions, since they represent the same memory state after
1175      this store.
1176
1177      Otherwise, the vdefs for the store are used when inserting into
1178      the table, since the store generates a new memory state.  */
1179
1180   result = vn_reference_lookup (lhs, shared_vuses_from_stmt (stmt));
1181
1182   if (result)
1183     {
1184       if (TREE_CODE (result) == SSA_NAME)
1185         result = SSA_VAL (result);
1186       resultsame = expressions_equal_p (result, op);
1187     }
1188
1189   if (!result || !resultsame)
1190     {
1191       VEC(tree, gc) *vdefs = copy_vdefs_from_stmt (stmt);
1192       int i;
1193       tree vdef;
1194
1195       if (dump_file && (dump_flags & TDF_DETAILS))
1196         {
1197           fprintf (dump_file, "No store match\n");
1198           fprintf (dump_file, "Value numbering store ");
1199           print_generic_expr (dump_file, lhs, 0);
1200           fprintf (dump_file, " to ");
1201           print_generic_expr (dump_file, op, 0);
1202           fprintf (dump_file, "\n");
1203         }
1204       /* Have to set value numbers before insert, since insert is
1205          going to valueize the references in-place.  */
1206       for (i = 0; VEC_iterate (tree, vdefs, i, vdef); i++)
1207         {
1208           VN_INFO (vdef)->use_processed = true;
1209           changed |= set_ssa_val_to (vdef, vdef);
1210         }
1211
1212       vn_reference_insert (lhs, op, vdefs);
1213     }
1214   else
1215     {
1216       /* We had a match, so value number the vdefs to have the value
1217          number of the vuses they came from.  */
1218       ssa_op_iter op_iter;
1219       def_operand_p var;
1220       vuse_vec_p vv;
1221
1222       if (dump_file && (dump_flags & TDF_DETAILS))
1223         fprintf (dump_file, "Store matched earlier value,"
1224                  "value numbering store vdefs to matching vuses.\n");
1225
1226       FOR_EACH_SSA_VDEF_OPERAND (var, vv, stmt, op_iter)
1227         {
1228           tree def = DEF_FROM_PTR (var);
1229           tree use;
1230
1231           /* Uh, if the vuse is a multiuse, we can't really do much
1232              here, sadly, since we don't know which value number of
1233              which vuse to use.  */
1234           if (VUSE_VECT_NUM_ELEM (*vv) != 1)
1235             use = def;
1236           else
1237             use = VUSE_ELEMENT_VAR (*vv, 0);
1238
1239           VN_INFO (def)->use_processed = true;
1240           changed |= set_ssa_val_to (def, SSA_VAL (use));
1241         }
1242     }
1243
1244   return changed;
1245 }
1246
1247 /* Visit and value number PHI, return true if the value number
1248    changed.  */
1249
1250 static bool
1251 visit_phi (tree phi)
1252 {
1253   bool changed = false;
1254   tree result;
1255   tree sameval = VN_TOP;
1256   bool allsame = true;
1257   int i;
1258
1259   /* See if all non-TOP arguments have the same value.  TOP is
1260      equivalent to everything, so we can ignore it.  */
1261   for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1262     {
1263       tree def = PHI_ARG_DEF (phi, i);
1264
1265       if (TREE_CODE (def) == SSA_NAME)
1266         def = SSA_VAL (def);
1267       if (def == VN_TOP)
1268         continue;
1269       if (sameval == VN_TOP)
1270         {
1271           sameval = def;
1272         }
1273       else
1274         {
1275           if (!expressions_equal_p (def, sameval))
1276             {
1277               allsame = false;
1278               break;
1279             }
1280         }
1281     }
1282
1283   /* If all value numbered to the same value, the phi node has that
1284      value.  */
1285   if (allsame)
1286     {
1287       if (is_gimple_min_invariant (sameval))
1288         {
1289           VN_INFO (PHI_RESULT (phi))->has_constants = true;
1290           VN_INFO (PHI_RESULT (phi))->expr = sameval;
1291         }
1292       else
1293         {
1294           VN_INFO (PHI_RESULT (phi))->has_constants = false;
1295           VN_INFO (PHI_RESULT (phi))->expr = sameval;
1296         }
1297       
1298       if (TREE_CODE (sameval) == SSA_NAME)
1299         return visit_copy (PHI_RESULT (phi), sameval);
1300       
1301       return set_ssa_val_to (PHI_RESULT (phi), sameval);
1302     }
1303
1304   /* Otherwise, see if it is equivalent to a phi node in this block.  */
1305   result = vn_phi_lookup (phi);
1306   if (result)
1307     {
1308       if (TREE_CODE (result) == SSA_NAME)
1309         changed = visit_copy (PHI_RESULT (phi), result);
1310       else
1311         changed = set_ssa_val_to (PHI_RESULT (phi), result);
1312     }
1313   else
1314     {
1315       vn_phi_insert (phi, PHI_RESULT (phi));
1316       VN_INFO (PHI_RESULT (phi))->has_constants = false;
1317       VN_INFO (PHI_RESULT (phi))->expr = PHI_RESULT (phi);
1318       changed = set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
1319     }
1320
1321   return changed;
1322 }
1323
1324 /* Return true if EXPR contains constants.  */
1325
1326 static bool
1327 expr_has_constants (tree expr)
1328 {
1329   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
1330     {
1331     case tcc_unary:
1332       return is_gimple_min_invariant (TREE_OPERAND (expr, 0));
1333
1334     case tcc_binary:
1335       return is_gimple_min_invariant (TREE_OPERAND (expr, 0))
1336         || is_gimple_min_invariant (TREE_OPERAND (expr, 1));
1337       /* Constants inside reference ops are rarely interesting, but
1338          it can take a lot of looking to find them.  */
1339     case tcc_reference:
1340       return false;
1341     default:
1342       return is_gimple_min_invariant (expr);
1343     }
1344   return false;
1345 }
1346
1347 /* Replace SSA_NAMES in expr with their value numbers, and return the
1348    result.
1349    This is performed in place. */
1350
1351 static tree
1352 valueize_expr (tree expr)
1353 {
1354   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
1355     {
1356     case tcc_unary:
1357       if (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1358           && SSA_VAL (TREE_OPERAND (expr, 0)) != VN_TOP)
1359         TREE_OPERAND (expr, 0) = SSA_VAL (TREE_OPERAND (expr, 0));
1360       break;
1361     case tcc_binary:
1362       if (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
1363           && SSA_VAL (TREE_OPERAND (expr, 0)) != VN_TOP)
1364         TREE_OPERAND (expr, 0) = SSA_VAL (TREE_OPERAND (expr, 0));
1365       if (TREE_CODE (TREE_OPERAND (expr, 1)) == SSA_NAME
1366           && SSA_VAL (TREE_OPERAND (expr, 1)) != VN_TOP)
1367         TREE_OPERAND (expr, 1) = SSA_VAL (TREE_OPERAND (expr, 1));
1368       break;
1369     default:
1370       break;
1371     }
1372   return expr;
1373 }
1374
1375 /* Simplify the binary expression RHS, and return the result if
1376    simplified. */
1377
1378 static tree
1379 simplify_binary_expression (tree rhs)
1380 {
1381   tree result = NULL_TREE;
1382   tree op0 = TREE_OPERAND (rhs, 0);
1383   tree op1 = TREE_OPERAND (rhs, 1);
1384
1385   /* This will not catch every single case we could combine, but will
1386      catch those with constants.  The goal here is to simultaneously
1387      combine constants between expressions, but avoid infinite
1388      expansion of expressions during simplification.  */
1389   if (TREE_CODE (op0) == SSA_NAME)
1390     {
1391       if (VN_INFO (op0)->has_constants)
1392         op0 = valueize_expr (VN_INFO (op0)->expr);
1393       else if (SSA_VAL (op0) != VN_TOP && SSA_VAL (op0) != op0)
1394         op0 = VN_INFO (op0)->valnum;      
1395     }
1396
1397   if (TREE_CODE (op1) == SSA_NAME)
1398     {
1399       if (VN_INFO (op1)->has_constants)
1400         op1 = valueize_expr (VN_INFO (op1)->expr);
1401       else if (SSA_VAL (op1) != VN_TOP && SSA_VAL (op1) != op1)
1402         op1 = VN_INFO (op1)->valnum;
1403     }
1404   result = fold_binary (TREE_CODE (rhs), TREE_TYPE (rhs), op0, op1);
1405
1406   /* Make sure result is not a complex expression consiting
1407      of operators of operators (IE (a + b) + (a + c))
1408      Otherwise, we will end up with unbounded expressions if
1409      fold does anything at all.  */
1410   if (result)
1411     {
1412       if (is_gimple_min_invariant (result))
1413         return result;
1414       else if (SSA_VAR_P (result))
1415         return result;
1416       else if (EXPR_P (result))
1417         {
1418           switch (TREE_CODE_CLASS (TREE_CODE (result)))
1419             {
1420             case tcc_unary:
1421               {
1422                 tree op0 = TREE_OPERAND (result, 0);
1423                 if (!EXPR_P (op0))
1424                   return result;
1425               }
1426               break;
1427             case tcc_binary:
1428               {
1429                 tree op0 = TREE_OPERAND (result, 0);
1430                 tree op1 = TREE_OPERAND (result, 1);
1431                 if (!EXPR_P (op0) && !EXPR_P (op1))
1432                   return result;
1433               }
1434               break;
1435             default:
1436               break;
1437             }
1438         }
1439     }
1440   return NULL_TREE;
1441 }
1442
1443 /* Try to simplify RHS using equivalences and constant folding.  */
1444
1445 static tree
1446 try_to_simplify (tree stmt, tree rhs)
1447 {
1448   if (TREE_CODE (rhs) == SSA_NAME)
1449     {
1450       if (is_gimple_min_invariant (SSA_VAL (rhs)))
1451         return SSA_VAL (rhs);
1452       else if (VN_INFO (rhs)->has_constants)
1453         return VN_INFO (rhs)->expr;
1454     }
1455   else
1456     {
1457       switch (TREE_CODE_CLASS (TREE_CODE (rhs)))
1458         {
1459           /* For references, see if we find a result for the lookup,
1460              and use it if we do.  */
1461
1462         case tcc_reference:
1463           {
1464             tree result = vn_reference_lookup (rhs,
1465                                                shared_vuses_from_stmt (stmt));
1466             if (result)
1467               return result;
1468           }
1469           break;
1470           /* We could do a little more with unary ops, if they expand
1471              into binary ops, but it's debatable whether it is worth it. */
1472         case tcc_unary:
1473           {
1474             tree result = NULL_TREE;
1475             tree op0 = TREE_OPERAND (rhs, 0);
1476             if (TREE_CODE (op0) == SSA_NAME && VN_INFO (op0)->has_constants)
1477               op0 = VN_INFO (op0)->expr;
1478             else if (TREE_CODE (op0) == SSA_NAME && SSA_VAL (op0) != op0)
1479               op0 = SSA_VAL (op0);
1480             result = fold_unary (TREE_CODE (rhs), TREE_TYPE (rhs), op0);
1481             if (result)
1482               return result;
1483           }
1484           break;
1485         case tcc_comparison:
1486         case tcc_binary:
1487           return simplify_binary_expression (rhs);
1488           break;
1489         default:
1490           break;
1491         }
1492     }
1493   return rhs;
1494 }
1495
1496 /* Visit and value number USE, return true if the value number
1497    changed. */
1498
1499 static bool
1500 visit_use (tree use)
1501 {
1502   bool changed = false;
1503   tree stmt = SSA_NAME_DEF_STMT (use);
1504   stmt_ann_t ann;
1505
1506   VN_INFO (use)->use_processed = true;
1507
1508   gcc_assert (!SSA_NAME_IN_FREE_LIST (use));
1509   if (dump_file && (dump_flags & TDF_DETAILS))
1510     {
1511       fprintf (dump_file, "Value numbering ");
1512       print_generic_expr (dump_file, use, 0);
1513       fprintf (dump_file, " stmt = ");
1514       print_generic_stmt (dump_file, stmt, 0);
1515     }
1516
1517   /* RETURN_EXPR may have an embedded MODIFY_STMT.  */
1518   if (TREE_CODE (stmt) == RETURN_EXPR
1519       && TREE_CODE (TREE_OPERAND (stmt, 0)) == GIMPLE_MODIFY_STMT)
1520     stmt = TREE_OPERAND (stmt, 0);
1521
1522   ann = stmt_ann (stmt);
1523
1524   /* Handle uninitialized uses.  */
1525   if (IS_EMPTY_STMT (stmt))
1526     {
1527       changed = set_ssa_val_to (use, use);
1528     }
1529   else
1530     {
1531       if (TREE_CODE (stmt) == PHI_NODE)
1532         {
1533           changed = visit_phi (stmt);
1534         }
1535       else if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT
1536                || (ann && ann->has_volatile_ops))
1537         {
1538           changed = defs_to_varying (stmt);
1539         }
1540       else
1541         {
1542           tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1543           tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1544           tree simplified;
1545
1546           STRIP_USELESS_TYPE_CONVERSION (rhs);
1547
1548           /* Shortcut for copies. Simplifying copies is pointless,
1549              since we copy the expression and value they represent.  */
1550           if (TREE_CODE (rhs) == SSA_NAME && TREE_CODE (lhs) == SSA_NAME)
1551             {
1552               changed = visit_copy (lhs, rhs);
1553               goto done;
1554             }
1555           simplified = try_to_simplify (stmt, rhs);
1556           if (simplified && simplified != rhs)
1557             {
1558               if (dump_file && (dump_flags & TDF_DETAILS))
1559                 {
1560                   fprintf (dump_file, "RHS ");
1561                   print_generic_expr (dump_file, rhs, 0);
1562                   fprintf (dump_file, " simplified to ");
1563                   print_generic_expr (dump_file, simplified, 0);
1564                   if (TREE_CODE (lhs) == SSA_NAME)
1565                     fprintf (dump_file, " has constants %d\n",
1566                              VN_INFO (lhs)->has_constants);
1567                   else
1568                     fprintf (dump_file, "\n");
1569
1570                 }
1571             }
1572           /* Setting value numbers to constants will occasionally
1573              screw up phi congruence because constants are not
1574              uniquely associated with a single ssa name that can be
1575              looked up.  */
1576           if (simplified && is_gimple_min_invariant (simplified)
1577               && TREE_CODE (lhs) == SSA_NAME
1578               && simplified != rhs)
1579             {
1580               VN_INFO (lhs)->expr = simplified;
1581               VN_INFO (lhs)->has_constants = true;
1582               changed = set_ssa_val_to (lhs, simplified);
1583               goto done;
1584             }
1585           else if (simplified && TREE_CODE (simplified) == SSA_NAME
1586                    && TREE_CODE (lhs) == SSA_NAME)
1587             {
1588               changed = visit_copy (lhs, simplified);
1589               goto done;
1590             }
1591           else if (simplified)
1592             {
1593               if (TREE_CODE (lhs) == SSA_NAME)
1594                 {
1595                   VN_INFO (lhs)->has_constants = expr_has_constants (simplified);
1596                   /* We have to unshare the expression or else
1597                      valuizing may change the IL stream.  */
1598                   VN_INFO (lhs)->expr = unshare_expr (simplified);
1599                 }
1600               rhs = simplified;
1601             }
1602           else if (expr_has_constants (rhs) && TREE_CODE (lhs) == SSA_NAME)
1603             {
1604               VN_INFO (lhs)->has_constants = true;
1605               VN_INFO (lhs)->expr = unshare_expr (rhs);
1606             }
1607           else if (TREE_CODE (lhs) == SSA_NAME)
1608             {
1609               /* We reset expr and constantness here because we may
1610                  have been value numbering optimistically, and
1611                  iterating. They may become non-constant in this case,
1612                  even if they were optimistically constant. */
1613                  
1614               VN_INFO (lhs)->has_constants = false;
1615               VN_INFO (lhs)->expr = lhs;
1616             }
1617
1618           if (TREE_CODE (lhs) == SSA_NAME
1619               && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
1620             changed = defs_to_varying (stmt);
1621           else if (REFERENCE_CLASS_P (lhs))
1622             {
1623               changed = visit_reference_op_store (lhs, rhs, stmt);
1624             }
1625           else if (TREE_CODE (lhs) == SSA_NAME)
1626             {
1627               if (is_gimple_min_invariant (rhs))
1628                 {
1629                   VN_INFO (lhs)->has_constants = true;
1630                   VN_INFO (lhs)->expr = rhs;
1631                   changed = set_ssa_val_to (lhs, rhs);
1632                 }
1633               else
1634                 {
1635                   switch (TREE_CODE_CLASS (TREE_CODE (rhs)))
1636                     {
1637                     case tcc_unary:
1638                       changed = visit_unary_op (lhs, rhs);
1639                       break;
1640                     case tcc_binary:
1641                       changed = visit_binary_op (lhs, rhs);
1642                       break;
1643                       /* If tcc_vl_expr ever encompasses more than
1644                          CALL_EXPR, this will need to be changed.  */
1645                     case tcc_vl_exp:
1646                       if (call_expr_flags (rhs)  & (ECF_PURE | ECF_CONST))
1647                         changed = visit_reference_op_load (lhs, rhs, stmt);
1648                       else
1649                         changed = defs_to_varying (stmt);
1650                       break;
1651                     case tcc_declaration:
1652                     case tcc_reference:
1653                       changed = visit_reference_op_load (lhs, rhs, stmt);
1654                       break;
1655                     case tcc_expression:
1656                       if (TREE_CODE (rhs) == ADDR_EXPR)
1657                         {
1658                           changed = visit_unary_op (lhs, rhs);
1659                           goto done;
1660                         }
1661                       /* Fallthrough.  */
1662                     default:
1663                       changed = defs_to_varying (stmt);
1664                       break;
1665                     }
1666                 }
1667             }
1668           else
1669             changed = defs_to_varying (stmt);
1670         }
1671     }
1672  done:
1673   return changed;
1674 }
1675
1676 /* Compare two operands by reverse postorder index */
1677
1678 static int
1679 compare_ops (const void *pa, const void *pb)
1680 {
1681   const tree opa = *((const tree *)pa);
1682   const tree opb = *((const tree *)pb);
1683   tree opstmta = SSA_NAME_DEF_STMT (opa);
1684   tree opstmtb = SSA_NAME_DEF_STMT (opb);
1685   basic_block bba;
1686   basic_block bbb;
1687
1688   if (IS_EMPTY_STMT (opstmta) && IS_EMPTY_STMT (opstmtb))
1689     return 0;
1690   else if (IS_EMPTY_STMT (opstmta))
1691     return -1;
1692   else if (IS_EMPTY_STMT (opstmtb))
1693     return 1;
1694
1695   bba = bb_for_stmt (opstmta);
1696   bbb = bb_for_stmt (opstmtb);
1697
1698   if (!bba && !bbb)
1699     return 0;
1700   else if (!bba)
1701     return -1;
1702   else if (!bbb)
1703     return 1;
1704
1705   if (bba == bbb)
1706     {
1707       if (TREE_CODE (opstmta) == PHI_NODE && TREE_CODE (opstmtb) == PHI_NODE)
1708         return 0;
1709       else if (TREE_CODE (opstmta) == PHI_NODE)
1710         return -1;
1711       else if (TREE_CODE (opstmtb) == PHI_NODE)
1712         return 1;
1713       return stmt_ann (opstmta)->uid - stmt_ann (opstmtb)->uid;
1714     }
1715   return rpo_numbers[bba->index] - rpo_numbers[bbb->index];
1716 }
1717
1718 /* Sort an array containing members of a strongly connected component
1719    SCC so that the members are ordered by RPO number.
1720    This means that when the sort is complete, iterating through the
1721    array will give you the members in RPO order.  */
1722
1723 static void
1724 sort_scc (VEC (tree, heap) *scc)
1725 {
1726   qsort (VEC_address (tree, scc),
1727          VEC_length (tree, scc),
1728          sizeof (tree),
1729          compare_ops);
1730 }
1731
1732 /* Process a strongly connected component in the SSA graph.  */
1733
1734 static void
1735 process_scc (VEC (tree, heap) *scc)
1736 {
1737   /* If the SCC has a single member, just visit it.  */
1738
1739   if (VEC_length (tree, scc) == 1)
1740     {
1741       tree use = VEC_index (tree, scc, 0);
1742       if (!VN_INFO (use)->use_processed) 
1743         visit_use (use);
1744     }
1745   else
1746     {
1747       tree var;
1748       unsigned int i;
1749       unsigned int iterations = 0;
1750       bool changed = true;
1751
1752       /* Iterate over the SCC with the optimistic table until it stops
1753          changing.  */
1754       current_info = optimistic_info;
1755       while (changed)
1756         {
1757           changed = false;
1758           iterations++;
1759           for (i = 0; VEC_iterate (tree, scc, i, var); i++)
1760             changed |= visit_use (var);
1761         }
1762
1763       if (dump_file && (dump_flags & TDF_STATS))
1764         fprintf (dump_file, "Processing SCC required %d iterations\n",
1765                  iterations);
1766
1767       /* Finally, visit the SCC once using the valid table.  */
1768       current_info = valid_info;
1769       for (i = 0; VEC_iterate (tree, scc, i, var); i++)
1770         visit_use (var);
1771     }
1772 }
1773
1774 /* Depth first search on NAME to discover and process SCC's in the SSA
1775    graph.
1776    Execution of this algorithm relies on the fact that the SCC's are
1777    popped off the stack in topological order.  */
1778
1779 static void
1780 DFS (tree name)
1781 {
1782   ssa_op_iter iter;
1783   use_operand_p usep;
1784   tree defstmt;
1785
1786   /* SCC info */
1787   VN_INFO (name)->dfsnum = next_dfs_num++;
1788   VN_INFO (name)->visited = true;
1789   VN_INFO (name)->low = VN_INFO (name)->dfsnum;
1790
1791   VEC_safe_push (tree, heap, sccstack, name);
1792   VN_INFO (name)->on_sccstack = true;
1793   defstmt = SSA_NAME_DEF_STMT (name);
1794
1795   /* Recursively DFS on our operands, looking for SCC's.  */
1796   if (!IS_EMPTY_STMT (defstmt))
1797     {
1798       FOR_EACH_PHI_OR_STMT_USE (usep, SSA_NAME_DEF_STMT (name), iter,
1799                                 SSA_OP_ALL_USES)
1800         {
1801           tree use = USE_FROM_PTR (usep);
1802
1803           /* Since we handle phi nodes, we will sometimes get
1804              invariants in the use expression.  */
1805           if (TREE_CODE (use) != SSA_NAME)
1806             continue;
1807
1808           if (! (VN_INFO (use)->visited))
1809             {
1810               DFS (use);
1811               VN_INFO (name)->low = MIN (VN_INFO (name)->low,
1812                                          VN_INFO (use)->low);
1813             }
1814           if (VN_INFO (use)->dfsnum < VN_INFO (name)->dfsnum
1815               && VN_INFO (use)->on_sccstack)
1816             {
1817               VN_INFO (name)->low = MIN (VN_INFO (use)->dfsnum,
1818                                          VN_INFO (name)->low);
1819             }
1820         }
1821     }
1822
1823   /* See if we found an SCC.  */
1824   if (VN_INFO (name)->low == VN_INFO (name)->dfsnum)
1825     {
1826       VEC (tree, heap) *scc = NULL;
1827       tree x;
1828
1829       /* Found an SCC, pop the components off the SCC stack and
1830          process them.  */
1831       do
1832         {
1833           x = VEC_pop (tree, sccstack);
1834
1835           VN_INFO (x)->on_sccstack = false;
1836           VEC_safe_push (tree, heap, scc, x);
1837         } while (x != name);
1838
1839       if (VEC_length (tree, scc) > 1)
1840         sort_scc (scc);
1841
1842       if (dump_file && (dump_flags & TDF_DETAILS))
1843         print_scc (dump_file, scc);
1844
1845       process_scc (scc);
1846
1847       VEC_free (tree, heap, scc);
1848     }
1849 }
1850
1851 static void
1852 free_phi (void *vp)
1853 {
1854   vn_phi_t phi = vp;
1855   VEC_free (tree, heap, phi->phiargs);
1856 }
1857
1858
1859 /* Free a reference operation structure VP.  */
1860
1861 static void
1862 free_reference (void *vp)
1863 {
1864   vn_reference_t vr = vp;
1865   VEC_free (vn_reference_op_s, heap, vr->operands);
1866 }
1867
1868 /* Allocate a value number table.  */
1869
1870 static void
1871 allocate_vn_table (vn_tables_t table)
1872 {
1873   table->phis = htab_create (23, vn_phi_hash, vn_phi_eq, free_phi);
1874   table->unary = htab_create (23, vn_unary_op_hash, vn_unary_op_eq, NULL);
1875   table->binary = htab_create (23, vn_binary_op_hash, vn_binary_op_eq, NULL);
1876   table->references = htab_create (23, vn_reference_hash, vn_reference_eq,
1877                                    free_reference);
1878
1879   table->unary_op_pool = create_alloc_pool ("VN unary operations",
1880                                             sizeof (struct vn_unary_op_s),
1881                                             30);
1882   table->binary_op_pool = create_alloc_pool ("VN binary operations",
1883                                              sizeof (struct vn_binary_op_s),
1884                                              30);
1885   table->phis_pool = create_alloc_pool ("VN phis",
1886                                         sizeof (struct vn_phi_s),
1887                                         30);
1888   table->references_pool = create_alloc_pool ("VN references",
1889                                               sizeof (struct vn_reference_s),
1890                                               30);
1891 }
1892
1893 /* Free a value number table.  */
1894
1895 static void
1896 free_vn_table (vn_tables_t table)
1897 {
1898   htab_delete (table->phis);
1899   htab_delete (table->unary);
1900   htab_delete (table->binary);
1901   htab_delete (table->references);
1902   free_alloc_pool (table->unary_op_pool);
1903   free_alloc_pool (table->binary_op_pool);
1904   free_alloc_pool (table->phis_pool);
1905   free_alloc_pool (table->references_pool);
1906 }
1907
1908 static void
1909 init_scc_vn (void)
1910 {
1911   size_t i;
1912   int j;
1913   int *rpo_numbers_temp;
1914   basic_block bb;
1915   size_t id = 0;
1916
1917   calculate_dominance_info (CDI_DOMINATORS);
1918   sccstack = NULL;
1919   next_dfs_num = 1;
1920
1921   vn_ssa_aux_table = VEC_alloc (vn_ssa_aux_t, heap, num_ssa_names + 1);
1922   /* VEC_alloc doesn't actually grow it to the right size, it just
1923      preallocates the space to do so.  */
1924   VEC_safe_grow (vn_ssa_aux_t, heap, vn_ssa_aux_table, num_ssa_names + 1);
1925   shared_lookup_phiargs = NULL;
1926   shared_lookup_vops = NULL;
1927   shared_lookup_references = NULL;
1928   rpo_numbers = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
1929   rpo_numbers_temp = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
1930   pre_and_rev_post_order_compute (NULL, rpo_numbers_temp, false);
1931
1932   /* RPO numbers is an array of rpo ordering, rpo[i] = bb means that
1933      the i'th block in RPO order is bb.  We want to map bb's to RPO
1934      numbers, so we need to rearrange this array.  */
1935   for (j = 0; j < n_basic_blocks - NUM_FIXED_BLOCKS; j++)
1936     rpo_numbers[rpo_numbers_temp[j]] = j;
1937
1938   free (rpo_numbers_temp);
1939
1940   VN_TOP = create_tmp_var_raw (void_type_node, "vn_top");
1941
1942   /* Create the VN_INFO structures, and initialize value numbers to
1943      TOP.  */
1944   for (i = 0; i < num_ssa_names; i++)
1945     {
1946       tree name = ssa_name (i);
1947       if (name)
1948         {
1949           VN_INFO_GET (name)->valnum = VN_TOP;
1950           VN_INFO (name)->expr = name;
1951         }
1952     }
1953
1954   FOR_ALL_BB (bb)
1955     {
1956       block_stmt_iterator bsi;
1957       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1958         {
1959           tree stmt = bsi_stmt (bsi);
1960           stmt_ann (stmt)->uid = id++;
1961         }
1962     }
1963
1964   /* Create the valid and optimistic value numbering tables.  */
1965   valid_info = XCNEW (struct vn_tables_s);
1966   allocate_vn_table (valid_info);
1967   optimistic_info = XCNEW (struct vn_tables_s);
1968   allocate_vn_table (optimistic_info);
1969   pre_info = NULL;
1970 }
1971
1972 void
1973 switch_to_PRE_table (void)
1974 {
1975   pre_info = XCNEW (struct vn_tables_s);
1976   allocate_vn_table (pre_info);
1977   current_info = pre_info;
1978 }
1979
1980 void
1981 free_scc_vn (void)
1982 {
1983   size_t i;
1984
1985   VEC_free (tree, heap, shared_lookup_phiargs);
1986   VEC_free (tree, gc, shared_lookup_vops);
1987   VEC_free (vn_reference_op_s, heap, shared_lookup_references);
1988   XDELETEVEC (rpo_numbers);
1989   for (i = 0; i < num_ssa_names; i++)
1990     {
1991       tree name = ssa_name (i);
1992       if (name)
1993         {
1994           XDELETE (VN_INFO (name));
1995           if (SSA_NAME_VALUE (name) &&
1996               TREE_CODE (SSA_NAME_VALUE (name)) == VALUE_HANDLE)
1997             SSA_NAME_VALUE (name) = NULL;
1998         }
1999     }
2000       
2001   VEC_free (vn_ssa_aux_t, heap, vn_ssa_aux_table);
2002   VEC_free (tree, heap, sccstack);
2003   free_vn_table (valid_info);
2004   XDELETE (valid_info);
2005   free_vn_table (optimistic_info);
2006   XDELETE (optimistic_info);
2007   if (pre_info)
2008     {
2009       free_vn_table (pre_info);
2010       XDELETE (pre_info);
2011     }
2012 }
2013
2014 void
2015 run_scc_vn (void)
2016 {
2017   size_t i;
2018   tree param;
2019
2020   init_scc_vn ();
2021   current_info = valid_info;
2022
2023   for (param = DECL_ARGUMENTS (current_function_decl);
2024        param;
2025        param = TREE_CHAIN (param))
2026     {
2027       if (gimple_default_def (cfun, param) != NULL)
2028         {
2029           tree def = gimple_default_def (cfun, param);
2030           SSA_VAL (def) = def;
2031         }
2032     }
2033
2034   for (i = num_ssa_names - 1; i > 0; i--)
2035     {
2036       tree name = ssa_name (i);
2037       if (name
2038           && VN_INFO (name)->visited == false
2039           && !has_zero_uses (name))
2040         DFS (name);
2041     }
2042
2043   if (dump_file && (dump_flags & TDF_DETAILS))
2044     {
2045       fprintf (dump_file, "Value numbers:\n");
2046       for (i = 0; i < num_ssa_names; i++)
2047         {
2048           tree name = ssa_name (i);
2049           if (name && VN_INFO (name)->visited
2050               && (SSA_VAL (name) != name
2051                   || is_gimple_min_invariant (VN_INFO (name)->expr)))
2052             {
2053               print_generic_expr (dump_file, name, 0);
2054               fprintf (dump_file, " = ");
2055               if (is_gimple_min_invariant (VN_INFO (name)->expr))
2056                 print_generic_expr (dump_file, VN_INFO (name)->expr, 0);
2057               else
2058                 print_generic_expr (dump_file, SSA_VAL (name), 0);
2059               fprintf (dump_file, "\n");
2060             }
2061         }
2062     }
2063 }