fb903921656f5a70eabd3a2ba27418fe9c10e840
[platform/upstream/gcc.git] / gcc / tree-ssa-sccvn.c
1 /* SCC value numbering for trees
2    Copyright (C) 2006, 2007, 2008, 2009
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 "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 static htab_t constant_to_value_id;
119 static bitmap constant_value_ids;
120
121
122 /* Valid hashtables storing information we have proven to be
123    correct.  */
124
125 static vn_tables_t valid_info;
126
127 /* Optimistic hashtables storing information we are making assumptions about
128    during iterations.  */
129
130 static vn_tables_t optimistic_info;
131
132 /* Pointer to the set of hashtables that is currently being used.
133    Should always point to either the optimistic_info, or the
134    valid_info.  */
135
136 static vn_tables_t current_info;
137
138
139 /* Reverse post order index for each basic block.  */
140
141 static int *rpo_numbers;
142
143 #define SSA_VAL(x) (VN_INFO ((x))->valnum)
144
145 /* This represents the top of the VN lattice, which is the universal
146    value.  */
147
148 tree VN_TOP;
149
150 /* Unique counter for our value ids.  */
151
152 static unsigned int next_value_id;
153
154 /* Next DFS number and the stack for strongly connected component
155    detection. */
156
157 static unsigned int next_dfs_num;
158 static VEC (tree, heap) *sccstack;
159
160 static bool may_insert;
161
162
163 DEF_VEC_P(vn_ssa_aux_t);
164 DEF_VEC_ALLOC_P(vn_ssa_aux_t, heap);
165
166 /* Table of vn_ssa_aux_t's, one per ssa_name.  The vn_ssa_aux_t objects
167    are allocated on an obstack for locality reasons, and to free them
168    without looping over the VEC.  */
169
170 static VEC (vn_ssa_aux_t, heap) *vn_ssa_aux_table;
171 static struct obstack vn_ssa_aux_obstack;
172
173 /* Return the value numbering information for a given SSA name.  */
174
175 vn_ssa_aux_t
176 VN_INFO (tree name)
177 {
178   vn_ssa_aux_t res = VEC_index (vn_ssa_aux_t, vn_ssa_aux_table,
179                                 SSA_NAME_VERSION (name));
180   gcc_assert (res);
181   return res;
182 }
183
184 /* Set the value numbering info for a given SSA name to a given
185    value.  */
186
187 static inline void
188 VN_INFO_SET (tree name, vn_ssa_aux_t value)
189 {
190   VEC_replace (vn_ssa_aux_t, vn_ssa_aux_table,
191                SSA_NAME_VERSION (name), value);
192 }
193
194 /* Initialize the value numbering info for a given SSA name.
195    This should be called just once for every SSA name.  */
196
197 vn_ssa_aux_t
198 VN_INFO_GET (tree name)
199 {
200   vn_ssa_aux_t newinfo;
201
202   newinfo = XOBNEW (&vn_ssa_aux_obstack, struct vn_ssa_aux);
203   memset (newinfo, 0, sizeof (struct vn_ssa_aux));
204   if (SSA_NAME_VERSION (name) >= VEC_length (vn_ssa_aux_t, vn_ssa_aux_table))
205     VEC_safe_grow (vn_ssa_aux_t, heap, vn_ssa_aux_table,
206                    SSA_NAME_VERSION (name) + 1);
207   VEC_replace (vn_ssa_aux_t, vn_ssa_aux_table,
208                SSA_NAME_VERSION (name), newinfo);
209   return newinfo;
210 }
211
212
213 /* Get the representative expression for the SSA_NAME NAME.  Returns
214    the representative SSA_NAME if there is no expression associated with it.  */
215
216 tree
217 vn_get_expr_for (tree name)
218 {
219   vn_ssa_aux_t vn = VN_INFO (name);
220   gimple def_stmt;
221   tree expr = NULL_TREE;
222
223   if (vn->valnum == VN_TOP)
224     return name;
225
226   /* If the value-number is a constant it is the representative
227      expression.  */
228   if (TREE_CODE (vn->valnum) != SSA_NAME)
229     return vn->valnum;
230
231   /* Get to the information of the value of this SSA_NAME.  */
232   vn = VN_INFO (vn->valnum);
233
234   /* If the value-number is a constant it is the representative
235      expression.  */
236   if (TREE_CODE (vn->valnum) != SSA_NAME)
237     return vn->valnum;
238
239   /* Else if we have an expression, return it.  */
240   if (vn->expr != NULL_TREE)
241     return vn->expr;
242
243   /* Otherwise use the defining statement to build the expression.  */
244   def_stmt = SSA_NAME_DEF_STMT (vn->valnum);
245
246   /* If the value number is a default-definition or a PHI result
247      use it directly.  */
248   if (gimple_nop_p (def_stmt)
249       || gimple_code (def_stmt) == GIMPLE_PHI)
250     return vn->valnum;
251
252   if (!is_gimple_assign (def_stmt))
253     return vn->valnum;
254
255   /* FIXME tuples.  This is incomplete and likely will miss some
256      simplifications.  */
257   switch (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)))
258     {
259     case tcc_reference:
260       if (gimple_assign_rhs_code (def_stmt) == VIEW_CONVERT_EXPR
261           || gimple_assign_rhs_code (def_stmt) == REALPART_EXPR
262           || gimple_assign_rhs_code (def_stmt) == IMAGPART_EXPR)
263         expr = fold_build1 (gimple_assign_rhs_code (def_stmt),
264                             gimple_expr_type (def_stmt),
265                             TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0));
266       break;
267
268     case tcc_unary:
269       expr = fold_build1 (gimple_assign_rhs_code (def_stmt),
270                           gimple_expr_type (def_stmt),
271                           gimple_assign_rhs1 (def_stmt));
272       break;
273
274     case tcc_binary:
275       expr = fold_build2 (gimple_assign_rhs_code (def_stmt),
276                           gimple_expr_type (def_stmt),
277                           gimple_assign_rhs1 (def_stmt),
278                           gimple_assign_rhs2 (def_stmt));
279       break;
280
281     default:;
282     }
283   if (expr == NULL_TREE)
284     return vn->valnum;
285
286   /* Cache the expression.  */
287   vn->expr = expr;
288
289   return expr;
290 }
291
292
293 /* Free a phi operation structure VP.  */
294
295 static void
296 free_phi (void *vp)
297 {
298   vn_phi_t phi = (vn_phi_t) vp;
299   VEC_free (tree, heap, phi->phiargs);
300 }
301
302 /* Free a reference operation structure VP.  */
303
304 static void
305 free_reference (void *vp)
306 {
307   vn_reference_t vr = (vn_reference_t) vp;
308   VEC_free (vn_reference_op_s, heap, vr->operands);
309 }
310
311 /* Hash table equality function for vn_constant_t.  */
312
313 static int
314 vn_constant_eq (const void *p1, const void *p2)
315 {
316   const struct vn_constant_s *vc1 = (const struct vn_constant_s *) p1;
317   const struct vn_constant_s *vc2 = (const struct vn_constant_s *) p2;
318
319   if (vc1->hashcode != vc2->hashcode)
320     return false;
321
322   return vn_constant_eq_with_type (vc1->constant, vc2->constant);
323 }
324
325 /* Hash table hash function for vn_constant_t.  */
326    
327 static hashval_t
328 vn_constant_hash (const void *p1)
329 {
330   const struct vn_constant_s *vc1 = (const struct vn_constant_s *) p1;
331   return vc1->hashcode;
332 }
333
334 /* Lookup a value id for CONSTANT and return it.  If it does not
335    exist returns 0.  */
336
337 unsigned int
338 get_constant_value_id (tree constant)
339 {
340   void **slot;
341   struct vn_constant_s vc;
342
343   vc.hashcode = vn_hash_constant_with_type (constant);
344   vc.constant = constant;
345   slot = htab_find_slot_with_hash (constant_to_value_id, &vc,
346                                    vc.hashcode, NO_INSERT);
347   if (slot)
348     return ((vn_constant_t)*slot)->value_id;
349   return 0;
350 }
351
352 /* Lookup a value id for CONSTANT, and if it does not exist, create a
353    new one and return it.  If it does exist, return it.  */
354
355 unsigned int
356 get_or_alloc_constant_value_id (tree constant)
357 {
358   void **slot;
359   vn_constant_t vc = XNEW (struct vn_constant_s);
360   
361   vc->hashcode = vn_hash_constant_with_type (constant);
362   vc->constant = constant;
363   slot = htab_find_slot_with_hash (constant_to_value_id, vc,
364                                    vc->hashcode, INSERT);  
365   if (*slot)
366     {
367       free (vc);
368       return ((vn_constant_t)*slot)->value_id;
369     }
370   vc->value_id = get_next_value_id ();
371   *slot = vc;
372   bitmap_set_bit (constant_value_ids, vc->value_id);
373   return vc->value_id;
374 }
375
376 /* Return true if V is a value id for a constant.  */
377
378 bool
379 value_id_constant_p (unsigned int v)
380 {
381   return bitmap_bit_p (constant_value_ids, v);  
382 }
383
384 /* Compare two reference operands P1 and P2 for equality.  Return true if
385    they are equal, and false otherwise.  */
386
387 static int
388 vn_reference_op_eq (const void *p1, const void *p2)
389 {
390   const_vn_reference_op_t const vro1 = (const_vn_reference_op_t) p1;
391   const_vn_reference_op_t const vro2 = (const_vn_reference_op_t) p2;
392
393   return vro1->opcode == vro2->opcode
394     && types_compatible_p (vro1->type, vro2->type)
395     && expressions_equal_p (vro1->op0, vro2->op0)
396     && expressions_equal_p (vro1->op1, vro2->op1)
397     && expressions_equal_p (vro1->op2, vro2->op2);
398 }
399
400 /* Compute the hash for a reference operand VRO1.  */
401
402 static hashval_t
403 vn_reference_op_compute_hash (const vn_reference_op_t vro1)
404 {
405   hashval_t result = 0;
406   if (vro1->op0)
407     result += iterative_hash_expr (vro1->op0, vro1->opcode);
408   if (vro1->op1)
409     result += iterative_hash_expr (vro1->op1, vro1->opcode);
410   if (vro1->op2)
411     result += iterative_hash_expr (vro1->op2, vro1->opcode);
412   return result;
413 }
414
415 /* Return the hashcode for a given reference operation P1.  */
416
417 static hashval_t
418 vn_reference_hash (const void *p1)
419 {
420   const_vn_reference_t const vr1 = (const_vn_reference_t) p1;
421   return vr1->hashcode;
422 }
423
424 /* Compute a hash for the reference operation VR1 and return it.  */
425
426 hashval_t
427 vn_reference_compute_hash (const vn_reference_t vr1)
428 {
429   hashval_t result = 0;
430   tree v;
431   int i;
432   vn_reference_op_t vro;
433
434   for (i = 0; VEC_iterate (tree, vr1->vuses, i, v); i++)
435     result += iterative_hash_expr (v, 0);
436   for (i = 0; VEC_iterate (vn_reference_op_s, vr1->operands, i, vro); i++)
437     result += vn_reference_op_compute_hash (vro);
438
439   return result;
440 }
441
442 /* Return true if reference operations P1 and P2 are equivalent.  This
443    means they have the same set of operands and vuses.  */
444
445 int
446 vn_reference_eq (const void *p1, const void *p2)
447 {
448   tree v;
449   int i;
450   vn_reference_op_t vro;
451
452   const_vn_reference_t const vr1 = (const_vn_reference_t) p1;
453   const_vn_reference_t const vr2 = (const_vn_reference_t) p2;
454   if (vr1->hashcode != vr2->hashcode)
455     return false;
456
457   if (vr1->vuses == vr2->vuses
458       && vr1->operands == vr2->operands)
459     return true;
460
461   /* Impossible for them to be equivalent if they have different
462      number of vuses.  */
463   if (VEC_length (tree, vr1->vuses) != VEC_length (tree, vr2->vuses))
464     return false;
465
466   /* We require that address operands be canonicalized in a way that
467      two memory references will have the same operands if they are
468      equivalent.  */
469   if (VEC_length (vn_reference_op_s, vr1->operands)
470       != VEC_length (vn_reference_op_s, vr2->operands))
471     return false;
472
473   /* The memory state is more often different than the address of the
474      store/load, so check it first.  */
475   for (i = 0; VEC_iterate (tree, vr1->vuses, i, v); i++)
476     {
477       if (VEC_index (tree, vr2->vuses, i) != v)
478         return false;
479     }
480
481   for (i = 0; VEC_iterate (vn_reference_op_s, vr1->operands, i, vro); i++)
482     {
483       if (!vn_reference_op_eq (VEC_index (vn_reference_op_s, vr2->operands, i),
484                                vro))
485         return false;
486     }
487   return true;
488 }
489
490 /* Place the vuses from STMT into *result.  */
491
492 static inline void
493 vuses_to_vec (gimple stmt, VEC (tree, gc) **result)
494 {
495   ssa_op_iter iter;
496   tree vuse;
497
498   if (!stmt)
499     return;
500
501   VEC_reserve_exact (tree, gc, *result,
502                      num_ssa_operands (stmt, SSA_OP_VIRTUAL_USES));
503
504   FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VIRTUAL_USES)
505     VEC_quick_push (tree, *result, vuse);
506 }
507
508
509 /* Copy the VUSE names in STMT into a vector, and return
510    the vector.  */
511
512 static VEC (tree, gc) *
513 copy_vuses_from_stmt (gimple stmt)
514 {
515   VEC (tree, gc) *vuses = NULL;
516
517   vuses_to_vec (stmt, &vuses);
518
519   return vuses;
520 }
521
522 /* Place the vdefs from STMT into *result.  */
523
524 static inline void
525 vdefs_to_vec (gimple stmt, VEC (tree, gc) **result)
526 {
527   ssa_op_iter iter;
528   tree vdef;
529
530   if (!stmt)
531     return;
532
533   *result = VEC_alloc (tree, gc, num_ssa_operands (stmt, SSA_OP_VIRTUAL_DEFS));
534
535   FOR_EACH_SSA_TREE_OPERAND (vdef, stmt, iter, SSA_OP_VIRTUAL_DEFS)
536     VEC_quick_push (tree, *result, vdef);
537 }
538
539 /* Copy the names of vdef results in STMT into a vector, and return
540    the vector.  */
541
542 static VEC (tree, gc) *
543 copy_vdefs_from_stmt (gimple stmt)
544 {
545   VEC (tree, gc) *vdefs = NULL;
546
547   vdefs_to_vec (stmt, &vdefs);
548
549   return vdefs;
550 }
551
552 /* Place for shared_v{uses/defs}_from_stmt to shove vuses/vdefs.  */
553 static VEC (tree, gc) *shared_lookup_vops;
554
555 /* Copy the virtual uses from STMT into SHARED_LOOKUP_VOPS.
556    This function will overwrite the current SHARED_LOOKUP_VOPS
557    variable.  */
558
559 VEC (tree, gc) *
560 shared_vuses_from_stmt (gimple stmt)
561 {
562   VEC_truncate (tree, shared_lookup_vops, 0);
563   vuses_to_vec (stmt, &shared_lookup_vops);
564
565   return shared_lookup_vops;
566 }
567
568 /* Copy the operations present in load/store REF into RESULT, a vector of
569    vn_reference_op_s's.  */
570
571 void
572 copy_reference_ops_from_ref (tree ref, VEC(vn_reference_op_s, heap) **result)
573 {
574   if (TREE_CODE (ref) == TARGET_MEM_REF)
575     {
576       vn_reference_op_s temp;
577
578       memset (&temp, 0, sizeof (temp));
579       /* We do not care for spurious type qualifications.  */
580       temp.type = TYPE_MAIN_VARIANT (TREE_TYPE (ref));
581       temp.opcode = TREE_CODE (ref);
582       temp.op0 = TMR_SYMBOL (ref) ? TMR_SYMBOL (ref) : TMR_BASE (ref);
583       temp.op1 = TMR_INDEX (ref);
584       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
585
586       memset (&temp, 0, sizeof (temp));
587       temp.type = NULL_TREE;
588       temp.opcode = TREE_CODE (ref);
589       temp.op0 = TMR_STEP (ref);
590       temp.op1 = TMR_OFFSET (ref);
591       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
592       return;
593     }
594
595   /* For non-calls, store the information that makes up the address.  */
596
597   while (ref)
598     {
599       vn_reference_op_s temp;
600
601       memset (&temp, 0, sizeof (temp));
602       /* We do not care for spurious type qualifications.  */
603       temp.type = TYPE_MAIN_VARIANT (TREE_TYPE (ref));
604       temp.opcode = TREE_CODE (ref);
605
606       switch (temp.opcode)
607         {
608         case ALIGN_INDIRECT_REF:
609         case INDIRECT_REF:
610           /* The only operand is the address, which gets its own
611              vn_reference_op_s structure.  */
612           break;
613         case MISALIGNED_INDIRECT_REF:
614           temp.op0 = TREE_OPERAND (ref, 1);
615           break;
616         case BIT_FIELD_REF:
617           /* Record bits and position.  */
618           temp.op0 = TREE_OPERAND (ref, 1);
619           temp.op1 = TREE_OPERAND (ref, 2);
620           break;
621         case COMPONENT_REF:
622           /* The field decl is enough to unambiguously specify the field,
623              a matching type is not necessary and a mismatching type
624              is always a spurious difference.  */
625           temp.type = NULL_TREE;
626           /* If this is a reference to a union member, record the union
627              member size as operand.  Do so only if we are doing
628              expression insertion (during FRE), as PRE currently gets
629              confused with this.  */
630           if (may_insert
631               && TREE_OPERAND (ref, 2) == NULL_TREE
632               && TREE_CODE (DECL_CONTEXT (TREE_OPERAND (ref, 1))) == UNION_TYPE
633               && integer_zerop (DECL_FIELD_OFFSET (TREE_OPERAND (ref, 1)))
634               && integer_zerop (DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1))))
635             temp.op0 = TYPE_SIZE (TREE_TYPE (TREE_OPERAND (ref, 1)));
636           else
637             {
638               /* Record field as operand.  */
639               temp.op0 = TREE_OPERAND (ref, 1);
640               temp.op1 = TREE_OPERAND (ref, 2);
641             }
642           break;
643         case ARRAY_RANGE_REF:
644         case ARRAY_REF:
645           /* Record index as operand.  */
646           temp.op0 = TREE_OPERAND (ref, 1);
647           temp.op1 = TREE_OPERAND (ref, 2);
648           temp.op2 = TREE_OPERAND (ref, 3);
649           break;
650         case STRING_CST:
651         case INTEGER_CST:
652         case COMPLEX_CST:
653         case VECTOR_CST:
654         case REAL_CST:
655         case CONSTRUCTOR:
656         case VAR_DECL:
657         case PARM_DECL:
658         case CONST_DECL:
659         case RESULT_DECL:
660         case SSA_NAME:
661         case EXC_PTR_EXPR:
662         case FILTER_EXPR:
663           temp.op0 = ref;
664           break;
665         case ADDR_EXPR:
666           if (is_gimple_min_invariant (ref))
667             {
668               temp.op0 = ref;
669               break;
670             }
671           /* Fallthrough.  */
672           /* These are only interesting for their operands, their
673              existence, and their type.  They will never be the last
674              ref in the chain of references (IE they require an
675              operand), so we don't have to put anything
676              for op* as it will be handled by the iteration  */
677         case IMAGPART_EXPR:
678         case REALPART_EXPR:
679         case VIEW_CONVERT_EXPR:
680           break;
681         default:
682           gcc_unreachable ();
683         }
684       VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
685
686       if (REFERENCE_CLASS_P (ref)
687           || (TREE_CODE (ref) == ADDR_EXPR
688               && !is_gimple_min_invariant (ref)))
689         ref = TREE_OPERAND (ref, 0);
690       else
691         ref = NULL_TREE;
692     }
693 }
694
695 /* Re-create a reference tree from the reference ops OPS.
696    Returns NULL_TREE if the ops were not handled.
697    This routine needs to be kept in sync with copy_reference_ops_from_ref.  */
698
699 static tree
700 get_ref_from_reference_ops (VEC(vn_reference_op_s, heap) *ops)
701 {
702   vn_reference_op_t op;
703   unsigned i;
704   tree ref, *op0_p = &ref;
705
706   for (i = 0; VEC_iterate (vn_reference_op_s, ops, i, op); ++i)
707     {
708       switch (op->opcode)
709         {
710         case CALL_EXPR:
711           return NULL_TREE;
712
713         case ALIGN_INDIRECT_REF:
714         case INDIRECT_REF:
715           *op0_p = build1 (op->opcode, op->type, NULL_TREE);
716           op0_p = &TREE_OPERAND (*op0_p, 0);
717           break;
718
719         case MISALIGNED_INDIRECT_REF:
720           *op0_p = build2 (MISALIGNED_INDIRECT_REF, op->type,
721                            NULL_TREE, op->op0);
722           op0_p = &TREE_OPERAND (*op0_p, 0);
723           break;
724
725         case BIT_FIELD_REF:
726           *op0_p = build3 (BIT_FIELD_REF, op->type, NULL_TREE,
727                            op->op0, op->op1);
728           op0_p = &TREE_OPERAND (*op0_p, 0);
729           break;
730
731         case COMPONENT_REF:
732           *op0_p = build3 (COMPONENT_REF, TREE_TYPE (op->op0), NULL_TREE,
733                            op->op0, op->op1);
734           op0_p = &TREE_OPERAND (*op0_p, 0);
735           break;
736
737         case ARRAY_RANGE_REF:
738         case ARRAY_REF:
739           *op0_p = build4 (op->opcode, op->type, NULL_TREE,
740                            op->op0, op->op1, op->op2);
741           op0_p = &TREE_OPERAND (*op0_p, 0);
742           break;
743
744         case STRING_CST:
745         case INTEGER_CST:
746         case COMPLEX_CST:
747         case VECTOR_CST:
748         case REAL_CST:
749         case CONSTRUCTOR:
750         case VAR_DECL:
751         case PARM_DECL:
752         case CONST_DECL:
753         case RESULT_DECL:
754         case SSA_NAME:
755         case FILTER_EXPR:
756         case EXC_PTR_EXPR:
757           *op0_p = op->op0;
758           break;
759
760         case ADDR_EXPR:
761           if (op->op0 != NULL_TREE)
762             {
763               gcc_assert (is_gimple_min_invariant (op->op0));
764               *op0_p = op->op0;
765               break;
766             }
767           /* Fallthrough.  */
768         case IMAGPART_EXPR:
769         case REALPART_EXPR:
770         case VIEW_CONVERT_EXPR:
771           *op0_p = build1 (op->opcode, op->type, NULL_TREE);
772           op0_p = &TREE_OPERAND (*op0_p, 0);
773           break;
774
775         default:
776           return NULL_TREE;
777         }
778     }
779
780   return ref;
781 }
782
783 /* Copy the operations present in load/store/call REF into RESULT, a vector of
784    vn_reference_op_s's.  */
785
786 void
787 copy_reference_ops_from_call (gimple call,
788                               VEC(vn_reference_op_s, heap) **result)
789 {
790   vn_reference_op_s temp;
791   unsigned i;
792
793   /* Copy the type, opcode, function being called and static chain.  */
794   memset (&temp, 0, sizeof (temp));
795   temp.type = gimple_call_return_type (call);
796   temp.opcode = CALL_EXPR;
797   temp.op0 = gimple_call_fn (call);
798   temp.op1 = gimple_call_chain (call);
799   VEC_safe_push (vn_reference_op_s, heap, *result, &temp);
800
801   /* Copy the call arguments.  As they can be references as well,
802      just chain them together.  */
803   for (i = 0; i < gimple_call_num_args (call); ++i)
804     {
805       tree callarg = gimple_call_arg (call, i);
806       copy_reference_ops_from_ref (callarg, result);
807     }
808 }
809
810 /* Create a vector of vn_reference_op_s structures from REF, a
811    REFERENCE_CLASS_P tree.  The vector is not shared. */
812
813 static VEC(vn_reference_op_s, heap) *
814 create_reference_ops_from_ref (tree ref)
815 {
816   VEC (vn_reference_op_s, heap) *result = NULL;
817
818   copy_reference_ops_from_ref (ref, &result);
819   return result;
820 }
821
822 /* Create a vector of vn_reference_op_s structures from CALL, a
823    call statement.  The vector is not shared.  */
824
825 static VEC(vn_reference_op_s, heap) *
826 create_reference_ops_from_call (gimple call)
827 {
828   VEC (vn_reference_op_s, heap) *result = NULL;
829
830   copy_reference_ops_from_call (call, &result);
831   return result;
832 }
833
834 static VEC(vn_reference_op_s, heap) *shared_lookup_references;
835
836 /* Create a vector of vn_reference_op_s structures from REF, a
837    REFERENCE_CLASS_P tree.  The vector is shared among all callers of
838    this function.  */
839
840 static VEC(vn_reference_op_s, heap) *
841 shared_reference_ops_from_ref (tree ref)
842 {
843   if (!ref)
844     return NULL;
845   VEC_truncate (vn_reference_op_s, shared_lookup_references, 0);
846   copy_reference_ops_from_ref (ref, &shared_lookup_references);
847   return shared_lookup_references;
848 }
849
850 /* Create a vector of vn_reference_op_s structures from CALL, a
851    call statement.  The vector is shared among all callers of
852    this function.  */
853
854 static VEC(vn_reference_op_s, heap) *
855 shared_reference_ops_from_call (gimple call)
856 {
857   if (!call)
858     return NULL;
859   VEC_truncate (vn_reference_op_s, shared_lookup_references, 0);
860   copy_reference_ops_from_call (call, &shared_lookup_references);
861   return shared_lookup_references;
862 }
863
864
865 /* Transform any SSA_NAME's in a vector of vn_reference_op_s
866    structures into their value numbers.  This is done in-place, and
867    the vector passed in is returned.  */
868
869 static VEC (vn_reference_op_s, heap) *
870 valueize_refs (VEC (vn_reference_op_s, heap) *orig)
871 {
872   vn_reference_op_t vro;
873   int i;
874
875   for (i = 0; VEC_iterate (vn_reference_op_s, orig, i, vro); i++)
876     {
877       if (vro->opcode == SSA_NAME
878           || (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME))
879         {
880           vro->op0 = SSA_VAL (vro->op0);
881           /* If it transforms from an SSA_NAME to a constant, update
882              the opcode.  */
883           if (TREE_CODE (vro->op0) != SSA_NAME && vro->opcode == SSA_NAME)
884             vro->opcode = TREE_CODE (vro->op0);
885         }
886       /* TODO: Do we want to valueize op2 and op1 of
887          ARRAY_REF/COMPONENT_REF for Ada */
888       
889     }
890
891   return orig;
892 }
893
894 /* Transform any SSA_NAME's in ORIG, a vector of vuse trees, into
895    their value numbers. This is done in-place, and the vector passed
896    in is returned.  */
897
898 static VEC (tree, gc) *
899 valueize_vuses (VEC (tree, gc) *orig)
900 {
901   bool made_replacement = false;
902   tree vuse;
903   int i;
904
905   for (i = 0; VEC_iterate (tree, orig, i, vuse); i++)
906     {
907       if (vuse != SSA_VAL (vuse))
908         {
909           made_replacement = true;
910           VEC_replace (tree, orig, i, SSA_VAL (vuse));
911         }
912     }
913
914   if (made_replacement && VEC_length (tree, orig) > 1)
915     sort_vuses (orig);
916
917   return orig;
918 }
919
920 /* Return the single reference statement defining all virtual uses
921    in VUSES or NULL_TREE, if there are multiple defining statements.
922    Take into account only definitions that alias REF if following
923    back-edges.  */
924
925 static gimple
926 get_def_ref_stmt_vuses (tree ref, VEC (tree, gc) *vuses)
927 {
928   gimple def_stmt;
929   tree vuse;
930   unsigned int i;
931
932   gcc_assert (VEC_length (tree, vuses) >= 1);
933
934   def_stmt = SSA_NAME_DEF_STMT (VEC_index (tree, vuses, 0));
935   if (gimple_code (def_stmt) == GIMPLE_PHI)
936     {
937       /* We can only handle lookups over PHI nodes for a single
938          virtual operand.  */
939       if (VEC_length (tree, vuses) == 1)
940         {
941           def_stmt = get_single_def_stmt_from_phi (ref, def_stmt);
942           goto cont;
943         }
944       else
945         return NULL;
946     }
947
948   /* Verify each VUSE reaches the same defining stmt.  */
949   for (i = 1; VEC_iterate (tree, vuses, i, vuse); ++i)
950     {
951       gimple tmp = SSA_NAME_DEF_STMT (vuse);
952       if (tmp != def_stmt)
953         return NULL;
954     }
955
956   /* Now see if the definition aliases ref, and loop until it does.  */
957 cont:
958   while (def_stmt
959          && is_gimple_assign (def_stmt)
960          && !refs_may_alias_p (ref, gimple_get_lhs (def_stmt)))
961     def_stmt = get_single_def_stmt_with_phi (ref, def_stmt);
962
963   return def_stmt;
964 }
965
966 /* Lookup a SCCVN reference operation VR in the current hash table.
967    Returns the resulting value number if it exists in the hash table,
968    NULL_TREE otherwise.  VNRESULT will be filled in with the actual
969    vn_reference_t stored in the hashtable if something is found.  */
970
971 static tree
972 vn_reference_lookup_1 (vn_reference_t vr, vn_reference_t *vnresult)
973 {
974   void **slot;
975   hashval_t hash;
976
977   hash = vr->hashcode;
978   slot = htab_find_slot_with_hash (current_info->references, vr,
979                                    hash, NO_INSERT);
980   if (!slot && current_info == optimistic_info)
981     slot = htab_find_slot_with_hash (valid_info->references, vr,
982                                      hash, NO_INSERT);
983   if (slot)
984     {
985       if (vnresult)
986         *vnresult = (vn_reference_t)*slot;
987       return ((vn_reference_t)*slot)->result;
988     }
989   
990   return NULL_TREE;
991 }
992
993
994 /* Lookup a reference operation by it's parts, in the current hash table.
995    Returns the resulting value number if it exists in the hash table,
996    NULL_TREE otherwise.  VNRESULT will be filled in with the actual
997    vn_reference_t stored in the hashtable if something is found.  */
998
999 tree
1000 vn_reference_lookup_pieces (VEC (tree, gc) *vuses,
1001                             VEC (vn_reference_op_s, heap) *operands,
1002                             vn_reference_t *vnresult, bool maywalk)
1003 {
1004   struct vn_reference_s vr1;
1005   tree result;
1006   if (vnresult)
1007     *vnresult = NULL;
1008   
1009   vr1.vuses = valueize_vuses (vuses);
1010   vr1.operands = valueize_refs (operands);
1011   vr1.hashcode = vn_reference_compute_hash (&vr1);
1012   result = vn_reference_lookup_1 (&vr1, vnresult);
1013
1014   /* If there is a single defining statement for all virtual uses, we can
1015      use that, following virtual use-def chains.  */
1016   if (!result
1017       && maywalk
1018       && vr1.vuses
1019       && VEC_length (tree, vr1.vuses) >= 1)
1020     {
1021       tree ref = get_ref_from_reference_ops (operands);
1022       gimple def_stmt;
1023       if (ref
1024           && (def_stmt = get_def_ref_stmt_vuses (ref, vr1.vuses))
1025           && is_gimple_assign (def_stmt))
1026         {
1027           /* We are now at an aliasing definition for the vuses we want to
1028              look up.  Re-do the lookup with the vdefs for this stmt.  */
1029           vdefs_to_vec (def_stmt, &vuses);
1030           vr1.vuses = valueize_vuses (vuses);
1031           vr1.hashcode = vn_reference_compute_hash (&vr1);
1032           result = vn_reference_lookup_1 (&vr1, vnresult);
1033         }
1034     }
1035
1036   return result;
1037 }
1038
1039 /* Lookup OP in the current hash table, and return the resulting value
1040    number if it exists in the hash table.  Return NULL_TREE if it does
1041    not exist in the hash table or if the result field of the structure
1042    was NULL..  VNRESULT will be filled in with the vn_reference_t
1043    stored in the hashtable if one exists.  */
1044
1045 tree
1046 vn_reference_lookup (tree op, VEC (tree, gc) *vuses, bool maywalk,
1047                      vn_reference_t *vnresult)
1048 {
1049   struct vn_reference_s vr1;
1050   tree result;
1051   gimple def_stmt;
1052   if (vnresult)
1053     *vnresult = NULL;
1054
1055   vr1.vuses = valueize_vuses (vuses);
1056   vr1.operands = valueize_refs (shared_reference_ops_from_ref (op));
1057   vr1.hashcode = vn_reference_compute_hash (&vr1);
1058   result = vn_reference_lookup_1 (&vr1, vnresult);
1059
1060   /* If there is a single defining statement for all virtual uses, we can
1061      use that, following virtual use-def chains.  */
1062   if (!result
1063       && maywalk
1064       && vr1.vuses
1065       && VEC_length (tree, vr1.vuses) >= 1
1066       && (def_stmt = get_def_ref_stmt_vuses (op, vr1.vuses))
1067       && is_gimple_assign (def_stmt))
1068     {
1069       /* We are now at an aliasing definition for the vuses we want to
1070          look up.  Re-do the lookup with the vdefs for this stmt.  */
1071       vdefs_to_vec (def_stmt, &vuses);
1072       vr1.vuses = valueize_vuses (vuses);
1073       vr1.hashcode = vn_reference_compute_hash (&vr1);
1074       result = vn_reference_lookup_1 (&vr1, vnresult);
1075     }
1076
1077   return result;
1078 }
1079
1080
1081 /* Insert OP into the current hash table with a value number of
1082    RESULT, and return the resulting reference structure we created.  */
1083
1084 vn_reference_t
1085 vn_reference_insert (tree op, tree result, VEC (tree, gc) *vuses)
1086 {
1087   void **slot;
1088   vn_reference_t vr1;
1089
1090   vr1 = (vn_reference_t) pool_alloc (current_info->references_pool);
1091   if (TREE_CODE (result) == SSA_NAME)
1092     vr1->value_id = VN_INFO (result)->value_id;
1093   else
1094     vr1->value_id = get_or_alloc_constant_value_id (result);
1095   vr1->vuses = valueize_vuses (vuses);
1096   vr1->operands = valueize_refs (create_reference_ops_from_ref (op));
1097   vr1->hashcode = vn_reference_compute_hash (vr1);
1098   vr1->result = TREE_CODE (result) == SSA_NAME ? SSA_VAL (result) : result;
1099
1100   slot = htab_find_slot_with_hash (current_info->references, vr1, vr1->hashcode,
1101                                    INSERT);
1102
1103   /* Because we lookup stores using vuses, and value number failures
1104      using the vdefs (see visit_reference_op_store for how and why),
1105      it's possible that on failure we may try to insert an already
1106      inserted store.  This is not wrong, there is no ssa name for a
1107      store that we could use as a differentiator anyway.  Thus, unlike
1108      the other lookup functions, you cannot gcc_assert (!*slot)
1109      here.  */
1110
1111   /* But free the old slot in case of a collision.  */
1112   if (*slot)
1113     free_reference (*slot);
1114
1115   *slot = vr1;
1116   return vr1;
1117 }
1118
1119 /* Insert a reference by it's pieces into the current hash table with
1120    a value number of RESULT.  Return the resulting reference
1121    structure we created.  */
1122
1123 vn_reference_t
1124 vn_reference_insert_pieces (VEC (tree, gc) *vuses,
1125                             VEC (vn_reference_op_s, heap) *operands,
1126                             tree result, unsigned int value_id)
1127
1128 {
1129   void **slot;
1130   vn_reference_t vr1;
1131
1132   vr1 = (vn_reference_t) pool_alloc (current_info->references_pool);
1133   vr1->value_id =  value_id;
1134   vr1->vuses = valueize_vuses (vuses);
1135   vr1->operands = valueize_refs (operands);
1136   vr1->hashcode = vn_reference_compute_hash (vr1);
1137   if (result && TREE_CODE (result) == SSA_NAME)
1138     result = SSA_VAL (result);
1139   vr1->result = result;
1140
1141   slot = htab_find_slot_with_hash (current_info->references, vr1, vr1->hashcode,
1142                                    INSERT);
1143   
1144   /* At this point we should have all the things inserted that we have
1145   seen before, and we should never try inserting something that
1146   already exists.  */
1147   gcc_assert (!*slot);
1148   if (*slot)
1149     free_reference (*slot);
1150
1151   *slot = vr1;
1152   return vr1;
1153 }
1154
1155 /* Compute and return the hash value for nary operation VBO1.  */
1156
1157 inline hashval_t
1158 vn_nary_op_compute_hash (const vn_nary_op_t vno1)
1159 {
1160   hashval_t hash = 0;
1161   unsigned i;
1162
1163   for (i = 0; i < vno1->length; ++i)
1164     if (TREE_CODE (vno1->op[i]) == SSA_NAME)
1165       vno1->op[i] = SSA_VAL (vno1->op[i]);
1166
1167   if (vno1->length == 2
1168       && commutative_tree_code (vno1->opcode)
1169       && tree_swap_operands_p (vno1->op[0], vno1->op[1], false))
1170     {
1171       tree temp = vno1->op[0];
1172       vno1->op[0] = vno1->op[1];
1173       vno1->op[1] = temp;
1174     }
1175
1176   for (i = 0; i < vno1->length; ++i)
1177     hash += iterative_hash_expr (vno1->op[i], vno1->opcode);
1178
1179   return hash;
1180 }
1181
1182 /* Return the computed hashcode for nary operation P1.  */
1183
1184 static hashval_t
1185 vn_nary_op_hash (const void *p1)
1186 {
1187   const_vn_nary_op_t const vno1 = (const_vn_nary_op_t) p1;
1188   return vno1->hashcode;
1189 }
1190
1191 /* Compare nary operations P1 and P2 and return true if they are
1192    equivalent.  */
1193
1194 int
1195 vn_nary_op_eq (const void *p1, const void *p2)
1196 {
1197   const_vn_nary_op_t const vno1 = (const_vn_nary_op_t) p1;
1198   const_vn_nary_op_t const vno2 = (const_vn_nary_op_t) p2;
1199   unsigned i;
1200
1201   if (vno1->hashcode != vno2->hashcode)
1202     return false;
1203
1204   if (vno1->opcode != vno2->opcode
1205       || !types_compatible_p (vno1->type, vno2->type))
1206     return false;
1207
1208   for (i = 0; i < vno1->length; ++i)
1209     if (!expressions_equal_p (vno1->op[i], vno2->op[i]))
1210       return false;
1211
1212   return true;
1213 }
1214
1215 /* Lookup a n-ary operation by its pieces and return the resulting value
1216    number if it exists in the hash table.  Return NULL_TREE if it does
1217    not exist in the hash table or if the result field of the operation
1218    is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
1219    if it exists.  */
1220
1221 tree
1222 vn_nary_op_lookup_pieces (unsigned int length, enum tree_code code,
1223                           tree type, tree op0, tree op1, tree op2,
1224                           tree op3, vn_nary_op_t *vnresult) 
1225 {
1226   void **slot;
1227   struct vn_nary_op_s vno1;
1228   if (vnresult)
1229     *vnresult = NULL;
1230   vno1.opcode = code;
1231   vno1.length = length;
1232   vno1.type = type;
1233   vno1.op[0] = op0;
1234   vno1.op[1] = op1;
1235   vno1.op[2] = op2;
1236   vno1.op[3] = op3;
1237   vno1.hashcode = vn_nary_op_compute_hash (&vno1);
1238   slot = htab_find_slot_with_hash (current_info->nary, &vno1, vno1.hashcode,
1239                                    NO_INSERT);
1240   if (!slot && current_info == optimistic_info)
1241     slot = htab_find_slot_with_hash (valid_info->nary, &vno1, vno1.hashcode,
1242                                      NO_INSERT);
1243   if (!slot)
1244     return NULL_TREE;
1245   if (vnresult)
1246     *vnresult = (vn_nary_op_t)*slot;
1247   return ((vn_nary_op_t)*slot)->result;
1248 }
1249
1250 /* Lookup OP in the current hash table, and return the resulting value
1251    number if it exists in the hash table.  Return NULL_TREE if it does
1252    not exist in the hash table or if the result field of the operation
1253    is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
1254    if it exists.  */
1255
1256 tree
1257 vn_nary_op_lookup (tree op, vn_nary_op_t *vnresult)
1258 {
1259   void **slot;
1260   struct vn_nary_op_s vno1;
1261   unsigned i;
1262
1263   if (vnresult)
1264     *vnresult = NULL;
1265   vno1.opcode = TREE_CODE (op);
1266   vno1.length = TREE_CODE_LENGTH (TREE_CODE (op));
1267   vno1.type = TREE_TYPE (op);
1268   for (i = 0; i < vno1.length; ++i)
1269     vno1.op[i] = TREE_OPERAND (op, i);
1270   vno1.hashcode = vn_nary_op_compute_hash (&vno1);
1271   slot = htab_find_slot_with_hash (current_info->nary, &vno1, vno1.hashcode,
1272                                    NO_INSERT);
1273   if (!slot && current_info == optimistic_info)
1274     slot = htab_find_slot_with_hash (valid_info->nary, &vno1, vno1.hashcode,
1275                                      NO_INSERT);
1276   if (!slot)
1277     return NULL_TREE;
1278   if (vnresult)
1279     *vnresult = (vn_nary_op_t)*slot;
1280   return ((vn_nary_op_t)*slot)->result;
1281 }
1282
1283 /* Lookup the rhs of STMT in the current hash table, and return the resulting
1284    value number if it exists in the hash table.  Return NULL_TREE if
1285    it does not exist in the hash table.  VNRESULT will contain the
1286    vn_nary_op_t from the hashtable if it exists.  */
1287
1288 tree
1289 vn_nary_op_lookup_stmt (gimple stmt, vn_nary_op_t *vnresult)
1290 {
1291   void **slot;
1292   struct vn_nary_op_s vno1;
1293   unsigned i;
1294
1295   if (vnresult)
1296     *vnresult = NULL;
1297   vno1.opcode = gimple_assign_rhs_code (stmt);
1298   vno1.length = gimple_num_ops (stmt) - 1;
1299   vno1.type = TREE_TYPE (gimple_assign_lhs (stmt));
1300   for (i = 0; i < vno1.length; ++i)
1301     vno1.op[i] = gimple_op (stmt, i + 1);
1302   if (vno1.opcode == REALPART_EXPR
1303       || vno1.opcode == IMAGPART_EXPR
1304       || vno1.opcode == VIEW_CONVERT_EXPR)
1305     vno1.op[0] = TREE_OPERAND (vno1.op[0], 0);
1306   vno1.hashcode = vn_nary_op_compute_hash (&vno1);
1307   slot = htab_find_slot_with_hash (current_info->nary, &vno1, vno1.hashcode,
1308                                    NO_INSERT);
1309   if (!slot && current_info == optimistic_info)
1310     slot = htab_find_slot_with_hash (valid_info->nary, &vno1, vno1.hashcode,
1311                                      NO_INSERT);
1312   if (!slot)
1313     return NULL_TREE;
1314   if (vnresult)
1315     *vnresult = (vn_nary_op_t)*slot;
1316   return ((vn_nary_op_t)*slot)->result;
1317 }
1318
1319 /* Insert a n-ary operation into the current hash table using it's
1320    pieces.  Return the vn_nary_op_t structure we created and put in
1321    the hashtable.  */
1322
1323 vn_nary_op_t
1324 vn_nary_op_insert_pieces (unsigned int length, enum tree_code code,
1325                           tree type, tree op0,
1326                           tree op1, tree op2, tree op3,
1327                           tree result,
1328                           unsigned int value_id) 
1329 {
1330   void **slot;
1331   vn_nary_op_t vno1;
1332
1333   vno1 = (vn_nary_op_t) obstack_alloc (&current_info->nary_obstack,
1334                                        (sizeof (struct vn_nary_op_s)
1335                                         - sizeof (tree) * (4 - length)));
1336   vno1->value_id = value_id;
1337   vno1->opcode = code;
1338   vno1->length = length;
1339   vno1->type = type;
1340   if (length >= 1)
1341     vno1->op[0] = op0;
1342   if (length >= 2)
1343     vno1->op[1] = op1;
1344   if (length >= 3)
1345     vno1->op[2] = op2;
1346   if (length >= 4)
1347     vno1->op[3] = op3;
1348   vno1->result = result;
1349   vno1->hashcode = vn_nary_op_compute_hash (vno1);
1350   slot = htab_find_slot_with_hash (current_info->nary, vno1, vno1->hashcode,
1351                                    INSERT);
1352   gcc_assert (!*slot);
1353
1354   *slot = vno1;
1355   return vno1;
1356   
1357 }
1358
1359 /* Insert OP into the current hash table with a value number of
1360    RESULT.  Return the vn_nary_op_t structure we created and put in
1361    the hashtable.  */
1362
1363 vn_nary_op_t
1364 vn_nary_op_insert (tree op, tree result)
1365 {
1366   unsigned length = TREE_CODE_LENGTH (TREE_CODE (op));
1367   void **slot;
1368   vn_nary_op_t vno1;
1369   unsigned i;
1370
1371   vno1 = (vn_nary_op_t) obstack_alloc (&current_info->nary_obstack,
1372                         (sizeof (struct vn_nary_op_s)
1373                          - sizeof (tree) * (4 - length)));
1374   vno1->value_id = VN_INFO (result)->value_id;
1375   vno1->opcode = TREE_CODE (op);
1376   vno1->length = length;
1377   vno1->type = TREE_TYPE (op);
1378   for (i = 0; i < vno1->length; ++i)
1379     vno1->op[i] = TREE_OPERAND (op, i);
1380   vno1->result = result;
1381   vno1->hashcode = vn_nary_op_compute_hash (vno1);
1382   slot = htab_find_slot_with_hash (current_info->nary, vno1, vno1->hashcode,
1383                                    INSERT);
1384   gcc_assert (!*slot);
1385
1386   *slot = vno1;
1387   return vno1;
1388 }
1389
1390 /* Insert the rhs of STMT into the current hash table with a value number of
1391    RESULT.  */
1392
1393 vn_nary_op_t
1394 vn_nary_op_insert_stmt (gimple stmt, tree result)
1395 {
1396   unsigned length = gimple_num_ops (stmt) - 1;
1397   void **slot;
1398   vn_nary_op_t vno1;
1399   unsigned i;
1400
1401   vno1 = (vn_nary_op_t) obstack_alloc (&current_info->nary_obstack,
1402                                        (sizeof (struct vn_nary_op_s)
1403                                         - sizeof (tree) * (4 - length)));
1404   vno1->value_id = VN_INFO (result)->value_id;
1405   vno1->opcode = gimple_assign_rhs_code (stmt);
1406   vno1->length = length;
1407   vno1->type = TREE_TYPE (gimple_assign_lhs (stmt));
1408   for (i = 0; i < vno1->length; ++i)
1409     vno1->op[i] = gimple_op (stmt, i + 1);
1410   if (vno1->opcode == REALPART_EXPR
1411       || vno1->opcode == IMAGPART_EXPR
1412       || vno1->opcode == VIEW_CONVERT_EXPR)
1413     vno1->op[0] = TREE_OPERAND (vno1->op[0], 0);
1414   vno1->result = result;
1415   vno1->hashcode = vn_nary_op_compute_hash (vno1);
1416   slot = htab_find_slot_with_hash (current_info->nary, vno1, vno1->hashcode,
1417                                    INSERT);
1418   gcc_assert (!*slot);
1419
1420   *slot = vno1;
1421   return vno1;
1422 }
1423
1424 /* Compute a hashcode for PHI operation VP1 and return it.  */
1425
1426 static inline hashval_t
1427 vn_phi_compute_hash (vn_phi_t vp1)
1428 {
1429   hashval_t result = 0;
1430   int i;
1431   tree phi1op;
1432   tree type;
1433
1434   result = vp1->block->index;
1435
1436   /* If all PHI arguments are constants we need to distinguish
1437      the PHI node via its type.  */
1438   type = TREE_TYPE (VEC_index (tree, vp1->phiargs, 0));
1439   result += (INTEGRAL_TYPE_P (type)
1440              + (INTEGRAL_TYPE_P (type)
1441                 ? TYPE_PRECISION (type) + TYPE_UNSIGNED (type) : 0));
1442
1443   for (i = 0; VEC_iterate (tree, vp1->phiargs, i, phi1op); i++)
1444     {
1445       if (phi1op == VN_TOP)
1446         continue;
1447       result += iterative_hash_expr (phi1op, result);
1448     }
1449
1450   return result;
1451 }
1452
1453 /* Return the computed hashcode for phi operation P1.  */
1454
1455 static hashval_t
1456 vn_phi_hash (const void *p1)
1457 {
1458   const_vn_phi_t const vp1 = (const_vn_phi_t) p1;
1459   return vp1->hashcode;
1460 }
1461
1462 /* Compare two phi entries for equality, ignoring VN_TOP arguments.  */
1463
1464 static int
1465 vn_phi_eq (const void *p1, const void *p2)
1466 {
1467   const_vn_phi_t const vp1 = (const_vn_phi_t) p1;
1468   const_vn_phi_t const vp2 = (const_vn_phi_t) p2;
1469
1470   if (vp1->hashcode != vp2->hashcode)
1471     return false;
1472
1473   if (vp1->block == vp2->block)
1474     {
1475       int i;
1476       tree phi1op;
1477
1478       /* If the PHI nodes do not have compatible types
1479          they are not the same.  */
1480       if (!types_compatible_p (TREE_TYPE (VEC_index (tree, vp1->phiargs, 0)),
1481                                TREE_TYPE (VEC_index (tree, vp2->phiargs, 0))))
1482         return false;
1483
1484       /* Any phi in the same block will have it's arguments in the
1485          same edge order, because of how we store phi nodes.  */
1486       for (i = 0; VEC_iterate (tree, vp1->phiargs, i, phi1op); i++)
1487         {
1488           tree phi2op = VEC_index (tree, vp2->phiargs, i);
1489           if (phi1op == VN_TOP || phi2op == VN_TOP)
1490             continue;
1491           if (!expressions_equal_p (phi1op, phi2op))
1492             return false;
1493         }
1494       return true;
1495     }
1496   return false;
1497 }
1498
1499 static VEC(tree, heap) *shared_lookup_phiargs;
1500
1501 /* Lookup PHI in the current hash table, and return the resulting
1502    value number if it exists in the hash table.  Return NULL_TREE if
1503    it does not exist in the hash table. */
1504
1505 static tree
1506 vn_phi_lookup (gimple phi)
1507 {
1508   void **slot;
1509   struct vn_phi_s vp1;
1510   unsigned i;
1511
1512   VEC_truncate (tree, shared_lookup_phiargs, 0);
1513
1514   /* Canonicalize the SSA_NAME's to their value number.  */
1515   for (i = 0; i < gimple_phi_num_args (phi); i++)
1516     {
1517       tree def = PHI_ARG_DEF (phi, i);
1518       def = TREE_CODE (def) == SSA_NAME ? SSA_VAL (def) : def;
1519       VEC_safe_push (tree, heap, shared_lookup_phiargs, def);
1520     }
1521   vp1.phiargs = shared_lookup_phiargs;
1522   vp1.block = gimple_bb (phi);
1523   vp1.hashcode = vn_phi_compute_hash (&vp1);
1524   slot = htab_find_slot_with_hash (current_info->phis, &vp1, vp1.hashcode,
1525                                    NO_INSERT);
1526   if (!slot && current_info == optimistic_info)
1527     slot = htab_find_slot_with_hash (valid_info->phis, &vp1, vp1.hashcode,
1528                                      NO_INSERT);
1529   if (!slot)
1530     return NULL_TREE;
1531   return ((vn_phi_t)*slot)->result;
1532 }
1533
1534 /* Insert PHI into the current hash table with a value number of
1535    RESULT.  */
1536
1537 static vn_phi_t
1538 vn_phi_insert (gimple phi, tree result)
1539 {
1540   void **slot;
1541   vn_phi_t vp1 = (vn_phi_t) pool_alloc (current_info->phis_pool);
1542   unsigned i;
1543   VEC (tree, heap) *args = NULL;
1544
1545   /* Canonicalize the SSA_NAME's to their value number.  */
1546   for (i = 0; i < gimple_phi_num_args (phi); i++)
1547     {
1548       tree def = PHI_ARG_DEF (phi, i);
1549       def = TREE_CODE (def) == SSA_NAME ? SSA_VAL (def) : def;
1550       VEC_safe_push (tree, heap, args, def);
1551     }
1552   vp1->value_id = VN_INFO (result)->value_id;
1553   vp1->phiargs = args;
1554   vp1->block = gimple_bb (phi);
1555   vp1->result = result;
1556   vp1->hashcode = vn_phi_compute_hash (vp1);
1557
1558   slot = htab_find_slot_with_hash (current_info->phis, vp1, vp1->hashcode,
1559                                    INSERT);
1560
1561   /* Because we iterate over phi operations more than once, it's
1562      possible the slot might already exist here, hence no assert.*/
1563   *slot = vp1;
1564   return vp1;
1565 }
1566
1567
1568 /* Print set of components in strongly connected component SCC to OUT. */
1569
1570 static void
1571 print_scc (FILE *out, VEC (tree, heap) *scc)
1572 {
1573   tree var;
1574   unsigned int i;
1575
1576   fprintf (out, "SCC consists of: ");
1577   for (i = 0; VEC_iterate (tree, scc, i, var); i++)
1578     {
1579       print_generic_expr (out, var, 0);
1580       fprintf (out, " ");
1581     }
1582   fprintf (out, "\n");
1583 }
1584
1585 /* Set the value number of FROM to TO, return true if it has changed
1586    as a result.  */
1587
1588 static inline bool
1589 set_ssa_val_to (tree from, tree to)
1590 {
1591   tree currval;
1592
1593   if (from != to
1594       && TREE_CODE (to) == SSA_NAME
1595       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (to))
1596     to = from;
1597
1598   /* The only thing we allow as value numbers are VN_TOP, ssa_names
1599      and invariants.  So assert that here.  */
1600   gcc_assert (to != NULL_TREE
1601               && (to == VN_TOP
1602                   || TREE_CODE (to) == SSA_NAME
1603                   || is_gimple_min_invariant (to)));
1604
1605   if (dump_file && (dump_flags & TDF_DETAILS))
1606     {
1607       fprintf (dump_file, "Setting value number of ");
1608       print_generic_expr (dump_file, from, 0);
1609       fprintf (dump_file, " to ");
1610       print_generic_expr (dump_file, to, 0);
1611     }
1612
1613   currval = SSA_VAL (from);
1614
1615   if (currval != to  && !operand_equal_p (currval, to, OEP_PURE_SAME))
1616     {
1617       SSA_VAL (from) = to;
1618       if (dump_file && (dump_flags & TDF_DETAILS))
1619         fprintf (dump_file, " (changed)\n");
1620       return true;
1621     }
1622   if (dump_file && (dump_flags & TDF_DETAILS))
1623     fprintf (dump_file, "\n");
1624   return false;
1625 }
1626
1627 /* Set all definitions in STMT to value number to themselves.
1628    Return true if a value number changed. */
1629
1630 static bool
1631 defs_to_varying (gimple stmt)
1632 {
1633   bool changed = false;
1634   ssa_op_iter iter;
1635   def_operand_p defp;
1636
1637   FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_ALL_DEFS)
1638     {
1639       tree def = DEF_FROM_PTR (defp);
1640
1641       VN_INFO (def)->use_processed = true;
1642       changed |= set_ssa_val_to (def, def);
1643     }
1644   return changed;
1645 }
1646
1647 static bool expr_has_constants (tree expr);
1648 static tree valueize_expr (tree expr);
1649
1650 /* Visit a copy between LHS and RHS, return true if the value number
1651    changed.  */
1652
1653 static bool
1654 visit_copy (tree lhs, tree rhs)
1655 {
1656   /* Follow chains of copies to their destination.  */
1657   while (TREE_CODE (rhs) == SSA_NAME
1658          && SSA_VAL (rhs) != rhs)
1659     rhs = SSA_VAL (rhs);
1660
1661   /* The copy may have a more interesting constant filled expression
1662      (we don't, since we know our RHS is just an SSA name).  */
1663   if (TREE_CODE (rhs) == SSA_NAME)
1664     {
1665       VN_INFO (lhs)->has_constants = VN_INFO (rhs)->has_constants;
1666       VN_INFO (lhs)->expr = VN_INFO (rhs)->expr;
1667     }
1668
1669   return set_ssa_val_to (lhs, rhs);
1670 }
1671
1672 /* Visit a unary operator RHS, value number it, and return true if the
1673    value number of LHS has changed as a result.  */
1674
1675 static bool
1676 visit_unary_op (tree lhs, gimple stmt)
1677 {
1678   bool changed = false;
1679   tree result = vn_nary_op_lookup_stmt (stmt, NULL);
1680
1681   if (result)
1682     {
1683       changed = set_ssa_val_to (lhs, result);
1684     }
1685   else
1686     {
1687       changed = set_ssa_val_to (lhs, lhs);
1688       vn_nary_op_insert_stmt (stmt, lhs);
1689     }
1690
1691   return changed;
1692 }
1693
1694 /* Visit a binary operator RHS, value number it, and return true if the
1695    value number of LHS has changed as a result.  */
1696
1697 static bool
1698 visit_binary_op (tree lhs, gimple stmt)
1699 {
1700   bool changed = false;
1701   tree result = vn_nary_op_lookup_stmt (stmt, NULL);
1702
1703   if (result)
1704     {
1705       changed = set_ssa_val_to (lhs, result);
1706     }
1707   else
1708     {
1709       changed = set_ssa_val_to (lhs, lhs);
1710       vn_nary_op_insert_stmt (stmt, lhs);
1711     }
1712
1713   return changed;
1714 }
1715
1716 /* Visit a call STMT storing into LHS.  Return true if the value number
1717    of the LHS has changed as a result.  */
1718
1719 static bool
1720 visit_reference_op_call (tree lhs, gimple stmt)
1721 {
1722   bool changed = false;
1723   struct vn_reference_s vr1;
1724   tree result;
1725
1726   vr1.vuses = valueize_vuses (shared_vuses_from_stmt (stmt));
1727   vr1.operands = valueize_refs (shared_reference_ops_from_call (stmt));
1728   vr1.hashcode = vn_reference_compute_hash (&vr1);
1729   result = vn_reference_lookup_1 (&vr1, NULL);
1730   if (result)
1731     {
1732       changed = set_ssa_val_to (lhs, result);
1733       if (TREE_CODE (result) == SSA_NAME
1734           && VN_INFO (result)->has_constants)
1735         VN_INFO (lhs)->has_constants = true;
1736     }
1737   else
1738     {
1739       void **slot;
1740       vn_reference_t vr2;
1741       changed = set_ssa_val_to (lhs, lhs);
1742       vr2 = (vn_reference_t) pool_alloc (current_info->references_pool);
1743       vr2->vuses = valueize_vuses (copy_vuses_from_stmt (stmt));
1744       vr2->operands = valueize_refs (create_reference_ops_from_call (stmt));
1745       vr2->hashcode = vr1.hashcode;
1746       vr2->result = lhs;
1747       slot = htab_find_slot_with_hash (current_info->references,
1748                                        vr2, vr2->hashcode, INSERT);
1749       if (*slot)
1750         free_reference (*slot);
1751       *slot = vr2;
1752     }
1753
1754   return changed;
1755 }
1756
1757 /* Visit a load from a reference operator RHS, part of STMT, value number it,
1758    and return true if the value number of the LHS has changed as a result.  */
1759
1760 static bool
1761 visit_reference_op_load (tree lhs, tree op, gimple stmt)
1762 {
1763   bool changed = false;
1764   tree result = vn_reference_lookup (op, shared_vuses_from_stmt (stmt), true,
1765                                      NULL);
1766
1767   /* We handle type-punning through unions by value-numbering based
1768      on offset and size of the access.  Be prepared to handle a
1769      type-mismatch here via creating a VIEW_CONVERT_EXPR.  */
1770   if (result
1771       && !useless_type_conversion_p (TREE_TYPE (result), TREE_TYPE (op)))
1772     {
1773       /* We will be setting the value number of lhs to the value number
1774          of VIEW_CONVERT_EXPR <TREE_TYPE (result)> (result).
1775          So first simplify and lookup this expression to see if it
1776          is already available.  */
1777       tree val = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (op), result);
1778       if ((CONVERT_EXPR_P (val)
1779            || TREE_CODE (val) == VIEW_CONVERT_EXPR)
1780           && TREE_CODE (TREE_OPERAND (val, 0)) == SSA_NAME)
1781         {
1782           tree tem = valueize_expr (vn_get_expr_for (TREE_OPERAND (val, 0)));
1783           if ((CONVERT_EXPR_P (tem)
1784                || TREE_CODE (tem) == VIEW_CONVERT_EXPR)
1785               && (tem = fold_unary_ignore_overflow (TREE_CODE (val),
1786                                                     TREE_TYPE (val), tem)))
1787             val = tem;
1788         }
1789       result = val;
1790       if (!is_gimple_min_invariant (val)
1791           && TREE_CODE (val) != SSA_NAME)
1792         result = vn_nary_op_lookup (val, NULL);
1793       /* If the expression is not yet available, value-number lhs to
1794          a new SSA_NAME we create.  */
1795       if (!result && may_insert)
1796         {
1797           result = make_ssa_name (SSA_NAME_VAR (lhs), NULL);
1798           /* Initialize value-number information properly.  */
1799           VN_INFO_GET (result)->valnum = result;
1800           VN_INFO (result)->value_id = get_next_value_id ();
1801           VN_INFO (result)->expr = val;
1802           VN_INFO (result)->has_constants = expr_has_constants (val);
1803           VN_INFO (result)->needs_insertion = true;
1804           /* As all "inserted" statements are singleton SCCs, insert
1805              to the valid table.  This is strictly needed to
1806              avoid re-generating new value SSA_NAMEs for the same
1807              expression during SCC iteration over and over (the
1808              optimistic table gets cleared after each iteration).
1809              We do not need to insert into the optimistic table, as
1810              lookups there will fall back to the valid table.  */
1811           if (current_info == optimistic_info)
1812             {
1813               current_info = valid_info;
1814               vn_nary_op_insert (val, result);
1815               current_info = optimistic_info;
1816             }
1817           else
1818             vn_nary_op_insert (val, result);
1819           if (dump_file && (dump_flags & TDF_DETAILS))
1820             {
1821               fprintf (dump_file, "Inserting name ");
1822               print_generic_expr (dump_file, result, 0);
1823               fprintf (dump_file, " for expression ");
1824               print_generic_expr (dump_file, val, 0);
1825               fprintf (dump_file, "\n");
1826             }
1827         }
1828     }
1829
1830   if (result)
1831     {
1832       changed = set_ssa_val_to (lhs, result);
1833       if (TREE_CODE (result) == SSA_NAME
1834           && VN_INFO (result)->has_constants)
1835         {
1836           VN_INFO (lhs)->expr = VN_INFO (result)->expr;
1837           VN_INFO (lhs)->has_constants = true;
1838         }
1839     }
1840   else
1841     {
1842       changed = set_ssa_val_to (lhs, lhs);
1843       vn_reference_insert (op, lhs, copy_vuses_from_stmt (stmt));
1844     }
1845
1846   return changed;
1847 }
1848
1849
1850 /* Visit a store to a reference operator LHS, part of STMT, value number it,
1851    and return true if the value number of the LHS has changed as a result.  */
1852
1853 static bool
1854 visit_reference_op_store (tree lhs, tree op, gimple stmt)
1855 {
1856   bool changed = false;
1857   tree result;
1858   bool resultsame = false;
1859
1860   /* First we want to lookup using the *vuses* from the store and see
1861      if there the last store to this location with the same address
1862      had the same value.
1863
1864      The vuses represent the memory state before the store.  If the
1865      memory state, address, and value of the store is the same as the
1866      last store to this location, then this store will produce the
1867      same memory state as that store.
1868
1869      In this case the vdef versions for this store are value numbered to those
1870      vuse versions, since they represent the same memory state after
1871      this store.
1872
1873      Otherwise, the vdefs for the store are used when inserting into
1874      the table, since the store generates a new memory state.  */
1875
1876   result = vn_reference_lookup (lhs, shared_vuses_from_stmt (stmt), false,
1877                                 NULL);
1878
1879   if (result)
1880     {
1881       if (TREE_CODE (result) == SSA_NAME)
1882         result = SSA_VAL (result);
1883       if (TREE_CODE (op) == SSA_NAME)
1884         op = SSA_VAL (op);
1885       resultsame = expressions_equal_p (result, op);
1886     }
1887
1888   if (!result || !resultsame)
1889     {
1890       VEC(tree, gc) *vdefs = copy_vdefs_from_stmt (stmt);
1891       int i;
1892       tree vdef;
1893
1894       if (dump_file && (dump_flags & TDF_DETAILS))
1895         {
1896           fprintf (dump_file, "No store match\n");
1897           fprintf (dump_file, "Value numbering store ");
1898           print_generic_expr (dump_file, lhs, 0);
1899           fprintf (dump_file, " to ");
1900           print_generic_expr (dump_file, op, 0);
1901           fprintf (dump_file, "\n");
1902         }
1903       /* Have to set value numbers before insert, since insert is
1904          going to valueize the references in-place.  */
1905       for (i = 0; VEC_iterate (tree, vdefs, i, vdef); i++)
1906         {
1907           VN_INFO (vdef)->use_processed = true;
1908           changed |= set_ssa_val_to (vdef, vdef);
1909         }
1910
1911       /* Do not insert structure copies into the tables.  */
1912       if (is_gimple_min_invariant (op)
1913           || is_gimple_reg (op))
1914         vn_reference_insert (lhs, op, vdefs);
1915     }
1916   else
1917     {
1918       /* We had a match, so value number the vdefs to have the value
1919          number of the vuses they came from.  */
1920       ssa_op_iter op_iter;
1921       def_operand_p var;
1922       vuse_vec_p vv;
1923
1924       if (dump_file && (dump_flags & TDF_DETAILS))
1925         fprintf (dump_file, "Store matched earlier value,"
1926                  "value numbering store vdefs to matching vuses.\n");
1927
1928       FOR_EACH_SSA_VDEF_OPERAND (var, vv, stmt, op_iter)
1929         {
1930           tree def = DEF_FROM_PTR (var);
1931           tree use;
1932
1933           /* Uh, if the vuse is a multiuse, we can't really do much
1934              here, sadly, since we don't know which value number of
1935              which vuse to use.  */
1936           if (VUSE_VECT_NUM_ELEM (*vv) != 1)
1937             use = def;
1938           else
1939             use = VUSE_ELEMENT_VAR (*vv, 0);
1940
1941           VN_INFO (def)->use_processed = true;
1942           changed |= set_ssa_val_to (def, SSA_VAL (use));
1943         }
1944     }
1945
1946   return changed;
1947 }
1948
1949 /* Visit and value number PHI, return true if the value number
1950    changed.  */
1951
1952 static bool
1953 visit_phi (gimple phi)
1954 {
1955   bool changed = false;
1956   tree result;
1957   tree sameval = VN_TOP;
1958   bool allsame = true;
1959   unsigned i;
1960
1961   /* TODO: We could check for this in init_sccvn, and replace this
1962      with a gcc_assert.  */
1963   if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
1964     return set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
1965
1966   /* See if all non-TOP arguments have the same value.  TOP is
1967      equivalent to everything, so we can ignore it.  */
1968   for (i = 0; i < gimple_phi_num_args (phi); i++)
1969     {
1970       tree def = PHI_ARG_DEF (phi, i);
1971
1972       if (TREE_CODE (def) == SSA_NAME)
1973         def = SSA_VAL (def);
1974       if (def == VN_TOP)
1975         continue;
1976       if (sameval == VN_TOP)
1977         {
1978           sameval = def;
1979         }
1980       else
1981         {
1982           if (!expressions_equal_p (def, sameval))
1983             {
1984               allsame = false;
1985               break;
1986             }
1987         }
1988     }
1989
1990   /* If all value numbered to the same value, the phi node has that
1991      value.  */
1992   if (allsame)
1993     {
1994       if (is_gimple_min_invariant (sameval))
1995         {
1996           VN_INFO (PHI_RESULT (phi))->has_constants = true;
1997           VN_INFO (PHI_RESULT (phi))->expr = sameval;
1998         }
1999       else
2000         {
2001           VN_INFO (PHI_RESULT (phi))->has_constants = false;
2002           VN_INFO (PHI_RESULT (phi))->expr = sameval;
2003         }
2004
2005       if (TREE_CODE (sameval) == SSA_NAME)
2006         return visit_copy (PHI_RESULT (phi), sameval);
2007
2008       return set_ssa_val_to (PHI_RESULT (phi), sameval);
2009     }
2010
2011   /* Otherwise, see if it is equivalent to a phi node in this block.  */
2012   result = vn_phi_lookup (phi);
2013   if (result)
2014     {
2015       if (TREE_CODE (result) == SSA_NAME)
2016         changed = visit_copy (PHI_RESULT (phi), result);
2017       else
2018         changed = set_ssa_val_to (PHI_RESULT (phi), result);
2019     }
2020   else
2021     {
2022       vn_phi_insert (phi, PHI_RESULT (phi));
2023       VN_INFO (PHI_RESULT (phi))->has_constants = false;
2024       VN_INFO (PHI_RESULT (phi))->expr = PHI_RESULT (phi);
2025       changed = set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
2026     }
2027
2028   return changed;
2029 }
2030
2031 /* Return true if EXPR contains constants.  */
2032
2033 static bool
2034 expr_has_constants (tree expr)
2035 {
2036   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
2037     {
2038     case tcc_unary:
2039       return is_gimple_min_invariant (TREE_OPERAND (expr, 0));
2040
2041     case tcc_binary:
2042       return is_gimple_min_invariant (TREE_OPERAND (expr, 0))
2043         || is_gimple_min_invariant (TREE_OPERAND (expr, 1));
2044       /* Constants inside reference ops are rarely interesting, but
2045          it can take a lot of looking to find them.  */
2046     case tcc_reference:
2047     case tcc_declaration:
2048       return false;
2049     default:
2050       return is_gimple_min_invariant (expr);
2051     }
2052   return false;
2053 }
2054
2055 /* Return true if STMT contains constants.  */
2056
2057 static bool
2058 stmt_has_constants (gimple stmt)
2059 {
2060   if (gimple_code (stmt) != GIMPLE_ASSIGN)
2061     return false;
2062
2063   switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
2064     {
2065     case GIMPLE_UNARY_RHS:
2066       return is_gimple_min_invariant (gimple_assign_rhs1 (stmt));
2067
2068     case GIMPLE_BINARY_RHS:
2069       return (is_gimple_min_invariant (gimple_assign_rhs1 (stmt))
2070               || is_gimple_min_invariant (gimple_assign_rhs2 (stmt)));
2071     case GIMPLE_SINGLE_RHS:
2072       /* Constants inside reference ops are rarely interesting, but
2073          it can take a lot of looking to find them.  */
2074       return is_gimple_min_invariant (gimple_assign_rhs1 (stmt));
2075     default:
2076       gcc_unreachable ();
2077     }
2078   return false;
2079 }
2080
2081 /* Replace SSA_NAMES in expr with their value numbers, and return the
2082    result.
2083    This is performed in place. */
2084
2085 static tree
2086 valueize_expr (tree expr)
2087 {
2088   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
2089     {
2090     case tcc_unary:
2091       if (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
2092           && SSA_VAL (TREE_OPERAND (expr, 0)) != VN_TOP)
2093         TREE_OPERAND (expr, 0) = SSA_VAL (TREE_OPERAND (expr, 0));
2094       break;
2095     case tcc_binary:
2096       if (TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME
2097           && SSA_VAL (TREE_OPERAND (expr, 0)) != VN_TOP)
2098         TREE_OPERAND (expr, 0) = SSA_VAL (TREE_OPERAND (expr, 0));
2099       if (TREE_CODE (TREE_OPERAND (expr, 1)) == SSA_NAME
2100           && SSA_VAL (TREE_OPERAND (expr, 1)) != VN_TOP)
2101         TREE_OPERAND (expr, 1) = SSA_VAL (TREE_OPERAND (expr, 1));
2102       break;
2103     default:
2104       break;
2105     }
2106   return expr;
2107 }
2108
2109 /* Simplify the binary expression RHS, and return the result if
2110    simplified. */
2111
2112 static tree
2113 simplify_binary_expression (gimple stmt)
2114 {
2115   tree result = NULL_TREE;
2116   tree op0 = gimple_assign_rhs1 (stmt);
2117   tree op1 = gimple_assign_rhs2 (stmt);
2118
2119   /* This will not catch every single case we could combine, but will
2120      catch those with constants.  The goal here is to simultaneously
2121      combine constants between expressions, but avoid infinite
2122      expansion of expressions during simplification.  */
2123   if (TREE_CODE (op0) == SSA_NAME)
2124     {
2125       if (VN_INFO (op0)->has_constants
2126           || TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
2127         op0 = valueize_expr (vn_get_expr_for (op0));
2128       else if (SSA_VAL (op0) != VN_TOP && SSA_VAL (op0) != op0)
2129         op0 = SSA_VAL (op0);
2130     }
2131
2132   if (TREE_CODE (op1) == SSA_NAME)
2133     {
2134       if (VN_INFO (op1)->has_constants)
2135         op1 = valueize_expr (vn_get_expr_for (op1));
2136       else if (SSA_VAL (op1) != VN_TOP && SSA_VAL (op1) != op1)
2137         op1 = SSA_VAL (op1);
2138     }
2139
2140   /* Avoid folding if nothing changed.  */
2141   if (op0 == gimple_assign_rhs1 (stmt)
2142       && op1 == gimple_assign_rhs2 (stmt))
2143     return NULL_TREE;
2144
2145   fold_defer_overflow_warnings ();
2146
2147   result = fold_binary (gimple_assign_rhs_code (stmt),
2148                         TREE_TYPE (gimple_get_lhs (stmt)), op0, op1);
2149   if (result)
2150     STRIP_USELESS_TYPE_CONVERSION (result);
2151
2152   fold_undefer_overflow_warnings (result && valid_gimple_rhs_p (result),
2153                                   stmt, 0);
2154
2155   /* Make sure result is not a complex expression consisting
2156      of operators of operators (IE (a + b) + (a + c))
2157      Otherwise, we will end up with unbounded expressions if
2158      fold does anything at all.  */
2159   if (result && valid_gimple_rhs_p (result))
2160     return result;
2161
2162   return NULL_TREE;
2163 }
2164
2165 /* Simplify the unary expression RHS, and return the result if
2166    simplified. */
2167
2168 static tree
2169 simplify_unary_expression (gimple stmt)
2170 {
2171   tree result = NULL_TREE;
2172   tree orig_op0, op0 = gimple_assign_rhs1 (stmt);
2173
2174   /* We handle some tcc_reference codes here that are all
2175      GIMPLE_ASSIGN_SINGLE codes.  */
2176   if (gimple_assign_rhs_code (stmt) == REALPART_EXPR
2177       || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR
2178       || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR)
2179     op0 = TREE_OPERAND (op0, 0);
2180
2181   if (TREE_CODE (op0) != SSA_NAME)
2182     return NULL_TREE;
2183
2184   orig_op0 = op0;
2185   if (VN_INFO (op0)->has_constants)
2186     op0 = valueize_expr (vn_get_expr_for (op0));
2187   else if (gimple_assign_cast_p (stmt)
2188            || gimple_assign_rhs_code (stmt) == REALPART_EXPR
2189            || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR
2190            || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR)
2191     {
2192       /* We want to do tree-combining on conversion-like expressions.
2193          Make sure we feed only SSA_NAMEs or constants to fold though.  */
2194       tree tem = valueize_expr (vn_get_expr_for (op0));
2195       if (UNARY_CLASS_P (tem)
2196           || BINARY_CLASS_P (tem)
2197           || TREE_CODE (tem) == VIEW_CONVERT_EXPR
2198           || TREE_CODE (tem) == SSA_NAME
2199           || is_gimple_min_invariant (tem))
2200         op0 = tem;
2201     }
2202
2203   /* Avoid folding if nothing changed, but remember the expression.  */
2204   if (op0 == orig_op0)
2205     return NULL_TREE;
2206
2207   result = fold_unary_ignore_overflow (gimple_assign_rhs_code (stmt),
2208                                        gimple_expr_type (stmt), op0);
2209   if (result)
2210     {
2211       STRIP_USELESS_TYPE_CONVERSION (result);
2212       if (valid_gimple_rhs_p (result))
2213         return result;
2214     }
2215
2216   return NULL_TREE;
2217 }
2218
2219 /* Try to simplify RHS using equivalences and constant folding.  */
2220
2221 static tree
2222 try_to_simplify (gimple stmt)
2223 {
2224   tree tem;
2225
2226   /* For stores we can end up simplifying a SSA_NAME rhs.  Just return
2227      in this case, there is no point in doing extra work.  */
2228   if (gimple_assign_copy_p (stmt)
2229       && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
2230     return NULL_TREE;
2231
2232   switch (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)))
2233     {
2234     case tcc_declaration:
2235       tem = get_symbol_constant_value (gimple_assign_rhs1 (stmt));
2236       if (tem)
2237         return tem;
2238       break;
2239
2240     case tcc_reference:
2241       /* Do not do full-blown reference lookup here, but simplify
2242          reads from constant aggregates.  */
2243       tem = fold_const_aggregate_ref (gimple_assign_rhs1 (stmt));
2244       if (tem)
2245         return tem;
2246
2247       /* Fallthrough for some codes that can operate on registers.  */
2248       if (!(TREE_CODE (gimple_assign_rhs1 (stmt)) == REALPART_EXPR
2249             || TREE_CODE (gimple_assign_rhs1 (stmt)) == IMAGPART_EXPR
2250             || TREE_CODE (gimple_assign_rhs1 (stmt)) == VIEW_CONVERT_EXPR))
2251         break;
2252       /* We could do a little more with unary ops, if they expand
2253          into binary ops, but it's debatable whether it is worth it. */
2254     case tcc_unary:
2255       return simplify_unary_expression (stmt);
2256       break;
2257     case tcc_comparison:
2258     case tcc_binary:
2259       return simplify_binary_expression (stmt);
2260       break;
2261     default:
2262       break;
2263     }
2264
2265   return NULL_TREE;
2266 }
2267
2268 /* Visit and value number USE, return true if the value number
2269    changed. */
2270
2271 static bool
2272 visit_use (tree use)
2273 {
2274   bool changed = false;
2275   gimple stmt = SSA_NAME_DEF_STMT (use);
2276
2277   VN_INFO (use)->use_processed = true;
2278
2279   gcc_assert (!SSA_NAME_IN_FREE_LIST (use));
2280   if (dump_file && (dump_flags & TDF_DETAILS)
2281       && !SSA_NAME_IS_DEFAULT_DEF (use))
2282     {
2283       fprintf (dump_file, "Value numbering ");
2284       print_generic_expr (dump_file, use, 0);
2285       fprintf (dump_file, " stmt = ");
2286       print_gimple_stmt (dump_file, stmt, 0, 0);
2287     }
2288
2289   /* Handle uninitialized uses.  */
2290   if (SSA_NAME_IS_DEFAULT_DEF (use))
2291     changed = set_ssa_val_to (use, use);
2292   else
2293     {
2294       if (gimple_code (stmt) == GIMPLE_PHI)
2295         changed = visit_phi (stmt);
2296       else if (!gimple_has_lhs (stmt)
2297                || gimple_has_volatile_ops (stmt)
2298                || stmt_could_throw_p (stmt))
2299         changed = defs_to_varying (stmt);
2300       else if (is_gimple_assign (stmt))
2301         {
2302           tree lhs = gimple_assign_lhs (stmt);
2303           tree simplified;
2304
2305           /* Shortcut for copies. Simplifying copies is pointless,
2306              since we copy the expression and value they represent.  */
2307           if (gimple_assign_copy_p (stmt)
2308               && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
2309               && TREE_CODE (lhs) == SSA_NAME)
2310             {
2311               changed = visit_copy (lhs, gimple_assign_rhs1 (stmt));
2312               goto done;
2313             }
2314           simplified = try_to_simplify (stmt);
2315           if (simplified)
2316             {
2317               if (dump_file && (dump_flags & TDF_DETAILS))
2318                 {
2319                   fprintf (dump_file, "RHS ");
2320                   print_gimple_expr (dump_file, stmt, 0, 0);
2321                   fprintf (dump_file, " simplified to ");
2322                   print_generic_expr (dump_file, simplified, 0);
2323                   if (TREE_CODE (lhs) == SSA_NAME)
2324                     fprintf (dump_file, " has constants %d\n",
2325                              expr_has_constants (simplified));
2326                   else
2327                     fprintf (dump_file, "\n");
2328                 }
2329             }
2330           /* Setting value numbers to constants will occasionally
2331              screw up phi congruence because constants are not
2332              uniquely associated with a single ssa name that can be
2333              looked up.  */
2334           if (simplified
2335               && is_gimple_min_invariant (simplified)
2336               && TREE_CODE (lhs) == SSA_NAME)
2337             {
2338               VN_INFO (lhs)->expr = simplified;
2339               VN_INFO (lhs)->has_constants = true;
2340               changed = set_ssa_val_to (lhs, simplified);
2341               goto done;
2342             }
2343           else if (simplified
2344                    && TREE_CODE (simplified) == SSA_NAME
2345                    && TREE_CODE (lhs) == SSA_NAME)
2346             {
2347               changed = visit_copy (lhs, simplified);
2348               goto done;
2349             }
2350           else if (simplified)
2351             {
2352               if (TREE_CODE (lhs) == SSA_NAME)
2353                 {
2354                   VN_INFO (lhs)->has_constants = expr_has_constants (simplified);
2355                   /* We have to unshare the expression or else
2356                      valuizing may change the IL stream.  */
2357                   VN_INFO (lhs)->expr = unshare_expr (simplified);
2358                 }
2359             }
2360           else if (stmt_has_constants (stmt)
2361                    && TREE_CODE (lhs) == SSA_NAME)
2362             VN_INFO (lhs)->has_constants = true;
2363           else if (TREE_CODE (lhs) == SSA_NAME)
2364             {
2365               /* We reset expr and constantness here because we may
2366                  have been value numbering optimistically, and
2367                  iterating. They may become non-constant in this case,
2368                  even if they were optimistically constant. */
2369
2370               VN_INFO (lhs)->has_constants = false;
2371               VN_INFO (lhs)->expr = NULL_TREE;
2372             }
2373
2374           if ((TREE_CODE (lhs) == SSA_NAME
2375                /* We can substitute SSA_NAMEs that are live over
2376                   abnormal edges with their constant value.  */
2377                && !(gimple_assign_copy_p (stmt)
2378                     && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
2379                && !(simplified
2380                     && is_gimple_min_invariant (simplified))
2381                && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2382               /* Stores or copies from SSA_NAMEs that are live over
2383                  abnormal edges are a problem.  */
2384               || (gimple_assign_single_p (stmt)
2385                   && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
2386                   && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs1 (stmt))))
2387             changed = defs_to_varying (stmt);
2388           else if (REFERENCE_CLASS_P (lhs) || DECL_P (lhs))
2389             {
2390               changed = visit_reference_op_store (lhs, gimple_assign_rhs1 (stmt), stmt);
2391             }
2392           else if (TREE_CODE (lhs) == SSA_NAME)
2393             {
2394               if ((gimple_assign_copy_p (stmt)
2395                    && is_gimple_min_invariant (gimple_assign_rhs1 (stmt)))
2396                   || (simplified
2397                       && is_gimple_min_invariant (simplified)))
2398                 {
2399                   VN_INFO (lhs)->has_constants = true;
2400                   if (simplified)
2401                     changed = set_ssa_val_to (lhs, simplified);
2402                   else
2403                     changed = set_ssa_val_to (lhs, gimple_assign_rhs1 (stmt));
2404                 }
2405               else
2406                 {
2407                   switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
2408                     {
2409                     case GIMPLE_UNARY_RHS:
2410                       changed = visit_unary_op (lhs, stmt);
2411                       break;
2412                     case GIMPLE_BINARY_RHS:
2413                       changed = visit_binary_op (lhs, stmt);
2414                       break;
2415                     case GIMPLE_SINGLE_RHS:
2416                       switch (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)))
2417                         {
2418                         case tcc_reference:
2419                           /* VOP-less references can go through unary case.  */
2420                           if ((gimple_assign_rhs_code (stmt) == REALPART_EXPR
2421                                || gimple_assign_rhs_code (stmt) == IMAGPART_EXPR
2422                                || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR )
2423                               && TREE_CODE (TREE_OPERAND (gimple_assign_rhs1 (stmt), 0)) == SSA_NAME)
2424                             {
2425                               changed = visit_unary_op (lhs, stmt);
2426                               break;
2427                             }
2428                           /* Fallthrough.  */
2429                         case tcc_declaration:
2430                           changed = visit_reference_op_load
2431                               (lhs, gimple_assign_rhs1 (stmt), stmt);
2432                           break;
2433                         case tcc_expression:
2434                           if (gimple_assign_rhs_code (stmt) == ADDR_EXPR)
2435                             {
2436                               changed = visit_unary_op (lhs, stmt);
2437                               break;
2438                             }
2439                           /* Fallthrough.  */
2440                         default:
2441                           changed = defs_to_varying (stmt);
2442                         }
2443                       break;
2444                     default:
2445                       changed = defs_to_varying (stmt);
2446                       break;
2447                     }
2448                 }
2449             }
2450           else
2451             changed = defs_to_varying (stmt);
2452         }
2453       else if (is_gimple_call (stmt))
2454         {
2455           tree lhs = gimple_call_lhs (stmt);
2456
2457           /* ???  We could try to simplify calls.  */
2458
2459           if (stmt_has_constants (stmt)
2460               && TREE_CODE (lhs) == SSA_NAME)
2461             VN_INFO (lhs)->has_constants = true;
2462           else if (TREE_CODE (lhs) == SSA_NAME)
2463             {
2464               /* We reset expr and constantness here because we may
2465                  have been value numbering optimistically, and
2466                  iterating. They may become non-constant in this case,
2467                  even if they were optimistically constant. */
2468               VN_INFO (lhs)->has_constants = false;
2469               VN_INFO (lhs)->expr = NULL_TREE;
2470             }
2471
2472           if (TREE_CODE (lhs) == SSA_NAME
2473               && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2474             changed = defs_to_varying (stmt);
2475           /* ???  We should handle stores from calls.  */
2476           else if (TREE_CODE (lhs) == SSA_NAME)
2477             {
2478               if (gimple_call_flags (stmt) & (ECF_PURE | ECF_CONST))
2479                 changed = visit_reference_op_call (lhs, stmt);
2480               else
2481                 changed = defs_to_varying (stmt);
2482             }
2483           else
2484             changed = defs_to_varying (stmt);
2485         }
2486     }
2487  done:
2488   return changed;
2489 }
2490
2491 /* Compare two operands by reverse postorder index */
2492
2493 static int
2494 compare_ops (const void *pa, const void *pb)
2495 {
2496   const tree opa = *((const tree *)pa);
2497   const tree opb = *((const tree *)pb);
2498   gimple opstmta = SSA_NAME_DEF_STMT (opa);
2499   gimple opstmtb = SSA_NAME_DEF_STMT (opb);
2500   basic_block bba;
2501   basic_block bbb;
2502
2503   if (gimple_nop_p (opstmta) && gimple_nop_p (opstmtb))
2504     return 0;
2505   else if (gimple_nop_p (opstmta))
2506     return -1;
2507   else if (gimple_nop_p (opstmtb))
2508     return 1;
2509
2510   bba = gimple_bb (opstmta);
2511   bbb = gimple_bb (opstmtb);
2512
2513   if (!bba && !bbb)
2514     return 0;
2515   else if (!bba)
2516     return -1;
2517   else if (!bbb)
2518     return 1;
2519
2520   if (bba == bbb)
2521     {
2522       if (gimple_code (opstmta) == GIMPLE_PHI
2523           && gimple_code (opstmtb) == GIMPLE_PHI)
2524         return 0;
2525       else if (gimple_code (opstmta) == GIMPLE_PHI)
2526         return -1;
2527       else if (gimple_code (opstmtb) == GIMPLE_PHI)
2528         return 1;
2529       return gimple_uid (opstmta) - gimple_uid (opstmtb);
2530     }
2531   return rpo_numbers[bba->index] - rpo_numbers[bbb->index];
2532 }
2533
2534 /* Sort an array containing members of a strongly connected component
2535    SCC so that the members are ordered by RPO number.
2536    This means that when the sort is complete, iterating through the
2537    array will give you the members in RPO order.  */
2538
2539 static void
2540 sort_scc (VEC (tree, heap) *scc)
2541 {
2542   qsort (VEC_address (tree, scc),
2543          VEC_length (tree, scc),
2544          sizeof (tree),
2545          compare_ops);
2546 }
2547
2548 /* Process a strongly connected component in the SSA graph.  */
2549
2550 static void
2551 process_scc (VEC (tree, heap) *scc)
2552 {
2553   /* If the SCC has a single member, just visit it.  */
2554
2555   if (VEC_length (tree, scc) == 1)
2556     {
2557       tree use = VEC_index (tree, scc, 0);
2558       if (!VN_INFO (use)->use_processed)
2559         visit_use (use);
2560     }
2561   else
2562     {
2563       tree var;
2564       unsigned int i;
2565       unsigned int iterations = 0;
2566       bool changed = true;
2567
2568       /* Iterate over the SCC with the optimistic table until it stops
2569          changing.  */
2570       current_info = optimistic_info;
2571       while (changed)
2572         {
2573           changed = false;
2574           iterations++;
2575           /* As we are value-numbering optimistically we have to
2576              clear the expression tables and the simplified expressions
2577              in each iteration until we converge.  */
2578           htab_empty (optimistic_info->nary);
2579           htab_empty (optimistic_info->phis);
2580           htab_empty (optimistic_info->references);
2581           obstack_free (&optimistic_info->nary_obstack, NULL);
2582           gcc_obstack_init (&optimistic_info->nary_obstack);
2583           empty_alloc_pool (optimistic_info->phis_pool);
2584           empty_alloc_pool (optimistic_info->references_pool);
2585           for (i = 0; VEC_iterate (tree, scc, i, var); i++)
2586             VN_INFO (var)->expr = NULL_TREE;
2587           for (i = 0; VEC_iterate (tree, scc, i, var); i++)
2588             changed |= visit_use (var);
2589         }
2590
2591       statistics_histogram_event (cfun, "SCC iterations", iterations);
2592
2593       /* Finally, visit the SCC once using the valid table.  */
2594       current_info = valid_info;
2595       for (i = 0; VEC_iterate (tree, scc, i, var); i++)
2596         visit_use (var);
2597     }
2598 }
2599
2600 DEF_VEC_O(ssa_op_iter);
2601 DEF_VEC_ALLOC_O(ssa_op_iter,heap);
2602
2603 /* Pop the components of the found SCC for NAME off the SCC stack
2604    and process them.  Returns true if all went well, false if
2605    we run into resource limits.  */
2606
2607 static bool
2608 extract_and_process_scc_for_name (tree name)
2609 {
2610   VEC (tree, heap) *scc = NULL;
2611   tree x;
2612
2613   /* Found an SCC, pop the components off the SCC stack and
2614      process them.  */
2615   do
2616     {
2617       x = VEC_pop (tree, sccstack);
2618
2619       VN_INFO (x)->on_sccstack = false;
2620       VEC_safe_push (tree, heap, scc, x);
2621     } while (x != name);
2622
2623   /* Bail out of SCCVN in case a SCC turns out to be incredibly large.  */
2624   if (VEC_length (tree, scc)
2625       > (unsigned)PARAM_VALUE (PARAM_SCCVN_MAX_SCC_SIZE))
2626     {
2627       if (dump_file)
2628         fprintf (dump_file, "WARNING: Giving up with SCCVN due to "
2629                  "SCC size %u exceeding %u\n", VEC_length (tree, scc),
2630                  (unsigned)PARAM_VALUE (PARAM_SCCVN_MAX_SCC_SIZE));
2631       return false;
2632     }
2633
2634   if (VEC_length (tree, scc) > 1)
2635     sort_scc (scc);
2636
2637   if (dump_file && (dump_flags & TDF_DETAILS))
2638     print_scc (dump_file, scc);
2639
2640   process_scc (scc);
2641
2642   VEC_free (tree, heap, scc);
2643
2644   return true;
2645 }
2646
2647 /* Depth first search on NAME to discover and process SCC's in the SSA
2648    graph.
2649    Execution of this algorithm relies on the fact that the SCC's are
2650    popped off the stack in topological order.
2651    Returns true if successful, false if we stopped processing SCC's due
2652    to resource constraints.  */
2653
2654 static bool
2655 DFS (tree name)
2656 {
2657   VEC(ssa_op_iter, heap) *itervec = NULL;
2658   VEC(tree, heap) *namevec = NULL;
2659   use_operand_p usep = NULL;
2660   gimple defstmt;
2661   tree use;
2662   ssa_op_iter iter;
2663
2664 start_over:
2665   /* SCC info */
2666   VN_INFO (name)->dfsnum = next_dfs_num++;
2667   VN_INFO (name)->visited = true;
2668   VN_INFO (name)->low = VN_INFO (name)->dfsnum;
2669
2670   VEC_safe_push (tree, heap, sccstack, name);
2671   VN_INFO (name)->on_sccstack = true;
2672   defstmt = SSA_NAME_DEF_STMT (name);
2673
2674   /* Recursively DFS on our operands, looking for SCC's.  */
2675   if (!gimple_nop_p (defstmt))
2676     {
2677       /* Push a new iterator.  */
2678       if (gimple_code (defstmt) == GIMPLE_PHI)
2679         usep = op_iter_init_phiuse (&iter, defstmt, SSA_OP_ALL_USES);
2680       else
2681         usep = op_iter_init_use (&iter, defstmt, SSA_OP_ALL_USES);
2682     }
2683   else
2684     clear_and_done_ssa_iter (&iter);
2685
2686   while (1)
2687     {
2688       /* If we are done processing uses of a name, go up the stack
2689          of iterators and process SCCs as we found them.  */
2690       if (op_iter_done (&iter))
2691         {
2692           /* See if we found an SCC.  */
2693           if (VN_INFO (name)->low == VN_INFO (name)->dfsnum)
2694             if (!extract_and_process_scc_for_name (name))
2695               {
2696                 VEC_free (tree, heap, namevec);
2697                 VEC_free (ssa_op_iter, heap, itervec);
2698                 return false;
2699               }
2700
2701           /* Check if we are done.  */
2702           if (VEC_empty (tree, namevec))
2703             {
2704               VEC_free (tree, heap, namevec);
2705               VEC_free (ssa_op_iter, heap, itervec);
2706               return true;
2707             }
2708
2709           /* Restore the last use walker and continue walking there.  */
2710           use = name;
2711           name = VEC_pop (tree, namevec);
2712           memcpy (&iter, VEC_last (ssa_op_iter, itervec),
2713                   sizeof (ssa_op_iter));
2714           VEC_pop (ssa_op_iter, itervec);
2715           goto continue_walking;
2716         }
2717
2718       use = USE_FROM_PTR (usep);
2719
2720       /* Since we handle phi nodes, we will sometimes get
2721          invariants in the use expression.  */
2722       if (TREE_CODE (use) == SSA_NAME)
2723         {
2724           if (! (VN_INFO (use)->visited))
2725             {
2726               /* Recurse by pushing the current use walking state on
2727                  the stack and starting over.  */
2728               VEC_safe_push(ssa_op_iter, heap, itervec, &iter);
2729               VEC_safe_push(tree, heap, namevec, name);
2730               name = use;
2731               goto start_over;
2732
2733 continue_walking:
2734               VN_INFO (name)->low = MIN (VN_INFO (name)->low,
2735                                          VN_INFO (use)->low);
2736             }
2737           if (VN_INFO (use)->dfsnum < VN_INFO (name)->dfsnum
2738               && VN_INFO (use)->on_sccstack)
2739             {
2740               VN_INFO (name)->low = MIN (VN_INFO (use)->dfsnum,
2741                                          VN_INFO (name)->low);
2742             }
2743         }
2744
2745       usep = op_iter_next_use (&iter);
2746     }
2747 }
2748
2749 /* Allocate a value number table.  */
2750
2751 static void
2752 allocate_vn_table (vn_tables_t table)
2753 {
2754   table->phis = htab_create (23, vn_phi_hash, vn_phi_eq, free_phi);
2755   table->nary = htab_create (23, vn_nary_op_hash, vn_nary_op_eq, NULL);
2756   table->references = htab_create (23, vn_reference_hash, vn_reference_eq,
2757                                    free_reference);
2758
2759   gcc_obstack_init (&table->nary_obstack);
2760   table->phis_pool = create_alloc_pool ("VN phis",
2761                                         sizeof (struct vn_phi_s),
2762                                         30);
2763   table->references_pool = create_alloc_pool ("VN references",
2764                                               sizeof (struct vn_reference_s),
2765                                               30);
2766 }
2767
2768 /* Free a value number table.  */
2769
2770 static void
2771 free_vn_table (vn_tables_t table)
2772 {
2773   htab_delete (table->phis);
2774   htab_delete (table->nary);
2775   htab_delete (table->references);
2776   obstack_free (&table->nary_obstack, NULL);
2777   free_alloc_pool (table->phis_pool);
2778   free_alloc_pool (table->references_pool);
2779 }
2780
2781 static void
2782 init_scc_vn (void)
2783 {
2784   size_t i;
2785   int j;
2786   int *rpo_numbers_temp;
2787
2788   calculate_dominance_info (CDI_DOMINATORS);
2789   sccstack = NULL;
2790   constant_to_value_id = htab_create (23, vn_constant_hash, vn_constant_eq,
2791                                   free);
2792   
2793   constant_value_ids = BITMAP_ALLOC (NULL);
2794   
2795   next_dfs_num = 1;
2796   next_value_id = 1;
2797   
2798   vn_ssa_aux_table = VEC_alloc (vn_ssa_aux_t, heap, num_ssa_names + 1);
2799   /* VEC_alloc doesn't actually grow it to the right size, it just
2800      preallocates the space to do so.  */
2801   VEC_safe_grow_cleared (vn_ssa_aux_t, heap, vn_ssa_aux_table, num_ssa_names + 1);
2802   gcc_obstack_init (&vn_ssa_aux_obstack);
2803
2804   shared_lookup_phiargs = NULL;
2805   shared_lookup_vops = NULL;
2806   shared_lookup_references = NULL;
2807   rpo_numbers = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
2808   rpo_numbers_temp = XCNEWVEC (int, last_basic_block + NUM_FIXED_BLOCKS);
2809   pre_and_rev_post_order_compute (NULL, rpo_numbers_temp, false);
2810
2811   /* RPO numbers is an array of rpo ordering, rpo[i] = bb means that
2812      the i'th block in RPO order is bb.  We want to map bb's to RPO
2813      numbers, so we need to rearrange this array.  */
2814   for (j = 0; j < n_basic_blocks - NUM_FIXED_BLOCKS; j++)
2815     rpo_numbers[rpo_numbers_temp[j]] = j;
2816
2817   XDELETE (rpo_numbers_temp);
2818
2819   VN_TOP = create_tmp_var_raw (void_type_node, "vn_top");
2820
2821   /* Create the VN_INFO structures, and initialize value numbers to
2822      TOP.  */
2823   for (i = 0; i < num_ssa_names; i++)
2824     {
2825       tree name = ssa_name (i);
2826       if (name)
2827         {
2828           VN_INFO_GET (name)->valnum = VN_TOP;
2829           VN_INFO (name)->expr = NULL_TREE;
2830           VN_INFO (name)->value_id = 0;
2831         }
2832     }
2833
2834   renumber_gimple_stmt_uids ();
2835
2836   /* Create the valid and optimistic value numbering tables.  */
2837   valid_info = XCNEW (struct vn_tables_s);
2838   allocate_vn_table (valid_info);
2839   optimistic_info = XCNEW (struct vn_tables_s);
2840   allocate_vn_table (optimistic_info);
2841 }
2842
2843 void
2844 free_scc_vn (void)
2845 {
2846   size_t i;
2847
2848   htab_delete (constant_to_value_id);
2849   BITMAP_FREE (constant_value_ids);
2850   VEC_free (tree, heap, shared_lookup_phiargs);
2851   VEC_free (tree, gc, shared_lookup_vops);
2852   VEC_free (vn_reference_op_s, heap, shared_lookup_references);
2853   XDELETEVEC (rpo_numbers);
2854
2855   for (i = 0; i < num_ssa_names; i++)
2856     {
2857       tree name = ssa_name (i);
2858       if (name
2859           && VN_INFO (name)->needs_insertion)
2860         release_ssa_name (name);
2861     }
2862   obstack_free (&vn_ssa_aux_obstack, NULL);
2863   VEC_free (vn_ssa_aux_t, heap, vn_ssa_aux_table);
2864
2865   VEC_free (tree, heap, sccstack);
2866   free_vn_table (valid_info);
2867   XDELETE (valid_info);
2868   free_vn_table (optimistic_info);
2869   XDELETE (optimistic_info);
2870 }
2871
2872 /* Set the value ids in the valid hash tables.  */
2873
2874 static void
2875 set_hashtable_value_ids (void)
2876 {
2877   htab_iterator hi;
2878   vn_nary_op_t vno;
2879   vn_reference_t vr;
2880   vn_phi_t vp;
2881
2882   /* Now set the value ids of the things we had put in the hash
2883      table.  */
2884
2885   FOR_EACH_HTAB_ELEMENT (valid_info->nary,
2886                          vno, vn_nary_op_t, hi) 
2887     {
2888       if (vno->result)
2889         {
2890           if (TREE_CODE (vno->result) == SSA_NAME)
2891             vno->value_id = VN_INFO (vno->result)->value_id;
2892           else if (is_gimple_min_invariant (vno->result))
2893             vno->value_id = get_or_alloc_constant_value_id (vno->result);
2894         }
2895     }
2896
2897   FOR_EACH_HTAB_ELEMENT (valid_info->phis,
2898                          vp, vn_phi_t, hi) 
2899     {
2900       if (vp->result)
2901         {
2902           if (TREE_CODE (vp->result) == SSA_NAME)
2903             vp->value_id = VN_INFO (vp->result)->value_id;
2904           else if (is_gimple_min_invariant (vp->result))
2905             vp->value_id = get_or_alloc_constant_value_id (vp->result);
2906         }
2907     }
2908
2909   FOR_EACH_HTAB_ELEMENT (valid_info->references,
2910                          vr, vn_reference_t, hi) 
2911     {
2912       if (vr->result)
2913         {
2914           if (TREE_CODE (vr->result) == SSA_NAME)
2915             vr->value_id = VN_INFO (vr->result)->value_id;
2916           else if (is_gimple_min_invariant (vr->result))
2917             vr->value_id = get_or_alloc_constant_value_id (vr->result);
2918         }
2919     }
2920 }
2921
2922 /* Do SCCVN.  Returns true if it finished, false if we bailed out
2923    due to resource constraints.  */
2924
2925 bool
2926 run_scc_vn (bool may_insert_arg)
2927 {
2928   size_t i;
2929   tree param;
2930   bool changed = true;
2931   
2932   may_insert = may_insert_arg;
2933
2934   init_scc_vn ();
2935   current_info = valid_info;
2936
2937   for (param = DECL_ARGUMENTS (current_function_decl);
2938        param;
2939        param = TREE_CHAIN (param))
2940     {
2941       if (gimple_default_def (cfun, param) != NULL)
2942         {
2943           tree def = gimple_default_def (cfun, param);
2944           SSA_VAL (def) = def;
2945         }
2946     }
2947
2948   for (i = 1; i < num_ssa_names; ++i)
2949     {
2950       tree name = ssa_name (i);
2951       if (name
2952           && VN_INFO (name)->visited == false
2953           && !has_zero_uses (name))
2954         if (!DFS (name))
2955           {
2956             free_scc_vn ();
2957             may_insert = false;
2958             return false;
2959           }
2960     }
2961
2962   /* Initialize the value ids.  */
2963       
2964   for (i = 1; i < num_ssa_names; ++i)
2965     {
2966       tree name = ssa_name (i);
2967       vn_ssa_aux_t info;
2968       if (!name)
2969         continue;
2970       info = VN_INFO (name);
2971       if (info->valnum == name)
2972         info->value_id = get_next_value_id ();
2973       else if (is_gimple_min_invariant (info->valnum))
2974         info->value_id = get_or_alloc_constant_value_id (info->valnum);
2975     }
2976   
2977   /* Propagate until they stop changing.  */
2978   while (changed)
2979     {
2980       changed = false;
2981       for (i = 1; i < num_ssa_names; ++i)
2982         {
2983           tree name = ssa_name (i);
2984           vn_ssa_aux_t info;
2985           if (!name)
2986             continue;
2987           info = VN_INFO (name);
2988           if (TREE_CODE (info->valnum) == SSA_NAME
2989               && info->valnum != name
2990               && info->value_id != VN_INFO (info->valnum)->value_id)
2991             {
2992               changed = true;
2993               info->value_id = VN_INFO (info->valnum)->value_id;
2994             }
2995         }
2996     }
2997   
2998   set_hashtable_value_ids ();
2999   
3000   if (dump_file && (dump_flags & TDF_DETAILS))
3001     {
3002       fprintf (dump_file, "Value numbers:\n");
3003       for (i = 0; i < num_ssa_names; i++)
3004         {
3005           tree name = ssa_name (i);
3006           if (name
3007               && VN_INFO (name)->visited
3008               && SSA_VAL (name) != name)
3009             {
3010               print_generic_expr (dump_file, name, 0);
3011               fprintf (dump_file, " = ");
3012               print_generic_expr (dump_file, SSA_VAL (name), 0);
3013               fprintf (dump_file, "\n");
3014             }
3015         }
3016     }
3017
3018   may_insert = false;
3019   return true;
3020 }
3021
3022 /* Return the maximum value id we have ever seen.  */
3023
3024 unsigned int
3025 get_max_value_id (void) 
3026 {
3027   return next_value_id;
3028 }
3029
3030 /* Return the next unique value id.  */
3031
3032 unsigned int
3033 get_next_value_id (void)
3034 {
3035   return next_value_id++;
3036 }
3037
3038
3039 /* Compare two expressions E1 and E2 and return true if they are equal.  */
3040
3041 bool
3042 expressions_equal_p (tree e1, tree e2)
3043 {
3044   /* The obvious case.  */
3045   if (e1 == e2)
3046     return true;
3047
3048   /* If only one of them is null, they cannot be equal.  */
3049   if (!e1 || !e2)
3050     return false;
3051
3052   /* Recurse on elements of lists.  */
3053   if (TREE_CODE (e1) == TREE_LIST && TREE_CODE (e2) == TREE_LIST)
3054     {
3055       tree lop1 = e1;
3056       tree lop2 = e2;
3057       for (lop1 = e1, lop2 = e2;
3058            lop1 || lop2;
3059            lop1 = TREE_CHAIN (lop1), lop2 = TREE_CHAIN (lop2))
3060         {
3061           if (!lop1 || !lop2)
3062             return false;
3063           if (!expressions_equal_p (TREE_VALUE (lop1), TREE_VALUE (lop2)))
3064             return false;
3065         }
3066       return true;
3067     }
3068
3069   /* Now perform the actual comparison.  */
3070   if (TREE_CODE (e1) == TREE_CODE (e2)
3071       && operand_equal_p (e1, e2, OEP_PURE_SAME))
3072     return true;
3073
3074   return false;
3075 }
3076
3077 /* Sort the VUSE array so that we can do equality comparisons
3078    quicker on two vuse vecs.  */
3079
3080 void
3081 sort_vuses (VEC (tree,gc) *vuses)
3082 {
3083   if (VEC_length (tree, vuses) > 1)
3084     qsort (VEC_address (tree, vuses),
3085            VEC_length (tree, vuses),
3086            sizeof (tree),
3087            operand_build_cmp);
3088 }
3089
3090 /* Sort the VUSE array so that we can do equality comparisons
3091    quicker on two vuse vecs.  */
3092
3093 void
3094 sort_vuses_heap (VEC (tree,heap) *vuses)
3095 {
3096   if (VEC_length (tree, vuses) > 1)
3097     qsort (VEC_address (tree, vuses),
3098            VEC_length (tree, vuses),
3099            sizeof (tree),
3100            operand_build_cmp);
3101 }
3102
3103
3104 /* Return true if the nary operation NARY may trap.  This is a copy
3105    of stmt_could_throw_1_p adjusted to the SCCVN IL.  */
3106
3107 bool
3108 vn_nary_may_trap (vn_nary_op_t nary)
3109 {
3110   tree type;
3111   tree rhs2;
3112   bool honor_nans = false;
3113   bool honor_snans = false;
3114   bool fp_operation = false;
3115   bool honor_trapv = false;
3116   bool handled, ret;
3117   unsigned i;
3118
3119   if (TREE_CODE_CLASS (nary->opcode) == tcc_comparison
3120       || TREE_CODE_CLASS (nary->opcode) == tcc_unary
3121       || TREE_CODE_CLASS (nary->opcode) == tcc_binary)
3122     {
3123       type = nary->type;
3124       fp_operation = FLOAT_TYPE_P (type);
3125       if (fp_operation)
3126         {
3127           honor_nans = flag_trapping_math && !flag_finite_math_only;
3128           honor_snans = flag_signaling_nans != 0;
3129         }
3130       else if (INTEGRAL_TYPE_P (type)
3131                && TYPE_OVERFLOW_TRAPS (type))
3132         honor_trapv = true;
3133     }
3134   rhs2 = nary->op[1];
3135   ret = operation_could_trap_helper_p (nary->opcode, fp_operation,
3136                                        honor_trapv,
3137                                        honor_nans, honor_snans, rhs2,
3138                                        &handled);
3139   if (handled
3140       && ret)
3141     return true;
3142
3143   for (i = 0; i < nary->length; ++i)
3144     if (tree_could_trap_p (nary->op[i]))
3145       return true;
3146
3147   return false;
3148 }