OSDN Git Service

gcc/ChangeLog:
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-reassoc.c
1 /* Reassociation for trees.
2    Copyright (C) 2005, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dan@dberlin.org>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "basic-block.h"
27 #include "diagnostic.h"
28 #include "tree-inline.h"
29 #include "tree-flow.h"
30 #include "gimple.h"
31 #include "tree-dump.h"
32 #include "timevar.h"
33 #include "tree-iterator.h"
34 #include "tree-pass.h"
35 #include "alloc-pool.h"
36 #include "vec.h"
37 #include "langhooks.h"
38 #include "pointer-set.h"
39 #include "cfgloop.h"
40 #include "flags.h"
41
42 /*  This is a simple global reassociation pass.  It is, in part, based
43     on the LLVM pass of the same name (They do some things more/less
44     than we do, in different orders, etc).
45
46     It consists of five steps:
47
48     1. Breaking up subtract operations into addition + negate, where
49     it would promote the reassociation of adds.
50
51     2. Left linearization of the expression trees, so that (A+B)+(C+D)
52     becomes (((A+B)+C)+D), which is easier for us to rewrite later.
53     During linearization, we place the operands of the binary
54     expressions into a vector of operand_entry_t
55
56     3. Optimization of the operand lists, eliminating things like a +
57     -a, a & a, etc.
58
59     4. Rewrite the expression trees we linearized and optimized so
60     they are in proper rank order.
61
62     5. Repropagate negates, as nothing else will clean it up ATM.
63
64     A bit of theory on #4, since nobody seems to write anything down
65     about why it makes sense to do it the way they do it:
66
67     We could do this much nicer theoretically, but don't (for reasons
68     explained after how to do it theoretically nice :P).
69
70     In order to promote the most redundancy elimination, you want
71     binary expressions whose operands are the same rank (or
72     preferably, the same value) exposed to the redundancy eliminator,
73     for possible elimination.
74
75     So the way to do this if we really cared, is to build the new op
76     tree from the leaves to the roots, merging as you go, and putting the
77     new op on the end of the worklist, until you are left with one
78     thing on the worklist.
79
80     IE if you have to rewrite the following set of operands (listed with
81     rank in parentheses), with opcode PLUS_EXPR:
82
83     a (1),  b (1),  c (1),  d (2), e (2)
84
85
86     We start with our merge worklist empty, and the ops list with all of
87     those on it.
88
89     You want to first merge all leaves of the same rank, as much as
90     possible.
91
92     So first build a binary op of
93
94     mergetmp = a + b, and put "mergetmp" on the merge worklist.
95
96     Because there is no three operand form of PLUS_EXPR, c is not going to
97     be exposed to redundancy elimination as a rank 1 operand.
98
99     So you might as well throw it on the merge worklist (you could also
100     consider it to now be a rank two operand, and merge it with d and e,
101     but in this case, you then have evicted e from a binary op. So at
102     least in this situation, you can't win.)
103
104     Then build a binary op of d + e
105     mergetmp2 = d + e
106
107     and put mergetmp2 on the merge worklist.
108
109     so merge worklist = {mergetmp, c, mergetmp2}
110
111     Continue building binary ops of these operations until you have only
112     one operation left on the worklist.
113
114     So we have
115
116     build binary op
117     mergetmp3 = mergetmp + c
118
119     worklist = {mergetmp2, mergetmp3}
120
121     mergetmp4 = mergetmp2 + mergetmp3
122
123     worklist = {mergetmp4}
124
125     because we have one operation left, we can now just set the original
126     statement equal to the result of that operation.
127
128     This will at least expose a + b  and d + e to redundancy elimination
129     as binary operations.
130
131     For extra points, you can reuse the old statements to build the
132     mergetmps, since you shouldn't run out.
133
134     So why don't we do this?
135
136     Because it's expensive, and rarely will help.  Most trees we are
137     reassociating have 3 or less ops.  If they have 2 ops, they already
138     will be written into a nice single binary op.  If you have 3 ops, a
139     single simple check suffices to tell you whether the first two are of the
140     same rank.  If so, you know to order it
141
142     mergetmp = op1 + op2
143     newstmt = mergetmp + op3
144
145     instead of
146     mergetmp = op2 + op3
147     newstmt = mergetmp + op1
148
149     If all three are of the same rank, you can't expose them all in a
150     single binary operator anyway, so the above is *still* the best you
151     can do.
152
153     Thus, this is what we do.  When we have three ops left, we check to see
154     what order to put them in, and call it a day.  As a nod to vector sum
155     reduction, we check if any of the ops are really a phi node that is a
156     destructive update for the associating op, and keep the destructive
157     update together for vector sum reduction recognition.  */
158
159
160 /* Statistics */
161 static struct
162 {
163   int linearized;
164   int constants_eliminated;
165   int ops_eliminated;
166   int rewritten;
167 } reassociate_stats;
168
169 /* Operator, rank pair.  */
170 typedef struct operand_entry
171 {
172   unsigned int rank;
173   int id;
174   tree op;
175 } *operand_entry_t;
176
177 static alloc_pool operand_entry_pool;
178
179 /* This is used to assign a unique ID to each struct operand_entry
180    so that qsort results are identical on different hosts.  */
181 static int next_operand_entry_id;
182
183 /* Starting rank number for a given basic block, so that we can rank
184    operations using unmovable instructions in that BB based on the bb
185    depth.  */
186 static long *bb_rank;
187
188 /* Operand->rank hashtable.  */
189 static struct pointer_map_t *operand_rank;
190
191
192 /* Look up the operand rank structure for expression E.  */
193
194 static inline long
195 find_operand_rank (tree e)
196 {
197   void **slot = pointer_map_contains (operand_rank, e);
198   return slot ? (long) (intptr_t) *slot : -1;
199 }
200
201 /* Insert {E,RANK} into the operand rank hashtable.  */
202
203 static inline void
204 insert_operand_rank (tree e, long rank)
205 {
206   void **slot;
207   gcc_assert (rank > 0);
208   slot = pointer_map_insert (operand_rank, e);
209   gcc_assert (!*slot);
210   *slot = (void *) (intptr_t) rank;
211 }
212
213 /* Given an expression E, return the rank of the expression.  */
214
215 static long
216 get_rank (tree e)
217 {
218   /* Constants have rank 0.  */
219   if (is_gimple_min_invariant (e))
220     return 0;
221
222   /* SSA_NAME's have the rank of the expression they are the result
223      of.
224      For globals and uninitialized values, the rank is 0.
225      For function arguments, use the pre-setup rank.
226      For PHI nodes, stores, asm statements, etc, we use the rank of
227      the BB.
228      For simple operations, the rank is the maximum rank of any of
229      its operands, or the bb_rank, whichever is less.
230      I make no claims that this is optimal, however, it gives good
231      results.  */
232
233   if (TREE_CODE (e) == SSA_NAME)
234     {
235       gimple stmt;
236       long rank, maxrank;
237       int i, n;
238
239       if (TREE_CODE (SSA_NAME_VAR (e)) == PARM_DECL
240           && SSA_NAME_IS_DEFAULT_DEF (e))
241         return find_operand_rank (e);
242
243       stmt = SSA_NAME_DEF_STMT (e);
244       if (gimple_bb (stmt) == NULL)
245         return 0;
246
247       if (!is_gimple_assign (stmt)
248           || gimple_vdef (stmt))
249         return bb_rank[gimple_bb (stmt)->index];
250
251       /* If we already have a rank for this expression, use that.  */
252       rank = find_operand_rank (e);
253       if (rank != -1)
254         return rank;
255
256       /* Otherwise, find the maximum rank for the operands, or the bb
257          rank, whichever is less.   */
258       rank = 0;
259       maxrank = bb_rank[gimple_bb(stmt)->index];
260       if (gimple_assign_single_p (stmt))
261         {
262           tree rhs = gimple_assign_rhs1 (stmt);
263           n = TREE_OPERAND_LENGTH (rhs);
264           if (n == 0)
265             rank = MAX (rank, get_rank (rhs));
266           else
267             {
268               for (i = 0;
269                    i < n && TREE_OPERAND (rhs, i) && rank != maxrank; i++)
270                 rank = MAX(rank, get_rank (TREE_OPERAND (rhs, i)));
271             }
272         }
273       else
274         {
275           n = gimple_num_ops (stmt);
276           for (i = 1; i < n && rank != maxrank; i++)
277             {
278               gcc_assert (gimple_op (stmt, i));
279               rank = MAX(rank, get_rank (gimple_op (stmt, i)));
280             }
281         }
282
283       if (dump_file && (dump_flags & TDF_DETAILS))
284         {
285           fprintf (dump_file, "Rank for ");
286           print_generic_expr (dump_file, e, 0);
287           fprintf (dump_file, " is %ld\n", (rank + 1));
288         }
289
290       /* Note the rank in the hashtable so we don't recompute it.  */
291       insert_operand_rank (e, (rank + 1));
292       return (rank + 1);
293     }
294
295   /* Globals, etc,  are rank 0 */
296   return 0;
297 }
298
299 DEF_VEC_P(operand_entry_t);
300 DEF_VEC_ALLOC_P(operand_entry_t, heap);
301
302 /* We want integer ones to end up last no matter what, since they are
303    the ones we can do the most with.  */
304 #define INTEGER_CONST_TYPE 1 << 3
305 #define FLOAT_CONST_TYPE 1 << 2
306 #define OTHER_CONST_TYPE 1 << 1
307
308 /* Classify an invariant tree into integer, float, or other, so that
309    we can sort them to be near other constants of the same type.  */
310 static inline int
311 constant_type (tree t)
312 {
313   if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
314     return INTEGER_CONST_TYPE;
315   else if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (t)))
316     return FLOAT_CONST_TYPE;
317   else
318     return OTHER_CONST_TYPE;
319 }
320
321 /* qsort comparison function to sort operand entries PA and PB by rank
322    so that the sorted array is ordered by rank in decreasing order.  */
323 static int
324 sort_by_operand_rank (const void *pa, const void *pb)
325 {
326   const operand_entry_t oea = *(const operand_entry_t *)pa;
327   const operand_entry_t oeb = *(const operand_entry_t *)pb;
328
329   /* It's nicer for optimize_expression if constants that are likely
330      to fold when added/multiplied//whatever are put next to each
331      other.  Since all constants have rank 0, order them by type.  */
332   if (oeb->rank == 0 &&  oea->rank == 0)
333     {
334       if (constant_type (oeb->op) != constant_type (oea->op))
335         return constant_type (oeb->op) - constant_type (oea->op);
336       else
337         /* To make sorting result stable, we use unique IDs to determine
338            order.  */
339         return oeb->id - oea->id;
340     }
341
342   /* Lastly, make sure the versions that are the same go next to each
343      other.  We use SSA_NAME_VERSION because it's stable.  */
344   if ((oeb->rank - oea->rank == 0)
345       && TREE_CODE (oea->op) == SSA_NAME
346       && TREE_CODE (oeb->op) == SSA_NAME)
347     {
348       if (SSA_NAME_VERSION (oeb->op) != SSA_NAME_VERSION (oea->op))
349         return SSA_NAME_VERSION (oeb->op) - SSA_NAME_VERSION (oea->op);
350       else
351         return oeb->id - oea->id;
352     }
353
354   if (oeb->rank != oea->rank)
355     return oeb->rank - oea->rank;
356   else
357     return oeb->id - oea->id;
358 }
359
360 /* Add an operand entry to *OPS for the tree operand OP.  */
361
362 static void
363 add_to_ops_vec (VEC(operand_entry_t, heap) **ops, tree op)
364 {
365   operand_entry_t oe = (operand_entry_t) pool_alloc (operand_entry_pool);
366
367   oe->op = op;
368   oe->rank = get_rank (op);
369   oe->id = next_operand_entry_id++;
370   VEC_safe_push (operand_entry_t, heap, *ops, oe);
371 }
372
373 /* Return true if STMT is reassociable operation containing a binary
374    operation with tree code CODE, and is inside LOOP.  */
375
376 static bool
377 is_reassociable_op (gimple stmt, enum tree_code code, struct loop *loop)
378 {
379   basic_block bb = gimple_bb (stmt);
380
381   if (gimple_bb (stmt) == NULL)
382     return false;
383
384   if (!flow_bb_inside_loop_p (loop, bb))
385     return false;
386
387   if (is_gimple_assign (stmt)
388       && gimple_assign_rhs_code (stmt) == code
389       && has_single_use (gimple_assign_lhs (stmt)))
390     return true;
391
392   return false;
393 }
394
395
396 /* Given NAME, if NAME is defined by a unary operation OPCODE, return the
397    operand of the negate operation.  Otherwise, return NULL.  */
398
399 static tree
400 get_unary_op (tree name, enum tree_code opcode)
401 {
402   gimple stmt = SSA_NAME_DEF_STMT (name);
403
404   if (!is_gimple_assign (stmt))
405     return NULL_TREE;
406
407   if (gimple_assign_rhs_code (stmt) == opcode)
408     return gimple_assign_rhs1 (stmt);
409   return NULL_TREE;
410 }
411
412 /* If CURR and LAST are a pair of ops that OPCODE allows us to
413    eliminate through equivalences, do so, remove them from OPS, and
414    return true.  Otherwise, return false.  */
415
416 static bool
417 eliminate_duplicate_pair (enum tree_code opcode,
418                           VEC (operand_entry_t, heap) **ops,
419                           bool *all_done,
420                           unsigned int i,
421                           operand_entry_t curr,
422                           operand_entry_t last)
423 {
424
425   /* If we have two of the same op, and the opcode is & |, min, or max,
426      we can eliminate one of them.
427      If we have two of the same op, and the opcode is ^, we can
428      eliminate both of them.  */
429
430   if (last && last->op == curr->op)
431     {
432       switch (opcode)
433         {
434         case MAX_EXPR:
435         case MIN_EXPR:
436         case BIT_IOR_EXPR:
437         case BIT_AND_EXPR:
438           if (dump_file && (dump_flags & TDF_DETAILS))
439             {
440               fprintf (dump_file, "Equivalence: ");
441               print_generic_expr (dump_file, curr->op, 0);
442               fprintf (dump_file, " [&|minmax] ");
443               print_generic_expr (dump_file, last->op, 0);
444               fprintf (dump_file, " -> ");
445               print_generic_stmt (dump_file, last->op, 0);
446             }
447
448           VEC_ordered_remove (operand_entry_t, *ops, i);
449           reassociate_stats.ops_eliminated ++;
450
451           return true;
452
453         case BIT_XOR_EXPR:
454           if (dump_file && (dump_flags & TDF_DETAILS))
455             {
456               fprintf (dump_file, "Equivalence: ");
457               print_generic_expr (dump_file, curr->op, 0);
458               fprintf (dump_file, " ^ ");
459               print_generic_expr (dump_file, last->op, 0);
460               fprintf (dump_file, " -> nothing\n");
461             }
462
463           reassociate_stats.ops_eliminated += 2;
464
465           if (VEC_length (operand_entry_t, *ops) == 2)
466             {
467               VEC_free (operand_entry_t, heap, *ops);
468               *ops = NULL;
469               add_to_ops_vec (ops, fold_convert (TREE_TYPE (last->op),
470                                                  integer_zero_node));
471               *all_done = true;
472             }
473           else
474             {
475               VEC_ordered_remove (operand_entry_t, *ops, i-1);
476               VEC_ordered_remove (operand_entry_t, *ops, i-1);
477             }
478
479           return true;
480
481         default:
482           break;
483         }
484     }
485   return false;
486 }
487
488 static VEC(tree, heap) *plus_negates;
489
490 /* If OPCODE is PLUS_EXPR, CURR->OP is a negate expression or a bitwise not
491    expression, look in OPS for a corresponding positive operation to cancel
492    it out.  If we find one, remove the other from OPS, replace
493    OPS[CURRINDEX] with 0 or -1, respectively, and return true.  Otherwise,
494    return false. */
495
496 static bool
497 eliminate_plus_minus_pair (enum tree_code opcode,
498                            VEC (operand_entry_t, heap) **ops,
499                            unsigned int currindex,
500                            operand_entry_t curr)
501 {
502   tree negateop;
503   tree notop;
504   unsigned int i;
505   operand_entry_t oe;
506
507   if (opcode != PLUS_EXPR || TREE_CODE (curr->op) != SSA_NAME)
508     return false;
509
510   negateop = get_unary_op (curr->op, NEGATE_EXPR);
511   notop = get_unary_op (curr->op, BIT_NOT_EXPR);
512   if (negateop == NULL_TREE && notop == NULL_TREE)
513     return false;
514
515   /* Any non-negated version will have a rank that is one less than
516      the current rank.  So once we hit those ranks, if we don't find
517      one, we can stop.  */
518
519   for (i = currindex + 1;
520        VEC_iterate (operand_entry_t, *ops, i, oe)
521        && oe->rank >= curr->rank - 1 ;
522        i++)
523     {
524       if (oe->op == negateop)
525         {
526
527           if (dump_file && (dump_flags & TDF_DETAILS))
528             {
529               fprintf (dump_file, "Equivalence: ");
530               print_generic_expr (dump_file, negateop, 0);
531               fprintf (dump_file, " + -");
532               print_generic_expr (dump_file, oe->op, 0);
533               fprintf (dump_file, " -> 0\n");
534             }
535
536           VEC_ordered_remove (operand_entry_t, *ops, i);
537           add_to_ops_vec (ops, fold_convert(TREE_TYPE (oe->op),
538                                             integer_zero_node));
539           VEC_ordered_remove (operand_entry_t, *ops, currindex);
540           reassociate_stats.ops_eliminated ++;
541
542           return true;
543         }
544       else if (oe->op == notop)
545         {
546           tree op_type = TREE_TYPE (oe->op);
547
548           if (dump_file && (dump_flags & TDF_DETAILS))
549             {
550               fprintf (dump_file, "Equivalence: ");
551               print_generic_expr (dump_file, notop, 0);
552               fprintf (dump_file, " + ~");
553               print_generic_expr (dump_file, oe->op, 0);
554               fprintf (dump_file, " -> -1\n");
555             }
556
557           VEC_ordered_remove (operand_entry_t, *ops, i);
558           add_to_ops_vec (ops, build_int_cst_type (op_type, -1));
559           VEC_ordered_remove (operand_entry_t, *ops, currindex);
560           reassociate_stats.ops_eliminated ++;
561
562           return true;
563         }
564     }
565
566   /* CURR->OP is a negate expr in a plus expr: save it for later
567      inspection in repropagate_negates().  */
568   if (negateop != NULL_TREE)
569     VEC_safe_push (tree, heap, plus_negates, curr->op);
570
571   return false;
572 }
573
574 /* If OPCODE is BIT_IOR_EXPR, BIT_AND_EXPR, and, CURR->OP is really a
575    bitwise not expression, look in OPS for a corresponding operand to
576    cancel it out.  If we find one, remove the other from OPS, replace
577    OPS[CURRINDEX] with 0, and return true.  Otherwise, return
578    false. */
579
580 static bool
581 eliminate_not_pairs (enum tree_code opcode,
582                      VEC (operand_entry_t, heap) **ops,
583                      unsigned int currindex,
584                      operand_entry_t curr)
585 {
586   tree notop;
587   unsigned int i;
588   operand_entry_t oe;
589
590   if ((opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
591       || TREE_CODE (curr->op) != SSA_NAME)
592     return false;
593
594   notop = get_unary_op (curr->op, BIT_NOT_EXPR);
595   if (notop == NULL_TREE)
596     return false;
597
598   /* Any non-not version will have a rank that is one less than
599      the current rank.  So once we hit those ranks, if we don't find
600      one, we can stop.  */
601
602   for (i = currindex + 1;
603        VEC_iterate (operand_entry_t, *ops, i, oe)
604        && oe->rank >= curr->rank - 1;
605        i++)
606     {
607       if (oe->op == notop)
608         {
609           if (dump_file && (dump_flags & TDF_DETAILS))
610             {
611               fprintf (dump_file, "Equivalence: ");
612               print_generic_expr (dump_file, notop, 0);
613               if (opcode == BIT_AND_EXPR)
614                 fprintf (dump_file, " & ~");
615               else if (opcode == BIT_IOR_EXPR)
616                 fprintf (dump_file, " | ~");
617               print_generic_expr (dump_file, oe->op, 0);
618               if (opcode == BIT_AND_EXPR)
619                 fprintf (dump_file, " -> 0\n");
620               else if (opcode == BIT_IOR_EXPR)
621                 fprintf (dump_file, " -> -1\n");
622             }
623
624           if (opcode == BIT_AND_EXPR)
625             oe->op = fold_convert (TREE_TYPE (oe->op), integer_zero_node);
626           else if (opcode == BIT_IOR_EXPR)
627             oe->op = build_low_bits_mask (TREE_TYPE (oe->op),
628                                           TYPE_PRECISION (TREE_TYPE (oe->op)));
629
630           reassociate_stats.ops_eliminated
631             += VEC_length (operand_entry_t, *ops) - 1;
632           VEC_free (operand_entry_t, heap, *ops);
633           *ops = NULL;
634           VEC_safe_push (operand_entry_t, heap, *ops, oe);
635           return true;
636         }
637     }
638
639   return false;
640 }
641
642 /* Use constant value that may be present in OPS to try to eliminate
643    operands.  Note that this function is only really used when we've
644    eliminated ops for other reasons, or merged constants.  Across
645    single statements, fold already does all of this, plus more.  There
646    is little point in duplicating logic, so I've only included the
647    identities that I could ever construct testcases to trigger.  */
648
649 static void
650 eliminate_using_constants (enum tree_code opcode,
651                            VEC(operand_entry_t, heap) **ops)
652 {
653   operand_entry_t oelast = VEC_last (operand_entry_t, *ops);
654   tree type = TREE_TYPE (oelast->op);
655
656   if (oelast->rank == 0
657       && (INTEGRAL_TYPE_P (type) || FLOAT_TYPE_P (type)))
658     {
659       switch (opcode)
660         {
661         case BIT_AND_EXPR:
662           if (integer_zerop (oelast->op))
663             {
664               if (VEC_length (operand_entry_t, *ops) != 1)
665                 {
666                   if (dump_file && (dump_flags & TDF_DETAILS))
667                     fprintf (dump_file, "Found & 0, removing all other ops\n");
668
669                   reassociate_stats.ops_eliminated
670                     += VEC_length (operand_entry_t, *ops) - 1;
671
672                   VEC_free (operand_entry_t, heap, *ops);
673                   *ops = NULL;
674                   VEC_safe_push (operand_entry_t, heap, *ops, oelast);
675                   return;
676                 }
677             }
678           else if (integer_all_onesp (oelast->op))
679             {
680               if (VEC_length (operand_entry_t, *ops) != 1)
681                 {
682                   if (dump_file && (dump_flags & TDF_DETAILS))
683                     fprintf (dump_file, "Found & -1, removing\n");
684                   VEC_pop (operand_entry_t, *ops);
685                   reassociate_stats.ops_eliminated++;
686                 }
687             }
688           break;
689         case BIT_IOR_EXPR:
690           if (integer_all_onesp (oelast->op))
691             {
692               if (VEC_length (operand_entry_t, *ops) != 1)
693                 {
694                   if (dump_file && (dump_flags & TDF_DETAILS))
695                     fprintf (dump_file, "Found | -1, removing all other ops\n");
696
697                   reassociate_stats.ops_eliminated
698                     += VEC_length (operand_entry_t, *ops) - 1;
699
700                   VEC_free (operand_entry_t, heap, *ops);
701                   *ops = NULL;
702                   VEC_safe_push (operand_entry_t, heap, *ops, oelast);
703                   return;
704                 }
705             }
706           else if (integer_zerop (oelast->op))
707             {
708               if (VEC_length (operand_entry_t, *ops) != 1)
709                 {
710                   if (dump_file && (dump_flags & TDF_DETAILS))
711                     fprintf (dump_file, "Found | 0, removing\n");
712                   VEC_pop (operand_entry_t, *ops);
713                   reassociate_stats.ops_eliminated++;
714                 }
715             }
716           break;
717         case MULT_EXPR:
718           if (integer_zerop (oelast->op)
719               || (FLOAT_TYPE_P (type)
720                   && !HONOR_NANS (TYPE_MODE (type))
721                   && !HONOR_SIGNED_ZEROS (TYPE_MODE (type))
722                   && real_zerop (oelast->op)))
723             {
724               if (VEC_length (operand_entry_t, *ops) != 1)
725                 {
726                   if (dump_file && (dump_flags & TDF_DETAILS))
727                     fprintf (dump_file, "Found * 0, removing all other ops\n");
728
729                   reassociate_stats.ops_eliminated
730                     += VEC_length (operand_entry_t, *ops) - 1;
731                   VEC_free (operand_entry_t, heap, *ops);
732                   *ops = NULL;
733                   VEC_safe_push (operand_entry_t, heap, *ops, oelast);
734                   return;
735                 }
736             }
737           else if (integer_onep (oelast->op)
738                    || (FLOAT_TYPE_P (type)
739                        && !HONOR_SNANS (TYPE_MODE (type))
740                        && real_onep (oelast->op)))
741             {
742               if (VEC_length (operand_entry_t, *ops) != 1)
743                 {
744                   if (dump_file && (dump_flags & TDF_DETAILS))
745                     fprintf (dump_file, "Found * 1, removing\n");
746                   VEC_pop (operand_entry_t, *ops);
747                   reassociate_stats.ops_eliminated++;
748                   return;
749                 }
750             }
751           break;
752         case BIT_XOR_EXPR:
753         case PLUS_EXPR:
754         case MINUS_EXPR:
755           if (integer_zerop (oelast->op)
756               || (FLOAT_TYPE_P (type)
757                   && (opcode == PLUS_EXPR || opcode == MINUS_EXPR)
758                   && fold_real_zero_addition_p (type, oelast->op,
759                                                 opcode == MINUS_EXPR)))
760             {
761               if (VEC_length (operand_entry_t, *ops) != 1)
762                 {
763                   if (dump_file && (dump_flags & TDF_DETAILS))
764                     fprintf (dump_file, "Found [|^+] 0, removing\n");
765                   VEC_pop (operand_entry_t, *ops);
766                   reassociate_stats.ops_eliminated++;
767                   return;
768                 }
769             }
770           break;
771         default:
772           break;
773         }
774     }
775 }
776
777
778 static void linearize_expr_tree (VEC(operand_entry_t, heap) **, gimple,
779                                  bool, bool);
780
781 /* Structure for tracking and counting operands.  */
782 typedef struct oecount_s {
783   int cnt;
784   int id;
785   enum tree_code oecode;
786   tree op;
787 } oecount;
788
789 DEF_VEC_O(oecount);
790 DEF_VEC_ALLOC_O(oecount,heap);
791
792 /* The heap for the oecount hashtable and the sorted list of operands.  */
793 static VEC (oecount, heap) *cvec;
794
795 /* Hash function for oecount.  */
796
797 static hashval_t
798 oecount_hash (const void *p)
799 {
800   const oecount *c = VEC_index (oecount, cvec, (size_t)p - 42);
801   return htab_hash_pointer (c->op) ^ (hashval_t)c->oecode;
802 }
803
804 /* Comparison function for oecount.  */
805
806 static int
807 oecount_eq (const void *p1, const void *p2)
808 {
809   const oecount *c1 = VEC_index (oecount, cvec, (size_t)p1 - 42);
810   const oecount *c2 = VEC_index (oecount, cvec, (size_t)p2 - 42);
811   return (c1->oecode == c2->oecode
812           && c1->op == c2->op);
813 }
814
815 /* Comparison function for qsort sorting oecount elements by count.  */
816
817 static int
818 oecount_cmp (const void *p1, const void *p2)
819 {
820   const oecount *c1 = (const oecount *)p1;
821   const oecount *c2 = (const oecount *)p2;
822   if (c1->cnt != c2->cnt)
823     return c1->cnt - c2->cnt;
824   else
825     /* If counts are identical, use unique IDs to stabilize qsort.  */
826     return c1->id - c2->id;
827 }
828
829 /* Walks the linear chain with result *DEF searching for an operation
830    with operand OP and code OPCODE removing that from the chain.  *DEF
831    is updated if there is only one operand but no operation left.  */
832
833 static void
834 zero_one_operation (tree *def, enum tree_code opcode, tree op)
835 {
836   gimple stmt = SSA_NAME_DEF_STMT (*def);
837
838   do
839     {
840       tree name = gimple_assign_rhs1 (stmt);
841
842       /* If this is the operation we look for and one of the operands
843          is ours simply propagate the other operand into the stmts
844          single use.  */
845       if (gimple_assign_rhs_code (stmt) == opcode
846           && (name == op
847               || gimple_assign_rhs2 (stmt) == op))
848         {
849           gimple use_stmt;
850           use_operand_p use;
851           gimple_stmt_iterator gsi;
852           if (name == op)
853             name = gimple_assign_rhs2 (stmt);
854           gcc_assert (has_single_use (gimple_assign_lhs (stmt)));
855           single_imm_use (gimple_assign_lhs (stmt), &use, &use_stmt);
856           if (gimple_assign_lhs (stmt) == *def)
857             *def = name;
858           SET_USE (use, name);
859           if (TREE_CODE (name) != SSA_NAME)
860             update_stmt (use_stmt);
861           gsi = gsi_for_stmt (stmt);
862           gsi_remove (&gsi, true);
863           release_defs (stmt);
864           return;
865         }
866
867       /* Continue walking the chain.  */
868       gcc_assert (name != op
869                   && TREE_CODE (name) == SSA_NAME);
870       stmt = SSA_NAME_DEF_STMT (name);
871     }
872   while (1);
873 }
874
875 /* Builds one statement performing OP1 OPCODE OP2 using TMPVAR for
876    the result.  Places the statement after the definition of either
877    OP1 or OP2.  Returns the new statement.  */
878
879 static gimple
880 build_and_add_sum (tree tmpvar, tree op1, tree op2, enum tree_code opcode)
881 {
882   gimple op1def = NULL, op2def = NULL;
883   gimple_stmt_iterator gsi;
884   tree op;
885   gimple sum;
886
887   /* Create the addition statement.  */
888   sum = gimple_build_assign_with_ops (opcode, tmpvar, op1, op2);
889   op = make_ssa_name (tmpvar, sum);
890   gimple_assign_set_lhs (sum, op);
891
892   /* Find an insertion place and insert.  */
893   if (TREE_CODE (op1) == SSA_NAME)
894     op1def = SSA_NAME_DEF_STMT (op1);
895   if (TREE_CODE (op2) == SSA_NAME)
896     op2def = SSA_NAME_DEF_STMT (op2);
897   if ((!op1def || gimple_nop_p (op1def))
898       && (!op2def || gimple_nop_p (op2def)))
899     {
900       gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
901       gsi_insert_before (&gsi, sum, GSI_NEW_STMT);
902     }
903   else if ((!op1def || gimple_nop_p (op1def))
904            || (op2def && !gimple_nop_p (op2def)
905                && stmt_dominates_stmt_p (op1def, op2def)))
906     {
907       if (gimple_code (op2def) == GIMPLE_PHI)
908         {
909           gsi = gsi_after_labels (gimple_bb (op2def));
910           gsi_insert_before (&gsi, sum, GSI_NEW_STMT);
911         }
912       else
913         {
914           if (!stmt_ends_bb_p (op2def))
915             {
916               gsi = gsi_for_stmt (op2def);
917               gsi_insert_after (&gsi, sum, GSI_NEW_STMT);
918             }
919           else
920             {
921               edge e;
922               edge_iterator ei;
923
924               FOR_EACH_EDGE (e, ei, gimple_bb (op2def)->succs)
925                 if (e->flags & EDGE_FALLTHRU)
926                   gsi_insert_on_edge_immediate (e, sum);
927             }
928         }
929     }
930   else
931     {
932       if (gimple_code (op1def) == GIMPLE_PHI)
933         {
934           gsi = gsi_after_labels (gimple_bb (op1def));
935           gsi_insert_before (&gsi, sum, GSI_NEW_STMT);
936         }
937       else
938         {
939           if (!stmt_ends_bb_p (op1def))
940             {
941               gsi = gsi_for_stmt (op1def);
942               gsi_insert_after (&gsi, sum, GSI_NEW_STMT);
943             }
944           else
945             {
946               edge e;
947               edge_iterator ei;
948
949               FOR_EACH_EDGE (e, ei, gimple_bb (op1def)->succs)
950                 if (e->flags & EDGE_FALLTHRU)
951                   gsi_insert_on_edge_immediate (e, sum);
952             }
953         }
954     }
955   update_stmt (sum);
956
957   return sum;
958 }
959
960 /* Perform un-distribution of divisions and multiplications.
961    A * X + B * X is transformed into (A + B) * X and A / X + B / X
962    to (A + B) / X for real X.
963
964    The algorithm is organized as follows.
965
966     - First we walk the addition chain *OPS looking for summands that
967       are defined by a multiplication or a real division.  This results
968       in the candidates bitmap with relevant indices into *OPS.
969
970     - Second we build the chains of multiplications or divisions for
971       these candidates, counting the number of occurences of (operand, code)
972       pairs in all of the candidates chains.
973
974     - Third we sort the (operand, code) pairs by number of occurence and
975       process them starting with the pair with the most uses.
976
977       * For each such pair we walk the candidates again to build a
978         second candidate bitmap noting all multiplication/division chains
979         that have at least one occurence of (operand, code).
980
981       * We build an alternate addition chain only covering these
982         candidates with one (operand, code) operation removed from their
983         multiplication/division chain.
984
985       * The first candidate gets replaced by the alternate addition chain
986         multiplied/divided by the operand.
987
988       * All candidate chains get disabled for further processing and
989         processing of (operand, code) pairs continues.
990
991   The alternate addition chains built are re-processed by the main
992   reassociation algorithm which allows optimizing a * x * y + b * y * x
993   to (a + b ) * x * y in one invocation of the reassociation pass.  */
994
995 static bool
996 undistribute_ops_list (enum tree_code opcode,
997                        VEC (operand_entry_t, heap) **ops, struct loop *loop)
998 {
999   unsigned int length = VEC_length (operand_entry_t, *ops);
1000   operand_entry_t oe1;
1001   unsigned i, j;
1002   sbitmap candidates, candidates2;
1003   unsigned nr_candidates, nr_candidates2;
1004   sbitmap_iterator sbi0;
1005   VEC (operand_entry_t, heap) **subops;
1006   htab_t ctable;
1007   bool changed = false;
1008   int next_oecount_id = 0;
1009
1010   if (length <= 1
1011       || opcode != PLUS_EXPR)
1012     return false;
1013
1014   /* Build a list of candidates to process.  */
1015   candidates = sbitmap_alloc (length);
1016   sbitmap_zero (candidates);
1017   nr_candidates = 0;
1018   for (i = 0; VEC_iterate (operand_entry_t, *ops, i, oe1); ++i)
1019     {
1020       enum tree_code dcode;
1021       gimple oe1def;
1022
1023       if (TREE_CODE (oe1->op) != SSA_NAME)
1024         continue;
1025       oe1def = SSA_NAME_DEF_STMT (oe1->op);
1026       if (!is_gimple_assign (oe1def))
1027         continue;
1028       dcode = gimple_assign_rhs_code (oe1def);
1029       if ((dcode != MULT_EXPR
1030            && dcode != RDIV_EXPR)
1031           || !is_reassociable_op (oe1def, dcode, loop))
1032         continue;
1033
1034       SET_BIT (candidates, i);
1035       nr_candidates++;
1036     }
1037
1038   if (nr_candidates < 2)
1039     {
1040       sbitmap_free (candidates);
1041       return false;
1042     }
1043
1044   if (dump_file && (dump_flags & TDF_DETAILS))
1045     {
1046       fprintf (dump_file, "searching for un-distribute opportunities ");
1047       print_generic_expr (dump_file,
1048         VEC_index (operand_entry_t, *ops,
1049                    sbitmap_first_set_bit (candidates))->op, 0);
1050       fprintf (dump_file, " %d\n", nr_candidates);
1051     }
1052
1053   /* Build linearized sub-operand lists and the counting table.  */
1054   cvec = NULL;
1055   ctable = htab_create (15, oecount_hash, oecount_eq, NULL);
1056   subops = XCNEWVEC (VEC (operand_entry_t, heap) *,
1057                      VEC_length (operand_entry_t, *ops));
1058   EXECUTE_IF_SET_IN_SBITMAP (candidates, 0, i, sbi0)
1059     {
1060       gimple oedef;
1061       enum tree_code oecode;
1062       unsigned j;
1063
1064       oedef = SSA_NAME_DEF_STMT (VEC_index (operand_entry_t, *ops, i)->op);
1065       oecode = gimple_assign_rhs_code (oedef);
1066       linearize_expr_tree (&subops[i], oedef,
1067                            associative_tree_code (oecode), false);
1068
1069       for (j = 0; VEC_iterate (operand_entry_t, subops[i], j, oe1); ++j)
1070         {
1071           oecount c;
1072           void **slot;
1073           size_t idx;
1074           c.oecode = oecode;
1075           c.cnt = 1;
1076           c.id = next_oecount_id++;
1077           c.op = oe1->op;
1078           VEC_safe_push (oecount, heap, cvec, &c);
1079           idx = VEC_length (oecount, cvec) + 41;
1080           slot = htab_find_slot (ctable, (void *)idx, INSERT);
1081           if (!*slot)
1082             {
1083               *slot = (void *)idx;
1084             }
1085           else
1086             {
1087               VEC_pop (oecount, cvec);
1088               VEC_index (oecount, cvec, (size_t)*slot - 42)->cnt++;
1089             }
1090         }
1091     }
1092   htab_delete (ctable);
1093
1094   /* Sort the counting table.  */
1095   qsort (VEC_address (oecount, cvec), VEC_length (oecount, cvec),
1096          sizeof (oecount), oecount_cmp);
1097
1098   if (dump_file && (dump_flags & TDF_DETAILS))
1099     {
1100       oecount *c;
1101       fprintf (dump_file, "Candidates:\n");
1102       for (j = 0; VEC_iterate (oecount, cvec, j, c); ++j)
1103         {
1104           fprintf (dump_file, "  %u %s: ", c->cnt,
1105                    c->oecode == MULT_EXPR
1106                    ? "*" : c->oecode == RDIV_EXPR ? "/" : "?");
1107           print_generic_expr (dump_file, c->op, 0);
1108           fprintf (dump_file, "\n");
1109         }
1110     }
1111
1112   /* Process the (operand, code) pairs in order of most occurence.  */
1113   candidates2 = sbitmap_alloc (length);
1114   while (!VEC_empty (oecount, cvec))
1115     {
1116       oecount *c = VEC_last (oecount, cvec);
1117       if (c->cnt < 2)
1118         break;
1119
1120       /* Now collect the operands in the outer chain that contain
1121          the common operand in their inner chain.  */
1122       sbitmap_zero (candidates2);
1123       nr_candidates2 = 0;
1124       EXECUTE_IF_SET_IN_SBITMAP (candidates, 0, i, sbi0)
1125         {
1126           gimple oedef;
1127           enum tree_code oecode;
1128           unsigned j;
1129           tree op = VEC_index (operand_entry_t, *ops, i)->op;
1130
1131           /* If we undistributed in this chain already this may be
1132              a constant.  */
1133           if (TREE_CODE (op) != SSA_NAME)
1134             continue;
1135
1136           oedef = SSA_NAME_DEF_STMT (op);
1137           oecode = gimple_assign_rhs_code (oedef);
1138           if (oecode != c->oecode)
1139             continue;
1140
1141           for (j = 0; VEC_iterate (operand_entry_t, subops[i], j, oe1); ++j)
1142             {
1143               if (oe1->op == c->op)
1144                 {
1145                   SET_BIT (candidates2, i);
1146                   ++nr_candidates2;
1147                   break;
1148                 }
1149             }
1150         }
1151
1152       if (nr_candidates2 >= 2)
1153         {
1154           operand_entry_t oe1, oe2;
1155           tree tmpvar;
1156           gimple prod;
1157           int first = sbitmap_first_set_bit (candidates2);
1158
1159           /* Build the new addition chain.  */
1160           oe1 = VEC_index (operand_entry_t, *ops, first);
1161           if (dump_file && (dump_flags & TDF_DETAILS))
1162             {
1163               fprintf (dump_file, "Building (");
1164               print_generic_expr (dump_file, oe1->op, 0);
1165             }
1166           tmpvar = create_tmp_reg (TREE_TYPE (oe1->op), NULL);
1167           add_referenced_var (tmpvar);
1168           zero_one_operation (&oe1->op, c->oecode, c->op);
1169           EXECUTE_IF_SET_IN_SBITMAP (candidates2, first+1, i, sbi0)
1170             {
1171               gimple sum;
1172               oe2 = VEC_index (operand_entry_t, *ops, i);
1173               if (dump_file && (dump_flags & TDF_DETAILS))
1174                 {
1175                   fprintf (dump_file, " + ");
1176                   print_generic_expr (dump_file, oe2->op, 0);
1177                 }
1178               zero_one_operation (&oe2->op, c->oecode, c->op);
1179               sum = build_and_add_sum (tmpvar, oe1->op, oe2->op, opcode);
1180               oe2->op = fold_convert (TREE_TYPE (oe2->op), integer_zero_node);
1181               oe2->rank = 0;
1182               oe1->op = gimple_get_lhs (sum);
1183             }
1184
1185           /* Apply the multiplication/division.  */
1186           prod = build_and_add_sum (tmpvar, oe1->op, c->op, c->oecode);
1187           if (dump_file && (dump_flags & TDF_DETAILS))
1188             {
1189               fprintf (dump_file, ") %s ", c->oecode == MULT_EXPR ? "*" : "/");
1190               print_generic_expr (dump_file, c->op, 0);
1191               fprintf (dump_file, "\n");
1192             }
1193
1194           /* Record it in the addition chain and disable further
1195              undistribution with this op.  */
1196           oe1->op = gimple_assign_lhs (prod);
1197           oe1->rank = get_rank (oe1->op);
1198           VEC_free (operand_entry_t, heap, subops[first]);
1199
1200           changed = true;
1201         }
1202
1203       VEC_pop (oecount, cvec);
1204     }
1205
1206   for (i = 0; i < VEC_length (operand_entry_t, *ops); ++i)
1207     VEC_free (operand_entry_t, heap, subops[i]);
1208   free (subops);
1209   VEC_free (oecount, heap, cvec);
1210   sbitmap_free (candidates);
1211   sbitmap_free (candidates2);
1212
1213   return changed;
1214 }
1215
1216 /* If OPCODE is BIT_IOR_EXPR or BIT_AND_EXPR and CURR is a comparison
1217    expression, examine the other OPS to see if any of them are comparisons
1218    of the same values, which we may be able to combine or eliminate.
1219    For example, we can rewrite (a < b) | (a == b) as (a <= b).  */
1220
1221 static bool
1222 eliminate_redundant_comparison (enum tree_code opcode,
1223                                 VEC (operand_entry_t, heap) **ops,
1224                                 unsigned int currindex,
1225                                 operand_entry_t curr)
1226 {
1227   tree op1, op2;
1228   enum tree_code lcode, rcode;
1229   gimple def1, def2;
1230   int i;
1231   operand_entry_t oe;
1232
1233   if (opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
1234     return false;
1235
1236   /* Check that CURR is a comparison.  */
1237   if (TREE_CODE (curr->op) != SSA_NAME)
1238     return false;
1239   def1 = SSA_NAME_DEF_STMT (curr->op);
1240   if (!is_gimple_assign (def1))
1241     return false;
1242   lcode = gimple_assign_rhs_code (def1);
1243   if (TREE_CODE_CLASS (lcode) != tcc_comparison)
1244     return false;
1245   op1 = gimple_assign_rhs1 (def1);
1246   op2 = gimple_assign_rhs2 (def1);
1247
1248   /* Now look for a similar comparison in the remaining OPS.  */
1249   for (i = currindex + 1;
1250        VEC_iterate (operand_entry_t, *ops, i, oe);
1251        i++)
1252     {
1253       tree t;
1254
1255       if (TREE_CODE (oe->op) != SSA_NAME)
1256         continue;
1257       def2 = SSA_NAME_DEF_STMT (oe->op);
1258       if (!is_gimple_assign (def2))
1259         continue;
1260       rcode = gimple_assign_rhs_code (def2);
1261       if (TREE_CODE_CLASS (rcode) != tcc_comparison)
1262         continue;
1263       if (operand_equal_p (op1, gimple_assign_rhs1 (def2), 0)
1264           && operand_equal_p (op2, gimple_assign_rhs2 (def2), 0))
1265         ;
1266       else if (operand_equal_p (op1, gimple_assign_rhs2 (def2), 0)
1267                && operand_equal_p (op2, gimple_assign_rhs1 (def2), 0))
1268         rcode = swap_tree_comparison (rcode);
1269       else
1270         continue;
1271
1272       /* If we got here, we have a match.  See if we can combine the
1273          two comparisons.  */
1274       t = combine_comparisons (UNKNOWN_LOCATION,
1275                                (opcode == BIT_IOR_EXPR
1276                                 ? TRUTH_OR_EXPR : TRUTH_AND_EXPR),
1277                                lcode, rcode, TREE_TYPE (curr->op), op1, op2);
1278       if (!t)
1279         continue;
1280       if (dump_file && (dump_flags & TDF_DETAILS))
1281         {
1282           fprintf (dump_file, "Equivalence: ");
1283           print_generic_expr (dump_file, curr->op, 0);
1284           fprintf (dump_file, " %s ", op_symbol_code (opcode));
1285           print_generic_expr (dump_file, oe->op, 0);
1286           fprintf (dump_file, " -> ");
1287           print_generic_expr (dump_file, t, 0);
1288           fprintf (dump_file, "\n");
1289         }
1290
1291       /* Now we can delete oe, as it has been subsumed by the new combined
1292          expression t.  */
1293       VEC_ordered_remove (operand_entry_t, *ops, i);
1294       reassociate_stats.ops_eliminated ++;
1295
1296       /* If t is the same as curr->op, we're done.  Otherwise we must
1297          replace curr->op with t.  Special case is if we got a constant
1298          back, in which case we add it to the end instead of in place of
1299          the current entry.  */
1300       if (TREE_CODE (t) == INTEGER_CST)
1301         {
1302           VEC_ordered_remove (operand_entry_t, *ops, currindex);
1303           add_to_ops_vec (ops, t);
1304         }
1305       else if (TREE_CODE (t) != lcode)
1306         {
1307           tree tmpvar;
1308           gimple sum;
1309           enum tree_code subcode;
1310           tree newop1;
1311           tree newop2;
1312           tmpvar = create_tmp_var (TREE_TYPE (t), NULL);
1313           add_referenced_var (tmpvar);
1314           extract_ops_from_tree (t, &subcode, &newop1, &newop2);
1315           sum = build_and_add_sum (tmpvar, newop1, newop2, subcode);
1316           curr->op = gimple_get_lhs (sum);
1317         }
1318       return true;
1319     }
1320
1321   return false;
1322 }
1323
1324 /* Perform various identities and other optimizations on the list of
1325    operand entries, stored in OPS.  The tree code for the binary
1326    operation between all the operands is OPCODE.  */
1327
1328 static void
1329 optimize_ops_list (enum tree_code opcode,
1330                    VEC (operand_entry_t, heap) **ops)
1331 {
1332   unsigned int length = VEC_length (operand_entry_t, *ops);
1333   unsigned int i;
1334   operand_entry_t oe;
1335   operand_entry_t oelast = NULL;
1336   bool iterate = false;
1337
1338   if (length == 1)
1339     return;
1340
1341   oelast = VEC_last (operand_entry_t, *ops);
1342
1343   /* If the last two are constants, pop the constants off, merge them
1344      and try the next two.  */
1345   if (oelast->rank == 0 && is_gimple_min_invariant (oelast->op))
1346     {
1347       operand_entry_t oelm1 = VEC_index (operand_entry_t, *ops, length - 2);
1348
1349       if (oelm1->rank == 0
1350           && is_gimple_min_invariant (oelm1->op)
1351           && useless_type_conversion_p (TREE_TYPE (oelm1->op),
1352                                        TREE_TYPE (oelast->op)))
1353         {
1354           tree folded = fold_binary (opcode, TREE_TYPE (oelm1->op),
1355                                      oelm1->op, oelast->op);
1356
1357           if (folded && is_gimple_min_invariant (folded))
1358             {
1359               if (dump_file && (dump_flags & TDF_DETAILS))
1360                 fprintf (dump_file, "Merging constants\n");
1361
1362               VEC_pop (operand_entry_t, *ops);
1363               VEC_pop (operand_entry_t, *ops);
1364
1365               add_to_ops_vec (ops, folded);
1366               reassociate_stats.constants_eliminated++;
1367
1368               optimize_ops_list (opcode, ops);
1369               return;
1370             }
1371         }
1372     }
1373
1374   eliminate_using_constants (opcode, ops);
1375   oelast = NULL;
1376
1377   for (i = 0; VEC_iterate (operand_entry_t, *ops, i, oe);)
1378     {
1379       bool done = false;
1380
1381       if (eliminate_not_pairs (opcode, ops, i, oe))
1382         return;
1383       if (eliminate_duplicate_pair (opcode, ops, &done, i, oe, oelast)
1384           || (!done && eliminate_plus_minus_pair (opcode, ops, i, oe))
1385           || (!done && eliminate_redundant_comparison (opcode, ops, i, oe)))
1386         {
1387           if (done)
1388             return;
1389           iterate = true;
1390           oelast = NULL;
1391           continue;
1392         }
1393       oelast = oe;
1394       i++;
1395     }
1396
1397   length  = VEC_length (operand_entry_t, *ops);
1398   oelast = VEC_last (operand_entry_t, *ops);
1399
1400   if (iterate)
1401     optimize_ops_list (opcode, ops);
1402 }
1403
1404 /* Return true if OPERAND is defined by a PHI node which uses the LHS
1405    of STMT in it's operands.  This is also known as a "destructive
1406    update" operation.  */
1407
1408 static bool
1409 is_phi_for_stmt (gimple stmt, tree operand)
1410 {
1411   gimple def_stmt;
1412   tree lhs;
1413   use_operand_p arg_p;
1414   ssa_op_iter i;
1415
1416   if (TREE_CODE (operand) != SSA_NAME)
1417     return false;
1418
1419   lhs = gimple_assign_lhs (stmt);
1420
1421   def_stmt = SSA_NAME_DEF_STMT (operand);
1422   if (gimple_code (def_stmt) != GIMPLE_PHI)
1423     return false;
1424
1425   FOR_EACH_PHI_ARG (arg_p, def_stmt, i, SSA_OP_USE)
1426     if (lhs == USE_FROM_PTR (arg_p))
1427       return true;
1428   return false;
1429 }
1430
1431 /* Remove def stmt of VAR if VAR has zero uses and recurse
1432    on rhs1 operand if so.  */
1433
1434 static void
1435 remove_visited_stmt_chain (tree var)
1436 {
1437   gimple stmt;
1438   gimple_stmt_iterator gsi;
1439
1440   while (1)
1441     {
1442       if (TREE_CODE (var) != SSA_NAME || !has_zero_uses (var))
1443         return;
1444       stmt = SSA_NAME_DEF_STMT (var);
1445       if (!is_gimple_assign (stmt)
1446           || !gimple_visited_p (stmt))
1447         return;
1448       var = gimple_assign_rhs1 (stmt);
1449       gsi = gsi_for_stmt (stmt);
1450       gsi_remove (&gsi, true);
1451       release_defs (stmt);
1452     }
1453 }
1454
1455 /* Recursively rewrite our linearized statements so that the operators
1456    match those in OPS[OPINDEX], putting the computation in rank
1457    order.  */
1458
1459 static void
1460 rewrite_expr_tree (gimple stmt, unsigned int opindex,
1461                    VEC(operand_entry_t, heap) * ops, bool moved)
1462 {
1463   tree rhs1 = gimple_assign_rhs1 (stmt);
1464   tree rhs2 = gimple_assign_rhs2 (stmt);
1465   operand_entry_t oe;
1466
1467   /* If we have three operands left, then we want to make sure the one
1468      that gets the double binary op are the ones with the same rank.
1469
1470      The alternative we try is to see if this is a destructive
1471      update style statement, which is like:
1472      b = phi (a, ...)
1473      a = c + b;
1474      In that case, we want to use the destructive update form to
1475      expose the possible vectorizer sum reduction opportunity.
1476      In that case, the third operand will be the phi node.
1477
1478      We could, of course, try to be better as noted above, and do a
1479      lot of work to try to find these opportunities in >3 operand
1480      cases, but it is unlikely to be worth it.  */
1481   if (opindex + 3 == VEC_length (operand_entry_t, ops))
1482     {
1483       operand_entry_t oe1, oe2, oe3;
1484
1485       oe1 = VEC_index (operand_entry_t, ops, opindex);
1486       oe2 = VEC_index (operand_entry_t, ops, opindex + 1);
1487       oe3 = VEC_index (operand_entry_t, ops, opindex + 2);
1488
1489       if ((oe1->rank == oe2->rank
1490            && oe2->rank != oe3->rank)
1491           || (is_phi_for_stmt (stmt, oe3->op)
1492               && !is_phi_for_stmt (stmt, oe1->op)
1493               && !is_phi_for_stmt (stmt, oe2->op)))
1494         {
1495           struct operand_entry temp = *oe3;
1496           oe3->op = oe1->op;
1497           oe3->rank = oe1->rank;
1498           oe1->op = temp.op;
1499           oe1->rank= temp.rank;
1500         }
1501       else if ((oe1->rank == oe3->rank
1502                 && oe2->rank != oe3->rank)
1503                || (is_phi_for_stmt (stmt, oe2->op)
1504                    && !is_phi_for_stmt (stmt, oe1->op)
1505                    && !is_phi_for_stmt (stmt, oe3->op)))
1506         {
1507           struct operand_entry temp = *oe2;
1508           oe2->op = oe1->op;
1509           oe2->rank = oe1->rank;
1510           oe1->op = temp.op;
1511           oe1->rank= temp.rank;
1512         }
1513     }
1514
1515   /* The final recursion case for this function is that you have
1516      exactly two operations left.
1517      If we had one exactly one op in the entire list to start with, we
1518      would have never called this function, and the tail recursion
1519      rewrites them one at a time.  */
1520   if (opindex + 2 == VEC_length (operand_entry_t, ops))
1521     {
1522       operand_entry_t oe1, oe2;
1523
1524       oe1 = VEC_index (operand_entry_t, ops, opindex);
1525       oe2 = VEC_index (operand_entry_t, ops, opindex + 1);
1526
1527       if (rhs1 != oe1->op || rhs2 != oe2->op)
1528         {
1529           if (dump_file && (dump_flags & TDF_DETAILS))
1530             {
1531               fprintf (dump_file, "Transforming ");
1532               print_gimple_stmt (dump_file, stmt, 0, 0);
1533             }
1534
1535           gimple_assign_set_rhs1 (stmt, oe1->op);
1536           gimple_assign_set_rhs2 (stmt, oe2->op);
1537           update_stmt (stmt);
1538           if (rhs1 != oe1->op && rhs1 != oe2->op)
1539             remove_visited_stmt_chain (rhs1);
1540
1541           if (dump_file && (dump_flags & TDF_DETAILS))
1542             {
1543               fprintf (dump_file, " into ");
1544               print_gimple_stmt (dump_file, stmt, 0, 0);
1545             }
1546
1547         }
1548       return;
1549     }
1550
1551   /* If we hit here, we should have 3 or more ops left.  */
1552   gcc_assert (opindex + 2 < VEC_length (operand_entry_t, ops));
1553
1554   /* Rewrite the next operator.  */
1555   oe = VEC_index (operand_entry_t, ops, opindex);
1556
1557   if (oe->op != rhs2)
1558     {
1559       if (!moved)
1560         {
1561           gimple_stmt_iterator gsinow, gsirhs1;
1562           gimple stmt1 = stmt, stmt2;
1563           unsigned int count;
1564
1565           gsinow = gsi_for_stmt (stmt);
1566           count = VEC_length (operand_entry_t, ops) - opindex - 2;
1567           while (count-- != 0)
1568             {
1569               stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt1));
1570               gsirhs1 = gsi_for_stmt (stmt2);
1571               gsi_move_before (&gsirhs1, &gsinow);
1572               gsi_prev (&gsinow);
1573               stmt1 = stmt2;
1574             }
1575           moved = true;
1576         }
1577
1578       if (dump_file && (dump_flags & TDF_DETAILS))
1579         {
1580           fprintf (dump_file, "Transforming ");
1581           print_gimple_stmt (dump_file, stmt, 0, 0);
1582         }
1583
1584       gimple_assign_set_rhs2 (stmt, oe->op);
1585       update_stmt (stmt);
1586
1587       if (dump_file && (dump_flags & TDF_DETAILS))
1588         {
1589           fprintf (dump_file, " into ");
1590           print_gimple_stmt (dump_file, stmt, 0, 0);
1591         }
1592     }
1593   /* Recurse on the LHS of the binary operator, which is guaranteed to
1594      be the non-leaf side.  */
1595   rewrite_expr_tree (SSA_NAME_DEF_STMT (rhs1), opindex + 1, ops, moved);
1596 }
1597
1598 /* Transform STMT, which is really (A +B) + (C + D) into the left
1599    linear form, ((A+B)+C)+D.
1600    Recurse on D if necessary.  */
1601
1602 static void
1603 linearize_expr (gimple stmt)
1604 {
1605   gimple_stmt_iterator gsinow, gsirhs;
1606   gimple binlhs = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
1607   gimple binrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
1608   enum tree_code rhscode = gimple_assign_rhs_code (stmt);
1609   gimple newbinrhs = NULL;
1610   struct loop *loop = loop_containing_stmt (stmt);
1611
1612   gcc_assert (is_reassociable_op (binlhs, rhscode, loop)
1613               && is_reassociable_op (binrhs, rhscode, loop));
1614
1615   gsinow = gsi_for_stmt (stmt);
1616   gsirhs = gsi_for_stmt (binrhs);
1617   gsi_move_before (&gsirhs, &gsinow);
1618
1619   gimple_assign_set_rhs2 (stmt, gimple_assign_rhs1 (binrhs));
1620   gimple_assign_set_rhs1 (binrhs, gimple_assign_lhs (binlhs));
1621   gimple_assign_set_rhs1 (stmt, gimple_assign_lhs (binrhs));
1622
1623   if (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME)
1624     newbinrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
1625
1626   if (dump_file && (dump_flags & TDF_DETAILS))
1627     {
1628       fprintf (dump_file, "Linearized: ");
1629       print_gimple_stmt (dump_file, stmt, 0, 0);
1630     }
1631
1632   reassociate_stats.linearized++;
1633   update_stmt (binrhs);
1634   update_stmt (binlhs);
1635   update_stmt (stmt);
1636
1637   gimple_set_visited (stmt, true);
1638   gimple_set_visited (binlhs, true);
1639   gimple_set_visited (binrhs, true);
1640
1641   /* Tail recurse on the new rhs if it still needs reassociation.  */
1642   if (newbinrhs && is_reassociable_op (newbinrhs, rhscode, loop))
1643     /* ??? This should probably be linearize_expr (newbinrhs) but I don't
1644            want to change the algorithm while converting to tuples.  */
1645     linearize_expr (stmt);
1646 }
1647
1648 /* If LHS has a single immediate use that is a GIMPLE_ASSIGN statement, return
1649    it.  Otherwise, return NULL.  */
1650
1651 static gimple
1652 get_single_immediate_use (tree lhs)
1653 {
1654   use_operand_p immuse;
1655   gimple immusestmt;
1656
1657   if (TREE_CODE (lhs) == SSA_NAME
1658       && single_imm_use (lhs, &immuse, &immusestmt)
1659       && is_gimple_assign (immusestmt))
1660     return immusestmt;
1661
1662   return NULL;
1663 }
1664
1665 /* Recursively negate the value of TONEGATE, and return the SSA_NAME
1666    representing the negated value.  Insertions of any necessary
1667    instructions go before GSI.
1668    This function is recursive in that, if you hand it "a_5" as the
1669    value to negate, and a_5 is defined by "a_5 = b_3 + b_4", it will
1670    transform b_3 + b_4 into a_5 = -b_3 + -b_4.  */
1671
1672 static tree
1673 negate_value (tree tonegate, gimple_stmt_iterator *gsi)
1674 {
1675   gimple negatedefstmt= NULL;
1676   tree resultofnegate;
1677
1678   /* If we are trying to negate a name, defined by an add, negate the
1679      add operands instead.  */
1680   if (TREE_CODE (tonegate) == SSA_NAME)
1681     negatedefstmt = SSA_NAME_DEF_STMT (tonegate);
1682   if (TREE_CODE (tonegate) == SSA_NAME
1683       && is_gimple_assign (negatedefstmt)
1684       && TREE_CODE (gimple_assign_lhs (negatedefstmt)) == SSA_NAME
1685       && has_single_use (gimple_assign_lhs (negatedefstmt))
1686       && gimple_assign_rhs_code (negatedefstmt) == PLUS_EXPR)
1687     {
1688       gimple_stmt_iterator gsi;
1689       tree rhs1 = gimple_assign_rhs1 (negatedefstmt);
1690       tree rhs2 = gimple_assign_rhs2 (negatedefstmt);
1691
1692       gsi = gsi_for_stmt (negatedefstmt);
1693       rhs1 = negate_value (rhs1, &gsi);
1694       gimple_assign_set_rhs1 (negatedefstmt, rhs1);
1695
1696       gsi = gsi_for_stmt (negatedefstmt);
1697       rhs2 = negate_value (rhs2, &gsi);
1698       gimple_assign_set_rhs2 (negatedefstmt, rhs2);
1699
1700       update_stmt (negatedefstmt);
1701       return gimple_assign_lhs (negatedefstmt);
1702     }
1703
1704   tonegate = fold_build1 (NEGATE_EXPR, TREE_TYPE (tonegate), tonegate);
1705   resultofnegate = force_gimple_operand_gsi (gsi, tonegate, true,
1706                                              NULL_TREE, true, GSI_SAME_STMT);
1707   return resultofnegate;
1708 }
1709
1710 /* Return true if we should break up the subtract in STMT into an add
1711    with negate.  This is true when we the subtract operands are really
1712    adds, or the subtract itself is used in an add expression.  In
1713    either case, breaking up the subtract into an add with negate
1714    exposes the adds to reassociation.  */
1715
1716 static bool
1717 should_break_up_subtract (gimple stmt)
1718 {
1719   tree lhs = gimple_assign_lhs (stmt);
1720   tree binlhs = gimple_assign_rhs1 (stmt);
1721   tree binrhs = gimple_assign_rhs2 (stmt);
1722   gimple immusestmt;
1723   struct loop *loop = loop_containing_stmt (stmt);
1724
1725   if (TREE_CODE (binlhs) == SSA_NAME
1726       && is_reassociable_op (SSA_NAME_DEF_STMT (binlhs), PLUS_EXPR, loop))
1727     return true;
1728
1729   if (TREE_CODE (binrhs) == SSA_NAME
1730       && is_reassociable_op (SSA_NAME_DEF_STMT (binrhs), PLUS_EXPR, loop))
1731     return true;
1732
1733   if (TREE_CODE (lhs) == SSA_NAME
1734       && (immusestmt = get_single_immediate_use (lhs))
1735       && is_gimple_assign (immusestmt)
1736       && (gimple_assign_rhs_code (immusestmt) == PLUS_EXPR
1737           ||  gimple_assign_rhs_code (immusestmt) == MULT_EXPR))
1738     return true;
1739   return false;
1740 }
1741
1742 /* Transform STMT from A - B into A + -B.  */
1743
1744 static void
1745 break_up_subtract (gimple stmt, gimple_stmt_iterator *gsip)
1746 {
1747   tree rhs1 = gimple_assign_rhs1 (stmt);
1748   tree rhs2 = gimple_assign_rhs2 (stmt);
1749
1750   if (dump_file && (dump_flags & TDF_DETAILS))
1751     {
1752       fprintf (dump_file, "Breaking up subtract ");
1753       print_gimple_stmt (dump_file, stmt, 0, 0);
1754     }
1755
1756   rhs2 = negate_value (rhs2, gsip);
1757   gimple_assign_set_rhs_with_ops (gsip, PLUS_EXPR, rhs1, rhs2);
1758   update_stmt (stmt);
1759 }
1760
1761 /* Recursively linearize a binary expression that is the RHS of STMT.
1762    Place the operands of the expression tree in the vector named OPS.  */
1763
1764 static void
1765 linearize_expr_tree (VEC(operand_entry_t, heap) **ops, gimple stmt,
1766                      bool is_associative, bool set_visited)
1767 {
1768   tree binlhs = gimple_assign_rhs1 (stmt);
1769   tree binrhs = gimple_assign_rhs2 (stmt);
1770   gimple binlhsdef, binrhsdef;
1771   bool binlhsisreassoc = false;
1772   bool binrhsisreassoc = false;
1773   enum tree_code rhscode = gimple_assign_rhs_code (stmt);
1774   struct loop *loop = loop_containing_stmt (stmt);
1775
1776   if (set_visited)
1777     gimple_set_visited (stmt, true);
1778
1779   if (TREE_CODE (binlhs) == SSA_NAME)
1780     {
1781       binlhsdef = SSA_NAME_DEF_STMT (binlhs);
1782       binlhsisreassoc = is_reassociable_op (binlhsdef, rhscode, loop);
1783     }
1784
1785   if (TREE_CODE (binrhs) == SSA_NAME)
1786     {
1787       binrhsdef = SSA_NAME_DEF_STMT (binrhs);
1788       binrhsisreassoc = is_reassociable_op (binrhsdef, rhscode, loop);
1789     }
1790
1791   /* If the LHS is not reassociable, but the RHS is, we need to swap
1792      them.  If neither is reassociable, there is nothing we can do, so
1793      just put them in the ops vector.  If the LHS is reassociable,
1794      linearize it.  If both are reassociable, then linearize the RHS
1795      and the LHS.  */
1796
1797   if (!binlhsisreassoc)
1798     {
1799       tree temp;
1800
1801       /* If this is not a associative operation like division, give up.  */
1802       if (!is_associative)
1803         {
1804           add_to_ops_vec (ops, binrhs);
1805           return;
1806         }
1807
1808       if (!binrhsisreassoc)
1809         {
1810           add_to_ops_vec (ops, binrhs);
1811           add_to_ops_vec (ops, binlhs);
1812           return;
1813         }
1814
1815       if (dump_file && (dump_flags & TDF_DETAILS))
1816         {
1817           fprintf (dump_file, "swapping operands of ");
1818           print_gimple_stmt (dump_file, stmt, 0, 0);
1819         }
1820
1821       swap_tree_operands (stmt,
1822                           gimple_assign_rhs1_ptr (stmt),
1823                           gimple_assign_rhs2_ptr (stmt));
1824       update_stmt (stmt);
1825
1826       if (dump_file && (dump_flags & TDF_DETAILS))
1827         {
1828           fprintf (dump_file, " is now ");
1829           print_gimple_stmt (dump_file, stmt, 0, 0);
1830         }
1831
1832       /* We want to make it so the lhs is always the reassociative op,
1833          so swap.  */
1834       temp = binlhs;
1835       binlhs = binrhs;
1836       binrhs = temp;
1837     }
1838   else if (binrhsisreassoc)
1839     {
1840       linearize_expr (stmt);
1841       binlhs = gimple_assign_rhs1 (stmt);
1842       binrhs = gimple_assign_rhs2 (stmt);
1843     }
1844
1845   gcc_assert (TREE_CODE (binrhs) != SSA_NAME
1846               || !is_reassociable_op (SSA_NAME_DEF_STMT (binrhs),
1847                                       rhscode, loop));
1848   linearize_expr_tree (ops, SSA_NAME_DEF_STMT (binlhs),
1849                        is_associative, set_visited);
1850   add_to_ops_vec (ops, binrhs);
1851 }
1852
1853 /* Repropagate the negates back into subtracts, since no other pass
1854    currently does it.  */
1855
1856 static void
1857 repropagate_negates (void)
1858 {
1859   unsigned int i = 0;
1860   tree negate;
1861
1862   for (i = 0; VEC_iterate (tree, plus_negates, i, negate); i++)
1863     {
1864       gimple user = get_single_immediate_use (negate);
1865
1866       if (!user || !is_gimple_assign (user))
1867         continue;
1868
1869       /* The negate operand can be either operand of a PLUS_EXPR
1870          (it can be the LHS if the RHS is a constant for example).
1871
1872          Force the negate operand to the RHS of the PLUS_EXPR, then
1873          transform the PLUS_EXPR into a MINUS_EXPR.  */
1874       if (gimple_assign_rhs_code (user) == PLUS_EXPR)
1875         {
1876           /* If the negated operand appears on the LHS of the
1877              PLUS_EXPR, exchange the operands of the PLUS_EXPR
1878              to force the negated operand to the RHS of the PLUS_EXPR.  */
1879           if (gimple_assign_rhs1 (user) == negate)
1880             {
1881               swap_tree_operands (user,
1882                                   gimple_assign_rhs1_ptr (user),
1883                                   gimple_assign_rhs2_ptr (user));
1884             }
1885
1886           /* Now transform the PLUS_EXPR into a MINUS_EXPR and replace
1887              the RHS of the PLUS_EXPR with the operand of the NEGATE_EXPR.  */
1888           if (gimple_assign_rhs2 (user) == negate)
1889             {
1890               tree rhs1 = gimple_assign_rhs1 (user);
1891               tree rhs2 = get_unary_op (negate, NEGATE_EXPR);
1892               gimple_stmt_iterator gsi = gsi_for_stmt (user);
1893               gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, rhs1, rhs2);
1894               update_stmt (user);
1895             }
1896         }
1897       else if (gimple_assign_rhs_code (user) == MINUS_EXPR)
1898         {
1899           if (gimple_assign_rhs1 (user) == negate)
1900             {
1901               /* We have
1902                    x = -a
1903                    y = x - b
1904                  which we transform into
1905                    x = a + b
1906                    y = -x .
1907                  This pushes down the negate which we possibly can merge
1908                  into some other operation, hence insert it into the
1909                  plus_negates vector.  */
1910               gimple feed = SSA_NAME_DEF_STMT (negate);
1911               tree a = gimple_assign_rhs1 (feed);
1912               tree rhs2 = gimple_assign_rhs2 (user);
1913               gimple_stmt_iterator gsi = gsi_for_stmt (feed), gsi2;
1914               gimple_replace_lhs (feed, negate);
1915               gimple_assign_set_rhs_with_ops (&gsi, PLUS_EXPR, a, rhs2);
1916               update_stmt (gsi_stmt (gsi));
1917               gsi2 = gsi_for_stmt (user);
1918               gimple_assign_set_rhs_with_ops (&gsi2, NEGATE_EXPR, negate, NULL);
1919               update_stmt (gsi_stmt (gsi2));
1920               gsi_move_before (&gsi, &gsi2);
1921               VEC_safe_push (tree, heap, plus_negates,
1922                              gimple_assign_lhs (gsi_stmt (gsi2)));
1923             }
1924           else
1925             {
1926               /* Transform "x = -a; y = b - x" into "y = b + a", getting
1927                  rid of one operation.  */
1928               gimple feed = SSA_NAME_DEF_STMT (negate);
1929               tree a = gimple_assign_rhs1 (feed);
1930               tree rhs1 = gimple_assign_rhs1 (user);
1931               gimple_stmt_iterator gsi = gsi_for_stmt (user);
1932               gimple_assign_set_rhs_with_ops (&gsi, PLUS_EXPR, rhs1, a);
1933               update_stmt (gsi_stmt (gsi));
1934             }
1935         }
1936     }
1937 }
1938
1939 /* Returns true if OP is of a type for which we can do reassociation.
1940    That is for integral or non-saturating fixed-point types, and for
1941    floating point type when associative-math is enabled.  */
1942
1943 static bool
1944 can_reassociate_p (tree op)
1945 {
1946   tree type = TREE_TYPE (op);
1947   if (INTEGRAL_TYPE_P (type)
1948       || NON_SAT_FIXED_POINT_TYPE_P (type)
1949       || (flag_associative_math && FLOAT_TYPE_P (type)))
1950     return true;
1951   return false;
1952 }
1953
1954 /* Break up subtract operations in block BB.
1955
1956    We do this top down because we don't know whether the subtract is
1957    part of a possible chain of reassociation except at the top.
1958
1959    IE given
1960    d = f + g
1961    c = a + e
1962    b = c - d
1963    q = b - r
1964    k = t - q
1965
1966    we want to break up k = t - q, but we won't until we've transformed q
1967    = b - r, which won't be broken up until we transform b = c - d.
1968
1969    En passant, clear the GIMPLE visited flag on every statement.  */
1970
1971 static void
1972 break_up_subtract_bb (basic_block bb)
1973 {
1974   gimple_stmt_iterator gsi;
1975   basic_block son;
1976
1977   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1978     {
1979       gimple stmt = gsi_stmt (gsi);
1980       gimple_set_visited (stmt, false);
1981
1982       if (!is_gimple_assign (stmt)
1983           || !can_reassociate_p (gimple_assign_lhs (stmt)))
1984         continue;
1985
1986       /* Look for simple gimple subtract operations.  */
1987       if (gimple_assign_rhs_code (stmt) == MINUS_EXPR)
1988         {
1989           if (!can_reassociate_p (gimple_assign_rhs1 (stmt))
1990               || !can_reassociate_p (gimple_assign_rhs2 (stmt)))
1991             continue;
1992
1993           /* Check for a subtract used only in an addition.  If this
1994              is the case, transform it into add of a negate for better
1995              reassociation.  IE transform C = A-B into C = A + -B if C
1996              is only used in an addition.  */
1997           if (should_break_up_subtract (stmt))
1998             break_up_subtract (stmt, &gsi);
1999         }
2000       else if (gimple_assign_rhs_code (stmt) == NEGATE_EXPR
2001                && can_reassociate_p (gimple_assign_rhs1 (stmt)))
2002         VEC_safe_push (tree, heap, plus_negates, gimple_assign_lhs (stmt));
2003     }
2004   for (son = first_dom_son (CDI_DOMINATORS, bb);
2005        son;
2006        son = next_dom_son (CDI_DOMINATORS, son))
2007     break_up_subtract_bb (son);
2008 }
2009
2010 /* Reassociate expressions in basic block BB and its post-dominator as
2011    children.  */
2012
2013 static void
2014 reassociate_bb (basic_block bb)
2015 {
2016   gimple_stmt_iterator gsi;
2017   basic_block son;
2018
2019   for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
2020     {
2021       gimple stmt = gsi_stmt (gsi);
2022
2023       if (is_gimple_assign (stmt))
2024         {
2025           tree lhs, rhs1, rhs2;
2026           enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
2027
2028           /* If this is not a gimple binary expression, there is
2029              nothing for us to do with it.  */
2030           if (get_gimple_rhs_class (rhs_code) != GIMPLE_BINARY_RHS)
2031             continue;
2032
2033           /* If this was part of an already processed statement,
2034              we don't need to touch it again. */
2035           if (gimple_visited_p (stmt))
2036             {
2037               /* This statement might have become dead because of previous
2038                  reassociations.  */
2039               if (has_zero_uses (gimple_get_lhs (stmt)))
2040                 {
2041                   gsi_remove (&gsi, true);
2042                   release_defs (stmt);
2043                   /* We might end up removing the last stmt above which
2044                      places the iterator to the end of the sequence.
2045                      Reset it to the last stmt in this case which might
2046                      be the end of the sequence as well if we removed
2047                      the last statement of the sequence.  In which case
2048                      we need to bail out.  */
2049                   if (gsi_end_p (gsi))
2050                     {
2051                       gsi = gsi_last_bb (bb);
2052                       if (gsi_end_p (gsi))
2053                         break;
2054                     }
2055                 }
2056               continue;
2057             }
2058
2059           lhs = gimple_assign_lhs (stmt);
2060           rhs1 = gimple_assign_rhs1 (stmt);
2061           rhs2 = gimple_assign_rhs2 (stmt);
2062
2063           if (!can_reassociate_p (lhs)
2064               || !can_reassociate_p (rhs1)
2065               || !can_reassociate_p (rhs2))
2066             continue;
2067
2068           if (associative_tree_code (rhs_code))
2069             {
2070               VEC(operand_entry_t, heap) *ops = NULL;
2071
2072               /* There may be no immediate uses left by the time we
2073                  get here because we may have eliminated them all.  */
2074               if (TREE_CODE (lhs) == SSA_NAME && has_zero_uses (lhs))
2075                 continue;
2076
2077               gimple_set_visited (stmt, true);
2078               linearize_expr_tree (&ops, stmt, true, true);
2079               qsort (VEC_address (operand_entry_t, ops),
2080                      VEC_length (operand_entry_t, ops),
2081                      sizeof (operand_entry_t),
2082                      sort_by_operand_rank);
2083               optimize_ops_list (rhs_code, &ops);
2084               if (undistribute_ops_list (rhs_code, &ops,
2085                                          loop_containing_stmt (stmt)))
2086                 {
2087                   qsort (VEC_address (operand_entry_t, ops),
2088                          VEC_length (operand_entry_t, ops),
2089                          sizeof (operand_entry_t),
2090                          sort_by_operand_rank);
2091                   optimize_ops_list (rhs_code, &ops);
2092                 }
2093
2094               if (VEC_length (operand_entry_t, ops) == 1)
2095                 {
2096                   if (dump_file && (dump_flags & TDF_DETAILS))
2097                     {
2098                       fprintf (dump_file, "Transforming ");
2099                       print_gimple_stmt (dump_file, stmt, 0, 0);
2100                     }
2101
2102                   rhs1 = gimple_assign_rhs1 (stmt);
2103                   gimple_assign_set_rhs_from_tree (&gsi,
2104                                                    VEC_last (operand_entry_t,
2105                                                              ops)->op);
2106                   update_stmt (stmt);
2107                   remove_visited_stmt_chain (rhs1);
2108
2109                   if (dump_file && (dump_flags & TDF_DETAILS))
2110                     {
2111                       fprintf (dump_file, " into ");
2112                       print_gimple_stmt (dump_file, stmt, 0, 0);
2113                     }
2114                 }
2115               else
2116                 rewrite_expr_tree (stmt, 0, ops, false);
2117
2118               VEC_free (operand_entry_t, heap, ops);
2119             }
2120         }
2121     }
2122   for (son = first_dom_son (CDI_POST_DOMINATORS, bb);
2123        son;
2124        son = next_dom_son (CDI_POST_DOMINATORS, son))
2125     reassociate_bb (son);
2126 }
2127
2128 void dump_ops_vector (FILE *file, VEC (operand_entry_t, heap) *ops);
2129 void debug_ops_vector (VEC (operand_entry_t, heap) *ops);
2130
2131 /* Dump the operand entry vector OPS to FILE.  */
2132
2133 void
2134 dump_ops_vector (FILE *file, VEC (operand_entry_t, heap) *ops)
2135 {
2136   operand_entry_t oe;
2137   unsigned int i;
2138
2139   for (i = 0; VEC_iterate (operand_entry_t, ops, i, oe); i++)
2140     {
2141       fprintf (file, "Op %d -> rank: %d, tree: ", i, oe->rank);
2142       print_generic_expr (file, oe->op, 0);
2143     }
2144 }
2145
2146 /* Dump the operand entry vector OPS to STDERR.  */
2147
2148 void
2149 debug_ops_vector (VEC (operand_entry_t, heap) *ops)
2150 {
2151   dump_ops_vector (stderr, ops);
2152 }
2153
2154 static void
2155 do_reassoc (void)
2156 {
2157   break_up_subtract_bb (ENTRY_BLOCK_PTR);
2158   reassociate_bb (EXIT_BLOCK_PTR);
2159 }
2160
2161 /* Initialize the reassociation pass.  */
2162
2163 static void
2164 init_reassoc (void)
2165 {
2166   int i;
2167   long rank = 2;
2168   tree param;
2169   int *bbs = XNEWVEC (int, last_basic_block + 1);
2170
2171   /* Find the loops, so that we can prevent moving calculations in
2172      them.  */
2173   loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
2174
2175   memset (&reassociate_stats, 0, sizeof (reassociate_stats));
2176
2177   operand_entry_pool = create_alloc_pool ("operand entry pool",
2178                                           sizeof (struct operand_entry), 30);
2179   next_operand_entry_id = 0;
2180
2181   /* Reverse RPO (Reverse Post Order) will give us something where
2182      deeper loops come later.  */
2183   pre_and_rev_post_order_compute (NULL, bbs, false);
2184   bb_rank = XCNEWVEC (long, last_basic_block + 1);
2185   operand_rank = pointer_map_create ();
2186
2187   /* Give each argument a distinct rank.   */
2188   for (param = DECL_ARGUMENTS (current_function_decl);
2189        param;
2190        param = TREE_CHAIN (param))
2191     {
2192       if (gimple_default_def (cfun, param) != NULL)
2193         {
2194           tree def = gimple_default_def (cfun, param);
2195           insert_operand_rank (def, ++rank);
2196         }
2197     }
2198
2199   /* Give the chain decl a distinct rank. */
2200   if (cfun->static_chain_decl != NULL)
2201     {
2202       tree def = gimple_default_def (cfun, cfun->static_chain_decl);
2203       if (def != NULL)
2204         insert_operand_rank (def, ++rank);
2205     }
2206
2207   /* Set up rank for each BB  */
2208   for (i = 0; i < n_basic_blocks - NUM_FIXED_BLOCKS; i++)
2209     bb_rank[bbs[i]] = ++rank  << 16;
2210
2211   free (bbs);
2212   calculate_dominance_info (CDI_POST_DOMINATORS);
2213   plus_negates = NULL;
2214 }
2215
2216 /* Cleanup after the reassociation pass, and print stats if
2217    requested.  */
2218
2219 static void
2220 fini_reassoc (void)
2221 {
2222   statistics_counter_event (cfun, "Linearized",
2223                             reassociate_stats.linearized);
2224   statistics_counter_event (cfun, "Constants eliminated",
2225                             reassociate_stats.constants_eliminated);
2226   statistics_counter_event (cfun, "Ops eliminated",
2227                             reassociate_stats.ops_eliminated);
2228   statistics_counter_event (cfun, "Statements rewritten",
2229                             reassociate_stats.rewritten);
2230
2231   pointer_map_destroy (operand_rank);
2232   free_alloc_pool (operand_entry_pool);
2233   free (bb_rank);
2234   VEC_free (tree, heap, plus_negates);
2235   free_dominance_info (CDI_POST_DOMINATORS);
2236   loop_optimizer_finalize ();
2237 }
2238
2239 /* Gate and execute functions for Reassociation.  */
2240
2241 static unsigned int
2242 execute_reassoc (void)
2243 {
2244   init_reassoc ();
2245
2246   do_reassoc ();
2247   repropagate_negates ();
2248
2249   fini_reassoc ();
2250   return 0;
2251 }
2252
2253 static bool
2254 gate_tree_ssa_reassoc (void)
2255 {
2256   return flag_tree_reassoc != 0;
2257 }
2258
2259 struct gimple_opt_pass pass_reassoc =
2260 {
2261  {
2262   GIMPLE_PASS,
2263   "reassoc",                            /* name */
2264   gate_tree_ssa_reassoc,                /* gate */
2265   execute_reassoc,                      /* execute */
2266   NULL,                                 /* sub */
2267   NULL,                                 /* next */
2268   0,                                    /* static_pass_number */
2269   TV_TREE_REASSOC,                      /* tv_id */
2270   PROP_cfg | PROP_ssa,                  /* properties_required */
2271   0,                                    /* properties_provided */
2272   0,                                    /* properties_destroyed */
2273   0,                                    /* todo_flags_start */
2274   TODO_dump_func | TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2275  }
2276 };
2277