OSDN Git Service

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