Debian Codegraph @

gcc/tree-ssa-reassoc.cc

raw
1 /* Reassociation for trees.
2 Copyright (C) 2005-2025 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <[email protected]>
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 "backend.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "cfghooks.h"
30 #include "alloc-pool.h"
31 #include "tree-pass.h"
32 #include "memmodel.h"
33 #include "tm_p.h"
34 #include "ssa.h"
35 #include "optabs-tree.h"
36 #include "gimple-pretty-print.h"
37 #include "diagnostic-core.h"
38 #include "fold-const.h"
39 #include "stor-layout.h"
40 #include "cfganal.h"
41 #include "gimple-iterator.h"
42 #include "gimple-fold.h"
43 #include "tree-eh.h"
44 #include "gimplify-me.h"
45 #include "tree-cfg.h"
46 #include "tree-ssa-loop.h"
47 #include "flags.h"
48 #include "tree-ssa.h"
49 #include "langhooks.h"
50 #include "cfgloop.h"
51 #include "builtins.h"
52 #include "gimplify.h"
53 #include "case-cfn-macros.h"
54 #include "tree-ssa-reassoc.h"
55 #include "tree-ssa-math-opts.h"
56 #include "gimple-range.h"
57 #include "internal-fn.h"
58
59 /* This is a simple global reassociation pass. It is, in part, based
60 on the LLVM pass of the same name (They do some things more/less
61 than we do, in different orders, etc).
62
63 It consists of five steps:
64
65 1. Breaking up subtract operations into addition + negate, where
66 it would promote the reassociation of adds.
67
68 2. Left linearization of the expression trees, so that (A+B)+(C+D)
69 becomes (((A+B)+C)+D), which is easier for us to rewrite later.
70 During linearization, we place the operands of the binary
71 expressions into a vector of operand_entry_*
72
73 3. Optimization of the operand lists, eliminating things like a +
74 -a, a & a, etc.
75
76 3a. Combine repeated factors with the same occurrence counts
77 into a __builtin_powi call that will later be optimized into
78 an optimal number of multiplies.
79
80 4. Rewrite the expression trees we linearized and optimized so
81 they are in proper rank order.
82
83 5. Repropagate negates, as nothing else will clean it up ATM.
84
85 A bit of theory on #4, since nobody seems to write anything down
86 about why it makes sense to do it the way they do it:
87
88 We could do this much nicer theoretically, but don't (for reasons
89 explained after how to do it theoretically nice :P).
90
91 In order to promote the most redundancy elimination, you want
92 binary expressions whose operands are the same rank (or
93 preferably, the same value) exposed to the redundancy eliminator,
94 for possible elimination.
95
96 So the way to do this if we really cared, is to build the new op
97 tree from the leaves to the roots, merging as you go, and putting the
98 new op on the end of the worklist, until you are left with one
99 thing on the worklist.
100
101 IE if you have to rewrite the following set of operands (listed with
102 rank in parentheses), with opcode PLUS_EXPR:
103
104 a (1), b (1), c (1), d (2), e (2)
105
106
107 We start with our merge worklist empty, and the ops list with all of
108 those on it.
109
110 You want to first merge all leaves of the same rank, as much as
111 possible.
112
113 So first build a binary op of
114
115 mergetmp = a + b, and put "mergetmp" on the merge worklist.
116
117 Because there is no three operand form of PLUS_EXPR, c is not going to
118 be exposed to redundancy elimination as a rank 1 operand.
119
120 So you might as well throw it on the merge worklist (you could also
121 consider it to now be a rank two operand, and merge it with d and e,
122 but in this case, you then have evicted e from a binary op. So at
123 least in this situation, you can't win.)
124
125 Then build a binary op of d + e
126 mergetmp2 = d + e
127
128 and put mergetmp2 on the merge worklist.
129
130 so merge worklist = {mergetmp, c, mergetmp2}
131
132 Continue building binary ops of these operations until you have only
133 one operation left on the worklist.
134
135 So we have
136
137 build binary op
138 mergetmp3 = mergetmp + c
139
140 worklist = {mergetmp2, mergetmp3}
141
142 mergetmp4 = mergetmp2 + mergetmp3
143
144 worklist = {mergetmp4}
145
146 because we have one operation left, we can now just set the original
147 statement equal to the result of that operation.
148
149 This will at least expose a + b and d + e to redundancy elimination
150 as binary operations.
151
152 For extra points, you can reuse the old statements to build the
153 mergetmps, since you shouldn't run out.
154
155 So why don't we do this?
156
157 Because it's expensive, and rarely will help. Most trees we are
158 reassociating have 3 or less ops. If they have 2 ops, they already
159 will be written into a nice single binary op. If you have 3 ops, a
160 single simple check suffices to tell you whether the first two are of the
161 same rank. If so, you know to order it
162
163 mergetmp = op1 + op2
164 newstmt = mergetmp + op3
165
166 instead of
167 mergetmp = op2 + op3
168 newstmt = mergetmp + op1
169
170 If all three are of the same rank, you can't expose them all in a
171 single binary operator anyway, so the above is *still* the best you
172 can do.
173
174 Thus, this is what we do. When we have three ops left, we check to see
175 what order to put them in, and call it a day. As a nod to vector sum
176 reduction, we check if any of the ops are really a phi node that is a
177 destructive update for the associating op, and keep the destructive
178 update together for vector sum reduction recognition. */
179
180 /* Enable insertion of __builtin_powi calls during execute_reassoc. See
181 point 3a in the pass header comment. */
182 static bool reassoc_insert_powi_p;
183
184 /* Enable biasing ranks of loop accumulators. We don't want this before
185 vectorization, since it interferes with reduction chains. */
186 static bool reassoc_bias_loop_carried_phi_ranks_p;
187
188 /* Statistics */
189 static struct
190 {
191 int linearized;
192 int constants_eliminated;
193 int ops_eliminated;
194 int rewritten;
195 int pows_encountered;
196 int pows_created;
197 } reassociate_stats;
198
199
200 static object_allocator<operand_entry> operand_entry_pool
201 ("operand entry pool");
202
203 /* This is used to assign a unique ID to each struct operand_entry
204 so that qsort results are identical on different hosts. */
205 static unsigned int next_operand_entry_id;
206
207 /* Starting rank number for a given basic block, so that we can rank
208 operations using unmovable instructions in that BB based on the bb
209 depth. */
210 static int64_t *bb_rank;
211
212 /* Operand->rank hashtable. */
213 static hash_map<tree, int64_t> *operand_rank;
214
215 /* SSA_NAMEs that are forms of loop accumulators and whose ranks need to be
216 biased. */
217 static auto_bitmap biased_names;
218
219 /* Vector of SSA_NAMEs on which after reassociate_bb is done with
220 all basic blocks the CFG should be adjusted - basic blocks
221 split right after that SSA_NAME's definition statement and before
222 the only use, which must be a bit ior. */
223 static vec<tree> reassoc_branch_fixups;
224
225 /* Forward decls. */
226 static int64_t get_rank (tree);
227 static bool reassoc_stmt_dominates_stmt_p (gimple *, gimple *);
228
229 /* Wrapper around gsi_remove, which adjusts gimple_uid of debug stmts
230 possibly added by gsi_remove. */
231
232 static bool
233 reassoc_remove_stmt (gimple_stmt_iterator *gsi)
234 {
235 gimple *stmt = gsi_stmt (*gsi);
236
237 if (!MAY_HAVE_DEBUG_BIND_STMTS || gimple_code (stmt) == GIMPLE_PHI)
238 return gsi_remove (gsi, true);
239
240 gimple_stmt_iterator prev = *gsi;
241 gsi_prev (&prev);
242 unsigned uid = gimple_uid (stmt);
243 basic_block bb = gimple_bb (stmt);
244 bool ret = gsi_remove (gsi, true);
245 if (!gsi_end_p (prev))
246 gsi_next (&prev);
247 else
248 prev = gsi_start_bb (bb);
249 gimple *end_stmt = gsi_stmt (*gsi);
250 while ((stmt = gsi_stmt (prev)) != end_stmt)
251 {
252 gcc_assert (stmt && is_gimple_debug (stmt) && gimple_uid (stmt) == 0);
253 gimple_set_uid (stmt, uid);
254 gsi_next (&prev);
255 }
256 return ret;
257 }
258
259 /* Bias amount for loop-carried phis. We want this to be larger than
260 the depth of any reassociation tree we can see, but not larger than
261 the rank difference between two blocks. */
262 #define PHI_LOOP_BIAS (1 << 15)
263
264 /* Return TRUE iff PHI_LOOP_BIAS should be propagated from one of the STMT's
265 operands to the STMT's left-hand side. The goal is to preserve bias in code
266 like this:
267
268 x_1 = phi(x_0, x_2)
269 a = x_1 | 1
270 b = a ^ 2
271 .MEM = b
272 c = b + d
273 x_2 = c + e
274
275 That is, we need to preserve bias along single-use chains originating from
276 loop-carried phis. Only GIMPLE_ASSIGNs to SSA_NAMEs are considered to be
277 uses, because only they participate in rank propagation. */
278 static bool
279 propagate_bias_p (gimple *stmt)
280 {
281 use_operand_p use;
282 imm_use_iterator use_iter;
283 gimple *single_use_stmt = NULL;
284
285 if (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_reference)
286 return false;
287
288 FOR_EACH_IMM_USE_FAST (use, use_iter, gimple_assign_lhs (stmt))
289 {
290 gimple *current_use_stmt = USE_STMT (use);
291
292 if (is_gimple_assign (current_use_stmt)
293 && TREE_CODE (gimple_assign_lhs (current_use_stmt)) == SSA_NAME)
294 {
295 if (single_use_stmt != NULL && single_use_stmt != current_use_stmt)
296 return false;
297 single_use_stmt = current_use_stmt;
298 }
299 }
300
301 if (single_use_stmt == NULL)
302 return false;
303
304 if (gimple_bb (stmt)->loop_father
305 != gimple_bb (single_use_stmt)->loop_father)
306 return false;
307
308 return true;
309 }
310
311 /* Rank assigned to a phi statement. If STMT is a loop-carried phi of
312 an innermost loop, and the phi has only a single use which is inside
313 the loop, then the rank is the block rank of the loop latch plus an
314 extra bias for the loop-carried dependence. This causes expressions
315 calculated into an accumulator variable to be independent for each
316 iteration of the loop. If STMT is some other phi, the rank is the
317 block rank of its containing block. */
318 static int64_t
319 phi_rank (gimple *stmt)
320 {
321 basic_block bb = gimple_bb (stmt);
322 class loop *father = bb->loop_father;
323 tree res;
324 unsigned i;
325 use_operand_p use;
326 gimple *use_stmt;
327
328 if (!reassoc_bias_loop_carried_phi_ranks_p)
329 return bb_rank[bb->index];
330
331 /* We only care about real loops (those with a latch). */
332 if (!father->latch)
333 return bb_rank[bb->index];
334
335 /* Interesting phis must be in headers of innermost loops. */
336 if (bb != father->header
337 || father->inner)
338 return bb_rank[bb->index];
339
340 /* Ignore virtual SSA_NAMEs. */
341 res = gimple_phi_result (stmt);
342 if (virtual_operand_p (res))
343 return bb_rank[bb->index];
344
345 /* The phi definition must have a single use, and that use must be
346 within the loop. Otherwise this isn't an accumulator pattern. */
347 if (!single_imm_use (res, &use, &use_stmt)
348 || gimple_bb (use_stmt)->loop_father != father)
349 return bb_rank[bb->index];
350
351 /* Look for phi arguments from within the loop. If found, bias this phi. */
352 for (i = 0; i < gimple_phi_num_args (stmt); i++)
353 {
354 tree arg = gimple_phi_arg_def (stmt, i);
355 if (TREE_CODE (arg) == SSA_NAME
356 && !SSA_NAME_IS_DEFAULT_DEF (arg))
357 {
358 gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
359 if (gimple_bb (def_stmt)->loop_father == father)
360 return bb_rank[father->latch->index] + PHI_LOOP_BIAS;
361 }
362 }
363
364 /* Must be an uninteresting phi. */
365 return bb_rank[bb->index];
366 }
367
368 /* Return the maximum of RANK and the rank that should be propagated
369 from expression OP. For most operands, this is just the rank of OP.
370 For loop-carried phis, the value is zero to avoid undoing the bias
371 in favor of the phi. */
372 static int64_t
373 propagate_rank (int64_t rank, tree op, bool *maybe_biased_p)
374 {
375 int64_t op_rank;
376
377 op_rank = get_rank (op);
378
379 /* Check whether op is biased after the get_rank () call, since it might have
380 updated biased_names. */
381 if (TREE_CODE (op) == SSA_NAME
382 && bitmap_bit_p (biased_names, SSA_NAME_VERSION (op)))
383 {
384 if (maybe_biased_p == NULL)
385 return rank;
386 *maybe_biased_p = true;
387 }
388
389 return MAX (rank, op_rank);
390 }
391
392 /* Look up the operand rank structure for expression E. */
393
394 static inline int64_t
395 find_operand_rank (tree e)
396 {
397 int64_t *slot = operand_rank->get (e);
398 return slot ? *slot : -1;
399 }
400
401 /* Insert {E,RANK} into the operand rank hashtable. */
402
403 static inline void
404 insert_operand_rank (tree e, int64_t rank)
405 {
406 gcc_assert (rank > 0);
407 bool existed = operand_rank->put (e, rank);
408 gcc_assert (!existed);
409 }
410
411 /* Given an expression E, return the rank of the expression. */
412
413 static int64_t
414 get_rank (tree e)
415 {
416 /* SSA_NAME's have the rank of the expression they are the result
417 of.
418 For globals and uninitialized values, the rank is 0.
419 For function arguments, use the pre-setup rank.
420 For PHI nodes, stores, asm statements, etc, we use the rank of
421 the BB.
422 For simple operations, the rank is the maximum rank of any of
423 its operands, or the bb_rank, whichever is less.
424 I make no claims that this is optimal, however, it gives good
425 results. */
426
427 /* We make an exception to the normal ranking system to break
428 dependences of accumulator variables in loops. Suppose we
429 have a simple one-block loop containing:
430
431 x_1 = phi(x_0, x_2)
432 b = a + x_1
433 c = b + d
434 x_2 = c + e
435
436 As shown, each iteration of the calculation into x is fully
437 dependent upon the iteration before it. We would prefer to
438 see this in the form:
439
440 x_1 = phi(x_0, x_2)
441 b = a + d
442 c = b + e
443 x_2 = c + x_1
444
445 If the loop is unrolled, the calculations of b and c from
446 different iterations can be interleaved.
447
448 To obtain this result during reassociation, we bias the rank
449 of the phi definition x_1 upward, when it is recognized as an
450 accumulator pattern. The artificial rank causes it to be
451 added last, providing the desired independence. */
452
453 if (TREE_CODE (e) == SSA_NAME)
454 {
455 ssa_op_iter iter;
456 gimple *stmt;
457 int64_t rank;
458 tree op;
459
460 /* If we already have a rank for this expression, use that. */
461 rank = find_operand_rank (e);
462 if (rank != -1)
463 return rank;
464
465 stmt = SSA_NAME_DEF_STMT (e);
466 if (gimple_code (stmt) == GIMPLE_PHI)
467 {
468 rank = phi_rank (stmt);
469 if (rank != bb_rank[gimple_bb (stmt)->index])
470 bitmap_set_bit (biased_names, SSA_NAME_VERSION (e));
471 }
472
473 else if (!is_gimple_assign (stmt))
474 rank = bb_rank[gimple_bb (stmt)->index];
475
476 else
477 {
478 bool biased_p = false;
479 bool *maybe_biased_p = propagate_bias_p (stmt) ? &biased_p : NULL;
480
481 /* Otherwise, find the maximum rank for the operands. As an
482 exception, remove the bias from loop-carried phis when propagating
483 the rank so that dependent operations are not also biased. */
484 /* Simply walk over all SSA uses - this takes advatage of the
485 fact that non-SSA operands are is_gimple_min_invariant and
486 thus have rank 0. */
487 rank = 0;
488 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
489 rank = propagate_rank (rank, op, maybe_biased_p);
490
491 rank += 1;
492 if (biased_p)
493 bitmap_set_bit (biased_names, SSA_NAME_VERSION (e));
494 }
495
496 if (dump_file && (dump_flags & TDF_DETAILS))
497 {
498 fprintf (dump_file, "Rank for ");
499 print_generic_expr (dump_file, e);
500 fprintf (dump_file, " is %" PRId64 "\n", rank);
501 }
502
503 /* Note the rank in the hashtable so we don't recompute it. */
504 insert_operand_rank (e, rank);
505 return rank;
506 }
507
508 /* Constants, globals, etc., are rank 0 */
509 return 0;
510 }
511
512
513 /* We want integer ones to end up last no matter what, since they are
514 the ones we can do the most with. */
515 #define INTEGER_CONST_TYPE 1 << 4
516 #define FLOAT_ONE_CONST_TYPE 1 << 3
517 #define FLOAT_CONST_TYPE 1 << 2
518 #define OTHER_CONST_TYPE 1 << 1
519
520 /* Classify an invariant tree into integer, float, or other, so that
521 we can sort them to be near other constants of the same type. */
522 static inline int
523 constant_type (tree t)
524 {
525 if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
526 return INTEGER_CONST_TYPE;
527 else if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (t)))
528 {
529 /* Sort -1.0 and 1.0 constants last, while in some cases
530 const_binop can't optimize some inexact operations, multiplication
531 by -1.0 or 1.0 can be always merged with others. */
532 if (real_onep (t) || real_minus_onep (t))
533 return FLOAT_ONE_CONST_TYPE;
534 return FLOAT_CONST_TYPE;
535 }
536 else
537 return OTHER_CONST_TYPE;
538 }
539
540 /* qsort comparison function to sort operand entries PA and PB by rank
541 so that the sorted array is ordered by rank in decreasing order. */
542 static int
543 sort_by_operand_rank (const void *pa, const void *pb)
544 {
545 const operand_entry *oea = *(const operand_entry *const *)pa;
546 const operand_entry *oeb = *(const operand_entry *const *)pb;
547
548 if (oeb->rank != oea->rank)
549 return oeb->rank > oea->rank ? 1 : -1;
550
551 /* It's nicer for optimize_expression if constants that are likely
552 to fold when added/multiplied/whatever are put next to each
553 other. Since all constants have rank 0, order them by type. */
554 if (oea->rank == 0)
555 {
556 if (constant_type (oeb->op) != constant_type (oea->op))
557 return constant_type (oea->op) - constant_type (oeb->op);
558 else
559 /* To make sorting result stable, we use unique IDs to determine
560 order. */
561 return oeb->id > oea->id ? 1 : -1;
562 }
563
564 if (TREE_CODE (oea->op) != SSA_NAME)
565 {
566 if (TREE_CODE (oeb->op) != SSA_NAME)
567 return oeb->id > oea->id ? 1 : -1;
568 else
569 return 1;
570 }
571 else if (TREE_CODE (oeb->op) != SSA_NAME)
572 return -1;
573
574 /* Lastly, make sure the versions that are the same go next to each
575 other. */
576 if (SSA_NAME_VERSION (oeb->op) != SSA_NAME_VERSION (oea->op))
577 {
578 /* As SSA_NAME_VERSION is assigned pretty randomly, because we reuse
579 versions of removed SSA_NAMEs, so if possible, prefer to sort
580 based on basic block and gimple_uid of the SSA_NAME_DEF_STMT.
581 See PR60418. */
582 gimple *stmta = SSA_NAME_DEF_STMT (oea->op);
583 gimple *stmtb = SSA_NAME_DEF_STMT (oeb->op);
584 basic_block bba = gimple_bb (stmta);
585 basic_block bbb = gimple_bb (stmtb);
586 if (bbb != bba)
587 {
588 /* One of the SSA_NAMEs can be defined in oeN->stmt_to_insert
589 but the other might not. */
590 if (!bba)
591 return 1;
592 if (!bbb)
593 return -1;
594 /* If neither is, compare bb_rank. */
595 if (bb_rank[bbb->index] != bb_rank[bba->index])
596 return (bb_rank[bbb->index] >> 16) - (bb_rank[bba->index] >> 16);
597 }
598
599 bool da = reassoc_stmt_dominates_stmt_p (stmta, stmtb);
600 bool db = reassoc_stmt_dominates_stmt_p (stmtb, stmta);
601 if (da != db)
602 return da ? 1 : -1;
603
604 return SSA_NAME_VERSION (oeb->op) > SSA_NAME_VERSION (oea->op) ? 1 : -1;
605 }
606
607 return oeb->id > oea->id ? 1 : -1;
608 }
609
610 /* Add an operand entry to *OPS for the tree operand OP. */
611
612 static void
613 add_to_ops_vec (vec<operand_entry *> *ops, tree op, gimple *stmt_to_insert = NULL)
614 {
615 operand_entry *oe = operand_entry_pool.allocate ();
616
617 oe->op = op;
618 oe->rank = get_rank (op);
619 oe->id = next_operand_entry_id++;
620 oe->count = 1;
621 oe->stmt_to_insert = stmt_to_insert;
622 ops->safe_push (oe);
623 }
624
625 /* Add an operand entry to *OPS for the tree operand OP with repeat
626 count REPEAT. */
627
628 static void
629 add_repeat_to_ops_vec (vec<operand_entry *> *ops, tree op,
630 HOST_WIDE_INT repeat)
631 {
632 operand_entry *oe = operand_entry_pool.allocate ();
633
634 oe->op = op;
635 oe->rank = get_rank (op);
636 oe->id = next_operand_entry_id++;
637 oe->count = repeat;
638 oe->stmt_to_insert = NULL;
639 ops->safe_push (oe);
640
641 reassociate_stats.pows_encountered++;
642 }
643
644 /* Returns true if we can associate the SSA def OP. */
645
646 static bool
647 can_reassociate_op_p (tree op)
648 {
649 if (TREE_CODE (op) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
650 return false;
651 /* Uninitialized variables can't participate in reassociation. */
652 if (TREE_CODE (op) == SSA_NAME && ssa_name_maybe_undef_p (op))
653 return false;
654 /* Make sure asm goto outputs do not participate in reassociation since
655 we have no way to find an insertion place after asm goto. */
656 if (TREE_CODE (op) == SSA_NAME
657 && gimple_code (SSA_NAME_DEF_STMT (op)) == GIMPLE_ASM
658 && gimple_asm_nlabels (as_a <gasm *> (SSA_NAME_DEF_STMT (op))) != 0)
659 return false;
660 return true;
661 }
662
663 /* Returns true if we can reassociate operations of TYPE.
664 That is for integral or non-saturating fixed-point types, and for
665 floating point type when associative-math is enabled. */
666
667 static bool
668 can_reassociate_type_p (tree type)
669 {
670 if ((ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
671 || NON_SAT_FIXED_POINT_TYPE_P (type)
672 || (flag_associative_math && FLOAT_TYPE_P (type)))
673 return true;
674 return false;
675 }
676
677 /* Return true if STMT is reassociable operation containing a binary
678 operation with tree code CODE, and is inside LOOP. */
679
680 static bool
681 is_reassociable_op (gimple *stmt, enum tree_code code, class loop *loop)
682 {
683 basic_block bb = gimple_bb (stmt);
684
685 if (gimple_bb (stmt) == NULL)
686 return false;
687
688 if (!flow_bb_inside_loop_p (loop, bb))
689 return false;
690
691 if (is_gimple_assign (stmt)
692 && gimple_assign_rhs_code (stmt) == code
693 && has_single_use (gimple_assign_lhs (stmt)))
694 {
695 tree rhs1 = gimple_assign_rhs1 (stmt);
696 tree rhs2 = gimple_assign_rhs2 (stmt);
697 if (!can_reassociate_op_p (rhs1)
698 || (rhs2 && !can_reassociate_op_p (rhs2)))
699 return false;
700 return true;
701 }
702
703 return false;
704 }
705
706
707 /* Return true if STMT is a nop-conversion. */
708
709 static bool
710 gimple_nop_conversion_p (gimple *stmt)
711 {
712 if (gassign *ass = dyn_cast <gassign *> (stmt))
713 {
714 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (ass))
715 && tree_nop_conversion_p (TREE_TYPE (gimple_assign_lhs (ass)),
716 TREE_TYPE (gimple_assign_rhs1 (ass))))
717 return true;
718 }
719 return false;
720 }
721
722 /* Given NAME, if NAME is defined by a unary operation OPCODE, return the
723 operand of the negate operation. Otherwise, return NULL. */
724
725 static tree
726 get_unary_op (tree name, enum tree_code opcode)
727 {
728 gimple *stmt = SSA_NAME_DEF_STMT (name);
729
730 /* Look through nop conversions (sign changes). */
731 if (gimple_nop_conversion_p (stmt)
732 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
733 stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
734
735 if (!is_gimple_assign (stmt))
736 return NULL_TREE;
737
738 if (gimple_assign_rhs_code (stmt) == opcode)
739 return gimple_assign_rhs1 (stmt);
740 return NULL_TREE;
741 }
742
743 /* Return true if OP1 and OP2 have the same value if casted to either type. */
744
745 static bool
746 ops_equal_values_p (tree op1, tree op2)
747 {
748 if (op1 == op2)
749 return true;
750
751 tree orig_op1 = op1;
752 if (TREE_CODE (op1) == SSA_NAME)
753 {
754 gimple *stmt = SSA_NAME_DEF_STMT (op1);
755 if (gimple_nop_conversion_p (stmt))
756 {
757 op1 = gimple_assign_rhs1 (stmt);
758 if (op1 == op2)
759 return true;
760 }
761 }
762
763 if (TREE_CODE (op2) == SSA_NAME)
764 {
765 gimple *stmt = SSA_NAME_DEF_STMT (op2);
766 if (gimple_nop_conversion_p (stmt))
767 {
768 op2 = gimple_assign_rhs1 (stmt);
769 if (op1 == op2
770 || orig_op1 == op2)
771 return true;
772 }
773 }
774
775 return false;
776 }
777
778
779 /* If CURR and LAST are a pair of ops that OPCODE allows us to
780 eliminate through equivalences, do so, remove them from OPS, and
781 return true. Otherwise, return false. */
782
783 static bool
784 eliminate_duplicate_pair (enum tree_code opcode,
785 vec<operand_entry *> *ops,
786 bool *all_done,
787 unsigned int i,
788 operand_entry *curr,
789 operand_entry *last)
790 {
791
792 /* If we have two of the same op, and the opcode is & |, min, or max,
793 we can eliminate one of them.
794 If we have two of the same op, and the opcode is ^, we can
795 eliminate both of them. */
796
797 if (last && last->op == curr->op)
798 {
799 switch (opcode)
800 {
801 case MAX_EXPR:
802 case MIN_EXPR:
803 case BIT_IOR_EXPR:
804 case BIT_AND_EXPR:
805 if (dump_file && (dump_flags & TDF_DETAILS))
806 {
807 fprintf (dump_file, "Equivalence: ");
808 print_generic_expr (dump_file, curr->op);
809 fprintf (dump_file, " [&|minmax] ");
810 print_generic_expr (dump_file, last->op);
811 fprintf (dump_file, " -> ");
812 print_generic_stmt (dump_file, last->op);
813 }
814
815 ops->ordered_remove (i);
816 reassociate_stats.ops_eliminated ++;
817
818 return true;
819
820 case BIT_XOR_EXPR:
821 if (dump_file && (dump_flags & TDF_DETAILS))
822 {
823 fprintf (dump_file, "Equivalence: ");
824 print_generic_expr (dump_file, curr->op);
825 fprintf (dump_file, " ^ ");
826 print_generic_expr (dump_file, last->op);
827 fprintf (dump_file, " -> nothing\n");
828 }
829
830 reassociate_stats.ops_eliminated += 2;
831
832 if (ops->length () == 2)
833 {
834 ops->truncate (0);
835 add_to_ops_vec (ops, build_zero_cst (TREE_TYPE (last->op)));
836 *all_done = true;
837 }
838 else
839 {
840 ops->ordered_remove (i-1);
841 ops->ordered_remove (i-1);
842 }
843
844 return true;
845
846 default:
847 break;
848 }
849 }
850 return false;
851 }
852
853 static vec<tree> plus_negates;
854
855 /* If OPCODE is PLUS_EXPR, CURR->OP is a negate expression or a bitwise not
856 expression, look in OPS for a corresponding positive operation to cancel
857 it out. If we find one, remove the other from OPS, replace
858 OPS[CURRINDEX] with 0 or -1, respectively, and return true. Otherwise,
859 return false. */
860
861 static bool
862 eliminate_plus_minus_pair (enum tree_code opcode,
863 vec<operand_entry *> *ops,
864 unsigned int currindex,
865 operand_entry *curr)
866 {
867 tree negateop;
868 tree notop;
869 unsigned int i;
870 operand_entry *oe;
871
872 if (opcode != PLUS_EXPR || TREE_CODE (curr->op) != SSA_NAME)
873 return false;
874
875 negateop = get_unary_op (curr->op, NEGATE_EXPR);
876 notop = get_unary_op (curr->op, BIT_NOT_EXPR);
877 if (negateop == NULL_TREE && notop == NULL_TREE)
878 return false;
879
880 /* Any non-negated version will have a rank that is one less than
881 the current rank. So once we hit those ranks, if we don't find
882 one, we can stop. */
883
884 for (i = currindex + 1;
885 ops->iterate (i, &oe)
886 && oe->rank >= curr->rank - 1 ;
887 i++)
888 {
889 if (negateop
890 && ops_equal_values_p (oe->op, negateop))
891 {
892 if (dump_file && (dump_flags & TDF_DETAILS))
893 {
894 fprintf (dump_file, "Equivalence: ");
895 print_generic_expr (dump_file, negateop);
896 fprintf (dump_file, " + -");
897 print_generic_expr (dump_file, oe->op);
898 fprintf (dump_file, " -> 0\n");
899 }
900
901 ops->ordered_remove (i);
902 add_to_ops_vec (ops, build_zero_cst (TREE_TYPE (oe->op)));
903 ops->ordered_remove (currindex);
904 reassociate_stats.ops_eliminated ++;
905
906 return true;
907 }
908 else if (notop
909 && ops_equal_values_p (oe->op, notop))
910 {
911 tree op_type = TREE_TYPE (oe->op);
912
913 if (dump_file && (dump_flags & TDF_DETAILS))
914 {
915 fprintf (dump_file, "Equivalence: ");
916 print_generic_expr (dump_file, notop);
917 fprintf (dump_file, " + ~");
918 print_generic_expr (dump_file, oe->op);
919 fprintf (dump_file, " -> -1\n");
920 }
921
922 ops->ordered_remove (i);
923 add_to_ops_vec (ops, build_all_ones_cst (op_type));
924 ops->ordered_remove (currindex);
925 reassociate_stats.ops_eliminated ++;
926
927 return true;
928 }
929 }
930
931 /* If CURR->OP is a negate expr without nop conversion in a plus expr:
932 save it for later inspection in repropagate_negates(). */
933 if (negateop != NULL_TREE
934 && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (curr->op)) == NEGATE_EXPR)
935 plus_negates.safe_push (curr->op);
936
937 return false;
938 }
939
940 /* If OPCODE is BIT_IOR_EXPR, BIT_AND_EXPR, and, CURR->OP is really a
941 bitwise not expression, look in OPS for a corresponding operand to
942 cancel it out. If we find one, remove the other from OPS, replace
943 OPS[CURRINDEX] with 0, and return true. Otherwise, return
944 false. */
945
946 static bool
947 eliminate_not_pairs (enum tree_code opcode,
948 vec<operand_entry *> *ops,
949 unsigned int currindex,
950 operand_entry *curr)
951 {
952 tree notop;
953 unsigned int i;
954 operand_entry *oe;
955
956 if ((opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
957 || TREE_CODE (curr->op) != SSA_NAME)
958 return false;
959
960 notop = get_unary_op (curr->op, BIT_NOT_EXPR);
961 if (notop == NULL_TREE)
962 return false;
963
964 /* Any non-not version will have a rank that is one less than
965 the current rank. So once we hit those ranks, if we don't find
966 one, we can stop. */
967
968 for (i = currindex + 1;
969 ops->iterate (i, &oe)
970 && oe->rank >= curr->rank - 1;
971 i++)
972 {
973 if (oe->op == notop)
974 {
975 if (dump_file && (dump_flags & TDF_DETAILS))
976 {
977 fprintf (dump_file, "Equivalence: ");
978 print_generic_expr (dump_file, notop);
979 if (opcode == BIT_AND_EXPR)
980 fprintf (dump_file, " & ~");
981 else if (opcode == BIT_IOR_EXPR)
982 fprintf (dump_file, " | ~");
983 print_generic_expr (dump_file, oe->op);
984 if (opcode == BIT_AND_EXPR)
985 fprintf (dump_file, " -> 0\n");
986 else if (opcode == BIT_IOR_EXPR)
987 fprintf (dump_file, " -> -1\n");
988 }
989
990 if (opcode == BIT_AND_EXPR)
991 oe->op = build_zero_cst (TREE_TYPE (oe->op));
992 else if (opcode == BIT_IOR_EXPR)
993 oe->op = build_all_ones_cst (TREE_TYPE (oe->op));
994
995 reassociate_stats.ops_eliminated += ops->length () - 1;
996 ops->truncate (0);
997 ops->quick_push (oe);
998 return true;
999 }
1000 }
1001
1002 return false;
1003 }
1004
1005 /* Use constant value that may be present in OPS to try to eliminate
1006 operands. Note that this function is only really used when we've
1007 eliminated ops for other reasons, or merged constants. Across
1008 single statements, fold already does all of this, plus more. There
1009 is little point in duplicating logic, so I've only included the
1010 identities that I could ever construct testcases to trigger. */
1011
1012 static void
1013 eliminate_using_constants (enum tree_code opcode,
1014 vec<operand_entry *> *ops)
1015 {
1016 operand_entry *oelast = ops->last ();
1017 tree type = TREE_TYPE (oelast->op);
1018
1019 if (oelast->rank == 0
1020 && (ANY_INTEGRAL_TYPE_P (type) || FLOAT_TYPE_P (type)))
1021 {
1022 switch (opcode)
1023 {
1024 case BIT_AND_EXPR:
1025 if (integer_zerop (oelast->op))
1026 {
1027 if (ops->length () != 1)
1028 {
1029 if (dump_file && (dump_flags & TDF_DETAILS))
1030 fprintf (dump_file, "Found & 0, removing all other ops\n");
1031
1032 reassociate_stats.ops_eliminated += ops->length () - 1;
1033
1034 ops->truncate (0);
1035 ops->quick_push (oelast);
1036 return;
1037 }
1038 }
1039 else if (integer_all_onesp (oelast->op))
1040 {
1041 if (ops->length () != 1)
1042 {
1043 if (dump_file && (dump_flags & TDF_DETAILS))
1044 fprintf (dump_file, "Found & -1, removing\n");
1045 ops->pop ();
1046 reassociate_stats.ops_eliminated++;
1047 }
1048 }
1049 break;
1050 case BIT_IOR_EXPR:
1051 if (integer_all_onesp (oelast->op))
1052 {
1053 if (ops->length () != 1)
1054 {
1055 if (dump_file && (dump_flags & TDF_DETAILS))
1056 fprintf (dump_file, "Found | -1, removing all other ops\n");
1057
1058 reassociate_stats.ops_eliminated += ops->length () - 1;
1059
1060 ops->truncate (0);
1061 ops->quick_push (oelast);
1062 return;
1063 }
1064 }
1065 else if (integer_zerop (oelast->op))
1066 {
1067 if (ops->length () != 1)
1068 {
1069 if (dump_file && (dump_flags & TDF_DETAILS))
1070 fprintf (dump_file, "Found | 0, removing\n");
1071 ops->pop ();
1072 reassociate_stats.ops_eliminated++;
1073 }
1074 }
1075 break;
1076 case MULT_EXPR:
1077 if (integer_zerop (oelast->op)
1078 || (FLOAT_TYPE_P (type)
1079 && !HONOR_NANS (type)
1080 && !HONOR_SIGNED_ZEROS (type)
1081 && real_zerop (oelast->op)))
1082 {
1083 if (ops->length () != 1)
1084 {
1085 if (dump_file && (dump_flags & TDF_DETAILS))
1086 fprintf (dump_file, "Found * 0, removing all other ops\n");
1087
1088 reassociate_stats.ops_eliminated += ops->length () - 1;
1089 ops->truncate (0);
1090 ops->quick_push (oelast);
1091 return;
1092 }
1093 }
1094 else if (integer_onep (oelast->op)
1095 || (FLOAT_TYPE_P (type)
1096 && !HONOR_SNANS (type)
1097 && real_onep (oelast->op)))
1098 {
1099 if (ops->length () != 1)
1100 {
1101 if (dump_file && (dump_flags & TDF_DETAILS))
1102 fprintf (dump_file, "Found * 1, removing\n");
1103 ops->pop ();
1104 reassociate_stats.ops_eliminated++;
1105 return;
1106 }
1107 }
1108 break;
1109 case BIT_XOR_EXPR:
1110 case PLUS_EXPR:
1111 case MINUS_EXPR:
1112 if (integer_zerop (oelast->op)
1113 || (FLOAT_TYPE_P (type)
1114 && (opcode == PLUS_EXPR || opcode == MINUS_EXPR)
1115 && fold_real_zero_addition_p (type, 0, oelast->op,
1116 opcode == MINUS_EXPR)))
1117 {
1118 if (ops->length () != 1)
1119 {
1120 if (dump_file && (dump_flags & TDF_DETAILS))
1121 fprintf (dump_file, "Found [|^+] 0, removing\n");
1122 ops->pop ();
1123 reassociate_stats.ops_eliminated++;
1124 return;
1125 }
1126 }
1127 break;
1128 default:
1129 break;
1130 }
1131 }
1132 }
1133
1134
1135 static void linearize_expr_tree (vec<operand_entry *> *, gimple *,
1136 bool, bool);
1137
1138 /* Structure for tracking and counting operands. */
1139 struct oecount {
1140 unsigned int cnt;
1141 unsigned int id;
1142 enum tree_code oecode;
1143 tree op;
1144 };
1145
1146
1147 /* The heap for the oecount hashtable and the sorted list of operands. */
1148 static vec<oecount> cvec;
1149
1150
1151 /* Oecount hashtable helpers. */
1152
1153 struct oecount_hasher : int_hash <int, 0, 1>
1154 {
1155 static inline hashval_t hash (int);
1156 static inline bool equal (int, int);
1157 };
1158
1159 /* Hash function for oecount. */
1160
1161 inline hashval_t
1162 oecount_hasher::hash (int p)
1163 {
1164 const oecount *c = &cvec[p - 42];
1165 return htab_hash_pointer (c->op) ^ (hashval_t)c->oecode;
1166 }
1167
1168 /* Comparison function for oecount. */
1169
1170 inline bool
1171 oecount_hasher::equal (int p1, int p2)
1172 {
1173 const oecount *c1 = &cvec[p1 - 42];
1174 const oecount *c2 = &cvec[p2 - 42];
1175 return c1->oecode == c2->oecode && c1->op == c2->op;
1176 }
1177
1178 /* Comparison function for qsort sorting oecount elements by count. */
1179
1180 static int
1181 oecount_cmp (const void *p1, const void *p2)
1182 {
1183 const oecount *c1 = (const oecount *)p1;
1184 const oecount *c2 = (const oecount *)p2;
1185 if (c1->cnt != c2->cnt)
1186 return c1->cnt > c2->cnt ? 1 : -1;
1187 else
1188 /* If counts are identical, use unique IDs to stabilize qsort. */
1189 return c1->id > c2->id ? 1 : -1;
1190 }
1191
1192 /* Return TRUE iff STMT represents a builtin call that raises OP
1193 to some exponent. */
1194
1195 static bool
1196 stmt_is_power_of_op (gimple *stmt, tree op)
1197 {
1198 if (!is_gimple_call (stmt))
1199 return false;
1200
1201 switch (gimple_call_combined_fn (stmt))
1202 {
1203 CASE_CFN_POW:
1204 CASE_CFN_POWI:
1205 return (operand_equal_p (gimple_call_arg (stmt, 0), op, 0));
1206
1207 default:
1208 return false;
1209 }
1210 }
1211
1212 /* Given STMT which is a __builtin_pow* call, decrement its exponent
1213 in place and return the result. Assumes that stmt_is_power_of_op
1214 was previously called for STMT and returned TRUE. */
1215
1216 static HOST_WIDE_INT
1217 decrement_power (gimple *stmt)
1218 {
1219 REAL_VALUE_TYPE c, cint;
1220 HOST_WIDE_INT power;
1221 tree arg1;
1222
1223 switch (gimple_call_combined_fn (stmt))
1224 {
1225 CASE_CFN_POW:
1226 arg1 = gimple_call_arg (stmt, 1);
1227 c = TREE_REAL_CST (arg1);
1228 power = real_to_integer (&c) - 1;
1229 real_from_integer (&cint, VOIDmode, power, SIGNED);
1230 gimple_call_set_arg (stmt, 1, build_real (TREE_TYPE (arg1), cint));
1231 return power;
1232
1233 CASE_CFN_POWI:
1234 arg1 = gimple_call_arg (stmt, 1);
1235 power = TREE_INT_CST_LOW (arg1) - 1;
1236 gimple_call_set_arg (stmt, 1, build_int_cst (TREE_TYPE (arg1), power));
1237 return power;
1238
1239 default:
1240 gcc_unreachable ();
1241 }
1242 }
1243
1244 /* Replace SSA defined by STMT and replace all its uses with new
1245 SSA. Also return the new SSA. */
1246
1247 static tree
1248 make_new_ssa_for_def (gimple *stmt, enum tree_code opcode, tree op)
1249 {
1250 gimple *use_stmt;
1251 use_operand_p use;
1252 imm_use_iterator iter;
1253 tree new_lhs, new_debug_lhs = NULL_TREE;
1254 tree lhs = gimple_get_lhs (stmt);
1255
1256 new_lhs = make_ssa_name (TREE_TYPE (lhs));
1257 gimple_set_lhs (stmt, new_lhs);
1258
1259 /* Also need to update GIMPLE_DEBUGs. */
1260 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
1261 {
1262 tree repl = new_lhs;
1263 if (is_gimple_debug (use_stmt))
1264 {
1265 if (new_debug_lhs == NULL_TREE)
1266 {
1267 new_debug_lhs = build_debug_expr_decl (TREE_TYPE (lhs));
1268 gdebug *def_temp
1269 = gimple_build_debug_bind (new_debug_lhs,
1270 build2 (opcode, TREE_TYPE (lhs),
1271 new_lhs, op),
1272 stmt);
1273 gimple_set_uid (def_temp, gimple_uid (stmt));
1274 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
1275 gsi_insert_after (&gsi, def_temp, GSI_SAME_STMT);
1276 }
1277 repl = new_debug_lhs;
1278 }
1279 FOR_EACH_IMM_USE_ON_STMT (use, iter)
1280 SET_USE (use, repl);
1281 update_stmt (use_stmt);
1282 }
1283 return new_lhs;
1284 }
1285
1286 /* Replace all SSAs defined in STMTS_TO_FIX and replace its
1287 uses with new SSAs. Also do this for the stmt that defines DEF
1288 if *DEF is not OP. */
1289
1290 static void
1291 make_new_ssa_for_all_defs (tree *def, enum tree_code opcode, tree op,
1292 vec<gimple *> &stmts_to_fix)
1293 {
1294 unsigned i;
1295 gimple *stmt;
1296
1297 if (*def != op
1298 && TREE_CODE (*def) == SSA_NAME
1299 && (stmt = SSA_NAME_DEF_STMT (*def))
1300 && gimple_code (stmt) != GIMPLE_NOP)
1301 *def = make_new_ssa_for_def (stmt, opcode, op);
1302
1303 FOR_EACH_VEC_ELT (stmts_to_fix, i, stmt)
1304 make_new_ssa_for_def (stmt, opcode, op);
1305 }
1306
1307 /* Find the single immediate use of STMT's LHS, and replace it
1308 with OP. Remove STMT. If STMT's LHS is the same as *DEF,
1309 replace *DEF with OP as well. */
1310
1311 static void
1312 propagate_op_to_single_use (tree op, gimple *stmt, tree *def)
1313 {
1314 tree lhs;
1315 gimple *use_stmt;
1316 use_operand_p use;
1317 gimple_stmt_iterator gsi;
1318
1319 if (is_gimple_call (stmt))
1320 lhs = gimple_call_lhs (stmt);
1321 else
1322 lhs = gimple_assign_lhs (stmt);
1323
1324 gcc_assert (has_single_use (lhs));
1325 single_imm_use (lhs, &use, &use_stmt);
1326 if (lhs == *def)
1327 *def = op;
1328 SET_USE (use, op);
1329 if (TREE_CODE (op) != SSA_NAME)
1330 update_stmt (use_stmt);
1331 gsi = gsi_for_stmt (stmt);
1332 unlink_stmt_vdef (stmt);
1333 reassoc_remove_stmt (&gsi);
1334 release_defs (stmt);
1335 }
1336
1337 /* Walks the linear chain with result *DEF searching for an operation
1338 with operand OP and code OPCODE removing that from the chain. *DEF
1339 is updated if there is only one operand but no operation left. */
1340
1341 static void
1342 zero_one_operation (tree *def, enum tree_code opcode, tree op)
1343 {
1344 tree orig_def = *def;
1345 gimple *stmt = SSA_NAME_DEF_STMT (*def);
1346 /* PR72835 - Record the stmt chain that has to be updated such that
1347 we dont use the same LHS when the values computed are different. */
1348 auto_vec<gimple *, 64> stmts_to_fix;
1349
1350 do
1351 {
1352 tree name;
1353
1354 if (opcode == MULT_EXPR)
1355 {
1356 if (stmt_is_power_of_op (stmt, op))
1357 {
1358 if (decrement_power (stmt) == 1)
1359 {
1360 if (stmts_to_fix.length () > 0)
1361 stmts_to_fix.pop ();
1362 propagate_op_to_single_use (op, stmt, def);
1363 }
1364 break;
1365 }
1366 else if (gimple_assign_rhs_code (stmt) == NEGATE_EXPR)
1367 {
1368 if (gimple_assign_rhs1 (stmt) == op)
1369 {
1370 tree cst = build_minus_one_cst (TREE_TYPE (op));
1371 if (stmts_to_fix.length () > 0)
1372 stmts_to_fix.pop ();
1373 propagate_op_to_single_use (cst, stmt, def);
1374 break;
1375 }
1376 else if (integer_minus_onep (op)
1377 || real_minus_onep (op))
1378 {
1379 gimple_assign_set_rhs_code
1380 (stmt, TREE_CODE (gimple_assign_rhs1 (stmt)));
1381 break;
1382 }
1383 }
1384 }
1385
1386 name = gimple_assign_rhs1 (stmt);
1387
1388 /* If this is the operation we look for and one of the operands
1389 is ours simply propagate the other operand into the stmts
1390 single use. */
1391 if (gimple_assign_rhs_code (stmt) == opcode
1392 && (name == op
1393 || gimple_assign_rhs2 (stmt) == op))
1394 {
1395 if (name == op)
1396 name = gimple_assign_rhs2 (stmt);
1397 if (stmts_to_fix.length () > 0)
1398 stmts_to_fix.pop ();
1399 propagate_op_to_single_use (name, stmt, def);
1400 break;
1401 }
1402
1403 /* We might have a multiply of two __builtin_pow* calls, and
1404 the operand might be hiding in the rightmost one. Likewise
1405 this can happen for a negate. */
1406 if (opcode == MULT_EXPR
1407 && gimple_assign_rhs_code (stmt) == opcode
1408 && TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME
1409 && has_single_use (gimple_assign_rhs2 (stmt)))
1410 {
1411 gimple *stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
1412 if (stmt_is_power_of_op (stmt2, op))
1413 {
1414 if (decrement_power (stmt2) == 1)
1415 propagate_op_to_single_use (op, stmt2, def);
1416 else
1417 stmts_to_fix.safe_push (stmt2);
1418 break;
1419 }
1420 else if (is_gimple_assign (stmt2)
1421 && gimple_assign_rhs_code (stmt2) == NEGATE_EXPR)
1422 {
1423 if (gimple_assign_rhs1 (stmt2) == op)
1424 {
1425 tree cst = build_minus_one_cst (TREE_TYPE (op));
1426 propagate_op_to_single_use (cst, stmt2, def);
1427 break;
1428 }
1429 else if (integer_minus_onep (op)
1430 || real_minus_onep (op))
1431 {
1432 stmts_to_fix.safe_push (stmt2);
1433 gimple_assign_set_rhs_code
1434 (stmt2, TREE_CODE (gimple_assign_rhs1 (stmt2)));
1435 break;
1436 }
1437 }
1438 }
1439
1440 /* Continue walking the chain. */
1441 gcc_assert (name != op
1442 && TREE_CODE (name) == SSA_NAME);
1443 stmt = SSA_NAME_DEF_STMT (name);
1444 stmts_to_fix.safe_push (stmt);
1445 }
1446 while (1);
1447
1448 if (stmts_to_fix.length () > 0 || *def == orig_def)
1449 make_new_ssa_for_all_defs (def, opcode, op, stmts_to_fix);
1450 }
1451
1452 /* Returns true if statement S1 dominates statement S2. Like
1453 stmt_dominates_stmt_p, but uses stmt UIDs to optimize. */
1454
1455 static bool
1456 reassoc_stmt_dominates_stmt_p (gimple *s1, gimple *s2)
1457 {
1458 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
1459
1460 /* If bb1 is NULL, it should be a GIMPLE_NOP def stmt of an (D)
1461 SSA_NAME. Assume it lives at the beginning of function and
1462 thus dominates everything. */
1463 if (!bb1 || s1 == s2)
1464 return true;
1465
1466 /* If bb2 is NULL, it doesn't dominate any stmt with a bb. */
1467 if (!bb2)
1468 return false;
1469
1470 if (bb1 == bb2)
1471 {
1472 /* PHIs in the same basic block are assumed to be
1473 executed all in parallel, if only one stmt is a PHI,
1474 it dominates the other stmt in the same basic block. */
1475 if (gimple_code (s1) == GIMPLE_PHI)
1476 return true;
1477
1478 if (gimple_code (s2) == GIMPLE_PHI)
1479 return false;
1480
1481 gcc_assert (gimple_uid (s1) && gimple_uid (s2));
1482
1483 if (gimple_uid (s1) < gimple_uid (s2))
1484 return true;
1485
1486 if (gimple_uid (s1) > gimple_uid (s2))
1487 return false;
1488
1489 gimple_stmt_iterator gsi = gsi_for_stmt (s1);
1490 unsigned int uid = gimple_uid (s1);
1491 for (gsi_next (&gsi); !gsi_end_p (gsi); gsi_next (&gsi))
1492 {
1493 gimple *s = gsi_stmt (gsi);
1494 if (gimple_uid (s) != uid)
1495 break;
1496 if (s == s2)
1497 return true;
1498 }
1499
1500 return false;
1501 }
1502
1503 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
1504 }
1505
1506 /* Insert STMT after INSERT_POINT. */
1507
1508 static void
1509 insert_stmt_after (gimple *stmt, gimple *insert_point)
1510 {
1511 gimple_stmt_iterator gsi;
1512 basic_block bb;
1513
1514 if (gimple_code (insert_point) == GIMPLE_PHI)
1515 bb = gimple_bb (insert_point);
1516 else if (!stmt_ends_bb_p (insert_point))
1517 {
1518 gsi = gsi_for_stmt (insert_point);
1519 gimple_set_uid (stmt, gimple_uid (insert_point));
1520 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1521 return;
1522 }
1523 else if (gimple_code (insert_point) == GIMPLE_ASM
1524 && gimple_asm_nlabels (as_a <gasm *> (insert_point)) != 0)
1525 /* We have no idea where to insert - it depends on where the
1526 uses will be placed. */
1527 gcc_unreachable ();
1528 else
1529 /* We assume INSERT_POINT is a SSA_NAME_DEF_STMT of some SSA_NAME,
1530 thus if it must end a basic block, it should be a call that can
1531 throw, or some assignment that can throw. If it throws, the LHS
1532 of it will not be initialized though, so only valid places using
1533 the SSA_NAME should be dominated by the fallthru edge. */
1534 bb = find_fallthru_edge (gimple_bb (insert_point)->succs)->dest;
1535 gsi = gsi_after_labels (bb);
1536 if (gsi_end_p (gsi))
1537 {
1538 gimple_stmt_iterator gsi2 = gsi_last_bb (bb);
1539 gimple_set_uid (stmt,
1540 gsi_end_p (gsi2) ? 1 : gimple_uid (gsi_stmt (gsi2)));
1541 }
1542 else
1543 gimple_set_uid (stmt, gimple_uid (gsi_stmt (gsi)));
1544 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1545 }
1546
1547 /* Builds one statement performing OP1 OPCODE OP2 using TMPVAR for
1548 the result. Places the statement after the definition of either
1549 OP1 or OP2. Returns the new statement. */
1550
1551 static gimple *
1552 build_and_add_sum (tree type, tree op1, tree op2, enum tree_code opcode)
1553 {
1554 gimple *op1def = NULL, *op2def = NULL;
1555 gimple_stmt_iterator gsi;
1556 tree op;
1557 gassign *sum;
1558
1559 /* Create the addition statement. */
1560 op = make_ssa_name (type);
1561 sum = gimple_build_assign (op, opcode, op1, op2);
1562
1563 /* Find an insertion place and insert. */
1564 if (TREE_CODE (op1) == SSA_NAME)
1565 op1def = SSA_NAME_DEF_STMT (op1);
1566 if (TREE_CODE (op2) == SSA_NAME)
1567 op2def = SSA_NAME_DEF_STMT (op2);
1568 if ((!op1def || gimple_nop_p (op1def))
1569 && (!op2def || gimple_nop_p (op2def)))
1570 {
1571 gsi = gsi_start_nondebug_after_labels_bb
1572 (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1573 if (!gsi_end_p (gsi)
1574 && is_gimple_call (gsi_stmt (gsi))
1575 && (gimple_call_flags (gsi_stmt (gsi)) & ECF_RETURNS_TWICE))
1576 {
1577 /* Don't add statements before a returns_twice call at the start
1578 of a function. */
1579 split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1580 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1581 }
1582 if (gsi_end_p (gsi))
1583 {
1584 gimple_stmt_iterator gsi2
1585 = gsi_last_bb (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1586 gimple_set_uid (sum,
1587 gsi_end_p (gsi2) ? 1 : gimple_uid (gsi_stmt (gsi2)));
1588 }
1589 else
1590 gimple_set_uid (sum, gimple_uid (gsi_stmt (gsi)));
1591 gsi_insert_before (&gsi, sum, GSI_NEW_STMT);
1592 }
1593 else
1594 {
1595 gimple *insert_point;
1596 if ((!op1def || gimple_nop_p (op1def))
1597 || (op2def && !gimple_nop_p (op2def)
1598 && reassoc_stmt_dominates_stmt_p (op1def, op2def)))
1599 insert_point = op2def;
1600 else
1601 insert_point = op1def;
1602 insert_stmt_after (sum, insert_point);
1603 }
1604 update_stmt (sum);
1605
1606 return sum;
1607 }
1608
1609 /* Perform un-distribution of divisions and multiplications.
1610 A * X + B * X is transformed into (A + B) * X and A / X + B / X
1611 to (A + B) / X for real X.
1612
1613 The algorithm is organized as follows.
1614
1615 - First we walk the addition chain *OPS looking for summands that
1616 are defined by a multiplication or a real division. This results
1617 in the candidates bitmap with relevant indices into *OPS.
1618
1619 - Second we build the chains of multiplications or divisions for
1620 these candidates, counting the number of occurrences of (operand, code)
1621 pairs in all of the candidates chains.
1622
1623 - Third we sort the (operand, code) pairs by number of occurrence and
1624 process them starting with the pair with the most uses.
1625
1626 * For each such pair we walk the candidates again to build a
1627 second candidate bitmap noting all multiplication/division chains
1628 that have at least one occurrence of (operand, code).
1629
1630 * We build an alternate addition chain only covering these
1631 candidates with one (operand, code) operation removed from their
1632 multiplication/division chain.
1633
1634 * The first candidate gets replaced by the alternate addition chain
1635 multiplied/divided by the operand.
1636
1637 * All candidate chains get disabled for further processing and
1638 processing of (operand, code) pairs continues.
1639
1640 The alternate addition chains built are re-processed by the main
1641 reassociation algorithm which allows optimizing a * x * y + b * y * x
1642 to (a + b ) * x * y in one invocation of the reassociation pass. */
1643
1644 static bool
1645 undistribute_ops_list (enum tree_code opcode,
1646 vec<operand_entry *> *ops, class loop *loop)
1647 {
1648 unsigned int length = ops->length ();
1649 operand_entry *oe1;
1650 unsigned i, j;
1651 unsigned nr_candidates, nr_candidates2;
1652 sbitmap_iterator sbi0;
1653 vec<operand_entry *> *subops;
1654 bool changed = false;
1655 unsigned int next_oecount_id = 0;
1656
1657 if (length <= 1
1658 || opcode != PLUS_EXPR)
1659 return false;
1660
1661 /* Build a list of candidates to process. */
1662 auto_sbitmap candidates (length);
1663 bitmap_clear (candidates);
1664 nr_candidates = 0;
1665 FOR_EACH_VEC_ELT (*ops, i, oe1)
1666 {
1667 enum tree_code dcode;
1668 gimple *oe1def;
1669
1670 if (TREE_CODE (oe1->op) != SSA_NAME)
1671 continue;
1672 oe1def = SSA_NAME_DEF_STMT (oe1->op);
1673 if (!is_gimple_assign (oe1def))
1674 continue;
1675 dcode = gimple_assign_rhs_code (oe1def);
1676 if ((dcode != MULT_EXPR
1677 && dcode != RDIV_EXPR)
1678 || !is_reassociable_op (oe1def, dcode, loop))
1679 continue;
1680
1681 bitmap_set_bit (candidates, i);
1682 nr_candidates++;
1683 }
1684
1685 if (nr_candidates < 2)
1686 return false;
1687
1688 if (dump_file && (dump_flags & TDF_DETAILS))
1689 {
1690 fprintf (dump_file, "searching for un-distribute opportunities ");
1691 print_generic_expr (dump_file,
1692 (*ops)[bitmap_first_set_bit (candidates)]->op, TDF_NONE);
1693 fprintf (dump_file, " %d\n", nr_candidates);
1694 }
1695
1696 /* Build linearized sub-operand lists and the counting table. */
1697 cvec.create (0);
1698
1699 hash_table<oecount_hasher> ctable (15);
1700
1701 /* ??? Macro arguments cannot have multi-argument template types in
1702 them. This typedef is needed to workaround that limitation. */
1703 typedef vec<operand_entry *> vec_operand_entry_t_heap;
1704 subops = XCNEWVEC (vec_operand_entry_t_heap, ops->length ());
1705 EXECUTE_IF_SET_IN_BITMAP (candidates, 0, i, sbi0)
1706 {
1707 gimple *oedef;
1708 enum tree_code oecode;
1709 unsigned j;
1710
1711 oedef = SSA_NAME_DEF_STMT ((*ops)[i]->op);
1712 oecode = gimple_assign_rhs_code (oedef);
1713 linearize_expr_tree (&subops[i], oedef,
1714 associative_tree_code (oecode), false);
1715
1716 FOR_EACH_VEC_ELT (subops[i], j, oe1)
1717 {
1718 oecount c;
1719 int *slot;
1720 int idx;
1721 c.oecode = oecode;
1722 c.cnt = 1;
1723 c.id = next_oecount_id++;
1724 c.op = oe1->op;
1725 cvec.safe_push (c);
1726 idx = cvec.length () + 41;
1727 slot = ctable.find_slot (idx, INSERT);
1728 if (!*slot)
1729 {
1730 *slot = idx;
1731 }
1732 else
1733 {
1734 cvec.pop ();
1735 cvec[*slot - 42].cnt++;
1736 }
1737 }
1738 }
1739
1740 /* Sort the counting table. */
1741 cvec.qsort (oecount_cmp);
1742
1743 if (dump_file && (dump_flags & TDF_DETAILS))
1744 {
1745 oecount *c;
1746 fprintf (dump_file, "Candidates:\n");
1747 FOR_EACH_VEC_ELT (cvec, j, c)
1748 {
1749 fprintf (dump_file, " %u %s: ", c->cnt,
1750 c->oecode == MULT_EXPR
1751 ? "*" : c->oecode == RDIV_EXPR ? "/" : "?");
1752 print_generic_expr (dump_file, c->op);
1753 fprintf (dump_file, "\n");
1754 }
1755 }
1756
1757 /* Process the (operand, code) pairs in order of most occurrence. */
1758 auto_sbitmap candidates2 (length);
1759 while (!cvec.is_empty ())
1760 {
1761 oecount *c = &cvec.last ();
1762 if (c->cnt < 2)
1763 break;
1764
1765 /* Now collect the operands in the outer chain that contain
1766 the common operand in their inner chain. */
1767 bitmap_clear (candidates2);
1768 nr_candidates2 = 0;
1769 EXECUTE_IF_SET_IN_BITMAP (candidates, 0, i, sbi0)
1770 {
1771 gimple *oedef;
1772 enum tree_code oecode;
1773 unsigned j;
1774 tree op = (*ops)[i]->op;
1775
1776 /* If we undistributed in this chain already this may be
1777 a constant. */
1778 if (TREE_CODE (op) != SSA_NAME)
1779 continue;
1780
1781 oedef = SSA_NAME_DEF_STMT (op);
1782 oecode = gimple_assign_rhs_code (oedef);
1783 if (oecode != c->oecode)
1784 continue;
1785
1786 FOR_EACH_VEC_ELT (subops[i], j, oe1)
1787 {
1788 if (oe1->op == c->op)
1789 {
1790 bitmap_set_bit (candidates2, i);
1791 ++nr_candidates2;
1792 break;
1793 }
1794 }
1795 }
1796
1797 if (nr_candidates2 >= 2)
1798 {
1799 operand_entry *oe1, *oe2;
1800 gimple *prod;
1801 int first = bitmap_first_set_bit (candidates2);
1802
1803 /* Build the new addition chain. */
1804 oe1 = (*ops)[first];
1805 if (dump_file && (dump_flags & TDF_DETAILS))
1806 {
1807 fprintf (dump_file, "Building (");
1808 print_generic_expr (dump_file, oe1->op);
1809 }
1810 zero_one_operation (&oe1->op, c->oecode, c->op);
1811 EXECUTE_IF_SET_IN_BITMAP (candidates2, first+1, i, sbi0)
1812 {
1813 gimple *sum;
1814 oe2 = (*ops)[i];
1815 if (dump_file && (dump_flags & TDF_DETAILS))
1816 {
1817 fprintf (dump_file, " + ");
1818 print_generic_expr (dump_file, oe2->op);
1819 }
1820 zero_one_operation (&oe2->op, c->oecode, c->op);
1821 sum = build_and_add_sum (TREE_TYPE (oe1->op),
1822 oe1->op, oe2->op, opcode);
1823 oe2->op = build_zero_cst (TREE_TYPE (oe2->op));
1824 oe2->rank = 0;
1825 oe1->op = gimple_get_lhs (sum);
1826 }
1827
1828 /* Apply the multiplication/division. */
1829 prod = build_and_add_sum (TREE_TYPE (oe1->op),
1830 oe1->op, c->op, c->oecode);
1831 if (dump_file && (dump_flags & TDF_DETAILS))
1832 {
1833 fprintf (dump_file, ") %s ", c->oecode == MULT_EXPR ? "*" : "/");
1834 print_generic_expr (dump_file, c->op);
1835 fprintf (dump_file, "\n");
1836 }
1837
1838 /* Record it in the addition chain and disable further
1839 undistribution with this op. */
1840 oe1->op = gimple_assign_lhs (prod);
1841 oe1->rank = get_rank (oe1->op);
1842 subops[first].release ();
1843
1844 changed = true;
1845 }
1846
1847 cvec.pop ();
1848 }
1849
1850 for (i = 0; i < ops->length (); ++i)
1851 subops[i].release ();
1852 free (subops);
1853 cvec.release ();
1854
1855 return changed;
1856 }
1857
1858 /* Pair to hold the information of one specific VECTOR_TYPE SSA_NAME:
1859 first: element index for each relevant BIT_FIELD_REF.
1860 second: the index of vec ops* for each relevant BIT_FIELD_REF. */
1861 typedef std::pair<unsigned, unsigned> v_info_elem;
1862 struct v_info {
1863 tree vec_type;
1864 auto_vec<v_info_elem, 32> vec;
1865 };
1866 typedef v_info *v_info_ptr;
1867
1868 /* Comparison function for qsort on VECTOR SSA_NAME trees by machine mode. */
1869 static int
1870 sort_by_mach_mode (const void *p_i, const void *p_j)
1871 {
1872 const tree tr1 = *((const tree *) p_i);
1873 const tree tr2 = *((const tree *) p_j);
1874 unsigned int mode1 = TYPE_MODE (TREE_TYPE (tr1));
1875 unsigned int mode2 = TYPE_MODE (TREE_TYPE (tr2));
1876 if (mode1 > mode2)
1877 return 1;
1878 else if (mode1 < mode2)
1879 return -1;
1880 if (SSA_NAME_VERSION (tr1) < SSA_NAME_VERSION (tr2))
1881 return -1;
1882 else if (SSA_NAME_VERSION (tr1) > SSA_NAME_VERSION (tr2))
1883 return 1;
1884 return 0;
1885 }
1886
1887 /* Cleanup hash map for VECTOR information. */
1888 static void
1889 cleanup_vinfo_map (hash_map<tree, v_info_ptr> &info_map)
1890 {
1891 for (hash_map<tree, v_info_ptr>::iterator it = info_map.begin ();
1892 it != info_map.end (); ++it)
1893 {
1894 v_info_ptr info = (*it).second;
1895 delete info;
1896 (*it).second = NULL;
1897 }
1898 }
1899
1900 /* Perform un-distribution of BIT_FIELD_REF on VECTOR_TYPE.
1901 V1[0] + V1[1] + ... + V1[k] + V2[0] + V2[1] + ... + V2[k] + ... Vn[k]
1902 is transformed to
1903 Vs = (V1 + V2 + ... + Vn)
1904 Vs[0] + Vs[1] + ... + Vs[k]
1905
1906 The basic steps are listed below:
1907
1908 1) Check the addition chain *OPS by looking those summands coming from
1909 VECTOR bit_field_ref on VECTOR type. Put the information into
1910 v_info_map for each satisfied summand, using VECTOR SSA_NAME as key.
1911
1912 2) For each key (VECTOR SSA_NAME), validate all its BIT_FIELD_REFs are
1913 continuous, they can cover the whole VECTOR perfectly without any holes.
1914 Obtain one VECTOR list which contain candidates to be transformed.
1915
1916 3) Sort the VECTOR list by machine mode of VECTOR type, for each group of
1917 candidates with same mode, build the addition statements for them and
1918 generate BIT_FIELD_REFs accordingly.
1919
1920 TODO:
1921 The current implementation requires the whole VECTORs should be fully
1922 covered, but it can be extended to support partial, checking adjacent
1923 but not fill the whole, it may need some cost model to define the
1924 boundary to do or not.
1925 */
1926 static bool
1927 undistribute_bitref_for_vector (enum tree_code opcode,
1928 vec<operand_entry *> *ops, struct loop *loop)
1929 {
1930 if (ops->length () <= 1)
1931 return false;
1932
1933 if (opcode != PLUS_EXPR
1934 && opcode != MULT_EXPR
1935 && opcode != BIT_XOR_EXPR
1936 && opcode != BIT_IOR_EXPR
1937 && opcode != BIT_AND_EXPR)
1938 return false;
1939
1940 hash_map<tree, v_info_ptr> v_info_map;
1941 operand_entry *oe1;
1942 unsigned i;
1943
1944 /* Find those summands from VECTOR BIT_FIELD_REF in addition chain, put the
1945 information into map. */
1946 FOR_EACH_VEC_ELT (*ops, i, oe1)
1947 {
1948 enum tree_code dcode;
1949 gimple *oe1def;
1950
1951 if (TREE_CODE (oe1->op) != SSA_NAME)
1952 continue;
1953 oe1def = SSA_NAME_DEF_STMT (oe1->op);
1954 if (!is_gimple_assign (oe1def))
1955 continue;
1956 dcode = gimple_assign_rhs_code (oe1def);
1957 if (dcode != BIT_FIELD_REF || !is_reassociable_op (oe1def, dcode, loop))
1958 continue;
1959
1960 tree rhs = gimple_assign_rhs1 (oe1def);
1961 tree vec = TREE_OPERAND (rhs, 0);
1962 tree vec_type = TREE_TYPE (vec);
1963
1964 if (TREE_CODE (vec) != SSA_NAME || !VECTOR_TYPE_P (vec_type))
1965 continue;
1966
1967 /* Ignore it if target machine can't support this VECTOR type. */
1968 if (!VECTOR_MODE_P (TYPE_MODE (vec_type)))
1969 continue;
1970
1971 /* Check const vector type, constrain BIT_FIELD_REF offset and size. */
1972 if (!TYPE_VECTOR_SUBPARTS (vec_type).is_constant ())
1973 continue;
1974
1975 if (VECTOR_TYPE_P (TREE_TYPE (rhs))
1976 || !is_a <scalar_mode> (TYPE_MODE (TREE_TYPE (rhs))))
1977 continue;
1978
1979 /* The type of BIT_FIELD_REF might not be equal to the element type of
1980 the vector. We want to use a vector type with element type the
1981 same as the BIT_FIELD_REF and size the same as TREE_TYPE (vec). */
1982 if (!useless_type_conversion_p (TREE_TYPE (rhs), TREE_TYPE (vec_type)))
1983 {
1984 machine_mode simd_mode;
1985 unsigned HOST_WIDE_INT size, nunits;
1986 unsigned HOST_WIDE_INT elem_size
1987 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (rhs)));
1988 if (!GET_MODE_BITSIZE (TYPE_MODE (vec_type)).is_constant (&size))
1989 continue;
1990 if (size <= elem_size || (size % elem_size) != 0)
1991 continue;
1992 nunits = size / elem_size;
1993 if (!mode_for_vector (SCALAR_TYPE_MODE (TREE_TYPE (rhs)),
1994 nunits).exists (&simd_mode))
1995 continue;
1996 vec_type = build_vector_type_for_mode (TREE_TYPE (rhs), simd_mode);
1997
1998 /* Ignore it if target machine can't support this VECTOR type. */
1999 if (!VECTOR_MODE_P (TYPE_MODE (vec_type)))
2000 continue;
2001
2002 /* Check const vector type, constrain BIT_FIELD_REF offset and
2003 size. */
2004 if (!TYPE_VECTOR_SUBPARTS (vec_type).is_constant ())
2005 continue;
2006
2007 if (maybe_ne (GET_MODE_SIZE (TYPE_MODE (vec_type)),
2008 GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (vec)))))
2009 continue;
2010 }
2011
2012 tree elem_type = TREE_TYPE (vec_type);
2013 unsigned HOST_WIDE_INT elem_size = tree_to_uhwi (TYPE_SIZE (elem_type));
2014 if (maybe_ne (bit_field_size (rhs), elem_size))
2015 continue;
2016
2017 unsigned idx;
2018 if (!constant_multiple_p (bit_field_offset (rhs), elem_size, &idx))
2019 continue;
2020
2021 /* Ignore it if target machine can't support this type of VECTOR
2022 operation. */
2023 optab op_tab = optab_for_tree_code (opcode, vec_type, optab_vector);
2024 if (optab_handler (op_tab, TYPE_MODE (vec_type)) == CODE_FOR_nothing)
2025 continue;
2026
2027 bool existed;
2028 v_info_ptr &info = v_info_map.get_or_insert (vec, &existed);
2029 if (!existed)
2030 {
2031 info = new v_info;
2032 info->vec_type = vec_type;
2033 }
2034 else if (!types_compatible_p (vec_type, info->vec_type))
2035 continue;
2036 info->vec.safe_push (std::make_pair (idx, i));
2037 }
2038
2039 /* At least two VECTOR to combine. */
2040 if (v_info_map.elements () <= 1)
2041 {
2042 cleanup_vinfo_map (v_info_map);
2043 return false;
2044 }
2045
2046 /* Verify all VECTOR candidates by checking two conditions:
2047 1) sorted offsets are adjacent, no holes.
2048 2) can fill the whole VECTOR perfectly.
2049 And add the valid candidates to a vector for further handling. */
2050 auto_vec<tree> valid_vecs (v_info_map.elements ());
2051 for (hash_map<tree, v_info_ptr>::iterator it = v_info_map.begin ();
2052 it != v_info_map.end (); ++it)
2053 {
2054 tree cand_vec = (*it).first;
2055 v_info_ptr cand_info = (*it).second;
2056 unsigned int num_elems
2057 = TYPE_VECTOR_SUBPARTS (cand_info->vec_type).to_constant ();
2058 if (cand_info->vec.length () != num_elems)
2059 continue;
2060 sbitmap holes = sbitmap_alloc (num_elems);
2061 bitmap_ones (holes);
2062 bool valid = true;
2063 v_info_elem *curr;
2064 FOR_EACH_VEC_ELT (cand_info->vec, i, curr)
2065 {
2066 if (!bitmap_bit_p (holes, curr->first))
2067 {
2068 valid = false;
2069 break;
2070 }
2071 else
2072 bitmap_clear_bit (holes, curr->first);
2073 }
2074 if (valid && bitmap_empty_p (holes))
2075 valid_vecs.quick_push (cand_vec);
2076 sbitmap_free (holes);
2077 }
2078
2079 /* At least two VECTOR to combine. */
2080 if (valid_vecs.length () <= 1)
2081 {
2082 cleanup_vinfo_map (v_info_map);
2083 return false;
2084 }
2085
2086 valid_vecs.qsort (sort_by_mach_mode);
2087 /* Go through all candidates by machine mode order, query the mode_to_total
2088 to get the total number for each mode and skip the single one. */
2089 for (unsigned i = 0; i < valid_vecs.length () - 1; ++i)
2090 {
2091 tree tvec = valid_vecs[i];
2092 enum machine_mode mode = TYPE_MODE (TREE_TYPE (tvec));
2093
2094 /* Skip modes with only a single candidate. */
2095 if (TYPE_MODE (TREE_TYPE (valid_vecs[i + 1])) != mode)
2096 continue;
2097
2098 unsigned int idx, j;
2099 gimple *sum = NULL;
2100 tree sum_vec = tvec;
2101 v_info_ptr info_ptr = *(v_info_map.get (tvec));
2102 v_info_elem *elem;
2103 tree vec_type = info_ptr->vec_type;
2104
2105 /* Build the sum for all candidates with same mode. */
2106 do
2107 {
2108 sum = build_and_add_sum (vec_type, sum_vec,
2109 valid_vecs[i + 1], opcode);
2110 /* Update the operands only after build_and_add_sum,
2111 so that we don't have to repeat the placement algorithm
2112 of build_and_add_sum. */
2113 if (sum_vec == tvec
2114 && !useless_type_conversion_p (vec_type, TREE_TYPE (sum_vec)))
2115 {
2116 gimple_stmt_iterator gsi = gsi_for_stmt (sum);
2117 tree vce = build1 (VIEW_CONVERT_EXPR, vec_type, sum_vec);
2118 tree lhs = make_ssa_name (vec_type);
2119 gimple *g = gimple_build_assign (lhs, VIEW_CONVERT_EXPR, vce);
2120 gimple_set_uid (g, gimple_uid (sum));
2121 gsi_insert_before (&gsi, g, GSI_NEW_STMT);
2122 gimple_assign_set_rhs1 (sum, lhs);
2123 update_stmt (sum);
2124 }
2125 if (!useless_type_conversion_p (vec_type,
2126 TREE_TYPE (valid_vecs[i + 1])))
2127 {
2128 gimple_stmt_iterator gsi = gsi_for_stmt (sum);
2129 tree vce = build1 (VIEW_CONVERT_EXPR, vec_type,
2130 valid_vecs[i + 1]);
2131 tree lhs = make_ssa_name (vec_type);
2132 gimple *g = gimple_build_assign (lhs, VIEW_CONVERT_EXPR, vce);
2133 gimple_set_uid (g, gimple_uid (sum));
2134 gsi_insert_before (&gsi, g, GSI_NEW_STMT);
2135 gimple_assign_set_rhs2 (sum, lhs);
2136 update_stmt (sum);
2137 }
2138 sum_vec = gimple_get_lhs (sum);
2139 info_ptr = *(v_info_map.get (valid_vecs[i + 1]));
2140 gcc_assert (types_compatible_p (vec_type, info_ptr->vec_type));
2141 /* Update those related ops of current candidate VECTOR. */
2142 FOR_EACH_VEC_ELT (info_ptr->vec, j, elem)
2143 {
2144 idx = elem->second;
2145 gimple *def = SSA_NAME_DEF_STMT ((*ops)[idx]->op);
2146 /* Set this then op definition will get DCEd later. */
2147 gimple_set_visited (def, true);
2148 if (opcode == PLUS_EXPR
2149 || opcode == BIT_XOR_EXPR
2150 || opcode == BIT_IOR_EXPR)
2151 (*ops)[idx]->op = build_zero_cst (TREE_TYPE ((*ops)[idx]->op));
2152 else if (opcode == MULT_EXPR)
2153 (*ops)[idx]->op = build_one_cst (TREE_TYPE ((*ops)[idx]->op));
2154 else
2155 {
2156 gcc_assert (opcode == BIT_AND_EXPR);
2157 (*ops)[idx]->op
2158 = build_all_ones_cst (TREE_TYPE ((*ops)[idx]->op));
2159 }
2160 (*ops)[idx]->rank = 0;
2161 }
2162 if (dump_file && (dump_flags & TDF_DETAILS))
2163 {
2164 fprintf (dump_file, "Generating addition -> ");
2165 print_gimple_stmt (dump_file, sum, 0);
2166 }
2167 i++;
2168 }
2169 while ((i < valid_vecs.length () - 1)
2170 && TYPE_MODE (TREE_TYPE (valid_vecs[i + 1])) == mode);
2171
2172 /* Referring to first valid VECTOR with this mode, generate the
2173 BIT_FIELD_REF statements accordingly. */
2174 info_ptr = *(v_info_map.get (tvec));
2175 gcc_assert (sum);
2176 tree elem_type = TREE_TYPE (vec_type);
2177 FOR_EACH_VEC_ELT (info_ptr->vec, j, elem)
2178 {
2179 idx = elem->second;
2180 tree dst = make_ssa_name (elem_type);
2181 tree pos = bitsize_int (elem->first
2182 * tree_to_uhwi (TYPE_SIZE (elem_type)));
2183 tree bfr = build3 (BIT_FIELD_REF, elem_type, sum_vec,
2184 TYPE_SIZE (elem_type), pos);
2185 gimple *gs = gimple_build_assign (dst, BIT_FIELD_REF, bfr);
2186 insert_stmt_after (gs, sum);
2187 gimple *def = SSA_NAME_DEF_STMT ((*ops)[idx]->op);
2188 /* Set this then op definition will get DCEd later. */
2189 gimple_set_visited (def, true);
2190 (*ops)[idx]->op = gimple_assign_lhs (gs);
2191 (*ops)[idx]->rank = get_rank ((*ops)[idx]->op);
2192 if (dump_file && (dump_flags & TDF_DETAILS))
2193 {
2194 fprintf (dump_file, "Generating bit_field_ref -> ");
2195 print_gimple_stmt (dump_file, gs, 0);
2196 }
2197 }
2198 }
2199
2200 if (dump_file && (dump_flags & TDF_DETAILS))
2201 fprintf (dump_file, "undistributiong bit_field_ref for vector done.\n");
2202
2203 cleanup_vinfo_map (v_info_map);
2204
2205 return true;
2206 }
2207
2208 /* If OPCODE is BIT_IOR_EXPR or BIT_AND_EXPR and CURR is a comparison
2209 expression, examine the other OPS to see if any of them are comparisons
2210 of the same values, which we may be able to combine or eliminate.
2211 For example, we can rewrite (a < b) | (a == b) as (a <= b). */
2212
2213 static bool
2214 eliminate_redundant_comparison (enum tree_code opcode,
2215 vec<operand_entry *> *ops,
2216 unsigned int currindex,
2217 operand_entry *curr)
2218 {
2219 tree op1, op2;
2220 enum tree_code lcode, rcode;
2221 gimple *def1, *def2;
2222 int i;
2223 operand_entry *oe;
2224
2225 if (opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
2226 return false;
2227
2228 /* Check that CURR is a comparison. */
2229 if (TREE_CODE (curr->op) != SSA_NAME)
2230 return false;
2231 def1 = SSA_NAME_DEF_STMT (curr->op);
2232 if (!is_gimple_assign (def1))
2233 return false;
2234 lcode = gimple_assign_rhs_code (def1);
2235 if (TREE_CODE_CLASS (lcode) != tcc_comparison)
2236 return false;
2237 op1 = gimple_assign_rhs1 (def1);
2238 op2 = gimple_assign_rhs2 (def1);
2239
2240 /* Now look for a similar comparison in the remaining OPS. */
2241 for (i = currindex + 1; ops->iterate (i, &oe); i++)
2242 {
2243 tree t;
2244
2245 if (TREE_CODE (oe->op) != SSA_NAME)
2246 continue;
2247 def2 = SSA_NAME_DEF_STMT (oe->op);
2248 if (!is_gimple_assign (def2))
2249 continue;
2250 rcode = gimple_assign_rhs_code (def2);
2251 if (TREE_CODE_CLASS (rcode) != tcc_comparison)
2252 continue;
2253
2254 /* If we got here, we have a match. See if we can combine the
2255 two comparisons. */
2256 tree type = TREE_TYPE (gimple_assign_lhs (def1));
2257 if (opcode == BIT_IOR_EXPR)
2258 t = maybe_fold_or_comparisons (type,
2259 lcode, op1, op2,
2260 rcode, gimple_assign_rhs1 (def2),
2261 gimple_assign_rhs2 (def2));
2262 else
2263 t = maybe_fold_and_comparisons (type,
2264 lcode, op1, op2,
2265 rcode, gimple_assign_rhs1 (def2),
2266 gimple_assign_rhs2 (def2));
2267 if (!t)
2268 continue;
2269
2270 /* maybe_fold_and_comparisons and maybe_fold_or_comparisons
2271 always give us a boolean_type_node value back. If the original
2272 BIT_AND_EXPR or BIT_IOR_EXPR was of a wider integer type,
2273 we need to convert. */
2274 if (!useless_type_conversion_p (TREE_TYPE (curr->op), TREE_TYPE (t)))
2275 {
2276 if (!fold_convertible_p (TREE_TYPE (curr->op), t))
2277 continue;
2278 t = fold_convert (TREE_TYPE (curr->op), t);
2279 }
2280
2281 if (TREE_CODE (t) != INTEGER_CST
2282 && !operand_equal_p (t, curr->op, 0))
2283 {
2284 enum tree_code subcode;
2285 tree newop1, newop2;
2286 if (!COMPARISON_CLASS_P (t))
2287 continue;
2288 extract_ops_from_tree (t, &subcode, &newop1, &newop2);
2289 STRIP_USELESS_TYPE_CONVERSION (newop1);
2290 STRIP_USELESS_TYPE_CONVERSION (newop2);
2291 if (!is_gimple_val (newop1) || !is_gimple_val (newop2))
2292 continue;
2293 if (lcode == TREE_CODE (t)
2294 && operand_equal_p (op1, newop1, 0)
2295 && operand_equal_p (op2, newop2, 0))
2296 t = curr->op;
2297 else if ((TREE_CODE (newop1) == SSA_NAME
2298 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (newop1))
2299 || (TREE_CODE (newop2) == SSA_NAME
2300 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (newop2)))
2301 continue;
2302 }
2303
2304 if (dump_file && (dump_flags & TDF_DETAILS))
2305 {
2306 fprintf (dump_file, "Equivalence: ");
2307 print_generic_expr (dump_file, curr->op);
2308 fprintf (dump_file, " %s ", op_symbol_code (opcode));
2309 print_generic_expr (dump_file, oe->op);
2310 fprintf (dump_file, " -> ");
2311 print_generic_expr (dump_file, t);
2312 fprintf (dump_file, "\n");
2313 }
2314
2315 /* Now we can delete oe, as it has been subsumed by the new combined
2316 expression t. */
2317 ops->ordered_remove (i);
2318 reassociate_stats.ops_eliminated ++;
2319
2320 /* If t is the same as curr->op, we're done. Otherwise we must
2321 replace curr->op with t. Special case is if we got a constant
2322 back, in which case we add it to the end instead of in place of
2323 the current entry. */
2324 if (TREE_CODE (t) == INTEGER_CST)
2325 {
2326 ops->ordered_remove (currindex);
2327 add_to_ops_vec (ops, t);
2328 }
2329 else if (!operand_equal_p (t, curr->op, 0))
2330 {
2331 gimple *sum;
2332 enum tree_code subcode;
2333 tree newop1;
2334 tree newop2;
2335 gcc_assert (COMPARISON_CLASS_P (t));
2336 extract_ops_from_tree (t, &subcode, &newop1, &newop2);
2337 STRIP_USELESS_TYPE_CONVERSION (newop1);
2338 STRIP_USELESS_TYPE_CONVERSION (newop2);
2339 gcc_checking_assert (is_gimple_val (newop1)
2340 && is_gimple_val (newop2));
2341 sum = build_and_add_sum (TREE_TYPE (t), newop1, newop2, subcode);
2342 curr->op = gimple_get_lhs (sum);
2343 }
2344 return true;
2345 }
2346
2347 return false;
2348 }
2349
2350
2351 /* Transform repeated addition of same values into multiply with
2352 constant. */
2353 static bool
2354 transform_add_to_multiply (vec<operand_entry *> *ops)
2355 {
2356 operand_entry *oe;
2357 tree op = NULL_TREE;
2358 int j;
2359 int i, start = -1, end = 0, count = 0;
2360 auto_vec<std::pair <int, int> > indxs;
2361 bool changed = false;
2362
2363 if (!INTEGRAL_TYPE_P (TREE_TYPE ((*ops)[0]->op))
2364 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE ((*ops)[0]->op))
2365 || !flag_unsafe_math_optimizations))
2366 return false;
2367
2368 /* Look for repeated operands. */
2369 FOR_EACH_VEC_ELT (*ops, i, oe)
2370 {
2371 if (start == -1)
2372 {
2373 count = 1;
2374 op = oe->op;
2375 start = i;
2376 }
2377 else if (operand_equal_p (oe->op, op, 0))
2378 {
2379 count++;
2380 end = i;
2381 }
2382 else
2383 {
2384 if (count > 1)
2385 indxs.safe_push (std::make_pair (start, end));
2386 count = 1;
2387 op = oe->op;
2388 start = i;
2389 }
2390 }
2391
2392 if (count > 1)
2393 indxs.safe_push (std::make_pair (start, end));
2394
2395 for (j = indxs.length () - 1; j >= 0; --j)
2396 {
2397 /* Convert repeated operand addition to multiplication. */
2398 start = indxs[j].first;
2399 end = indxs[j].second;
2400 op = (*ops)[start]->op;
2401 count = end - start + 1;
2402 for (i = end; i >= start; --i)
2403 ops->unordered_remove (i);
2404 tree tmp = make_ssa_name (TREE_TYPE (op));
2405 tree cst = build_int_cst (integer_type_node, count);
2406 gassign *mul_stmt
2407 = gimple_build_assign (tmp, MULT_EXPR,
2408 op, fold_convert (TREE_TYPE (op), cst));
2409 gimple_set_visited (mul_stmt, true);
2410 add_to_ops_vec (ops, tmp, mul_stmt);
2411 changed = true;
2412 }
2413
2414 return changed;
2415 }
2416
2417
2418 /* Perform various identities and other optimizations on the list of
2419 operand entries, stored in OPS. The tree code for the binary
2420 operation between all the operands is OPCODE. */
2421
2422 static void
2423 optimize_ops_list (enum tree_code opcode,
2424 vec<operand_entry *> *ops)
2425 {
2426 unsigned int length = ops->length ();
2427 unsigned int i;
2428 operand_entry *oe;
2429 operand_entry *oelast = NULL;
2430 bool iterate = false;
2431
2432 if (length == 1)
2433 return;
2434
2435 oelast = ops->last ();
2436
2437 /* If the last two are constants, pop the constants off, merge them
2438 and try the next two. */
2439 if (oelast->rank == 0 && is_gimple_min_invariant (oelast->op))
2440 {
2441 operand_entry *oelm1 = (*ops)[length - 2];
2442
2443 if (oelm1->rank == 0
2444 && is_gimple_min_invariant (oelm1->op)
2445 && useless_type_conversion_p (TREE_TYPE (oelm1->op),
2446 TREE_TYPE (oelast->op)))
2447 {
2448 tree folded = fold_binary (opcode, TREE_TYPE (oelm1->op),
2449 oelm1->op, oelast->op);
2450
2451 if (folded && is_gimple_min_invariant (folded))
2452 {
2453 if (dump_file && (dump_flags & TDF_DETAILS))
2454 fprintf (dump_file, "Merging constants\n");
2455
2456 ops->pop ();
2457 ops->pop ();
2458
2459 add_to_ops_vec (ops, folded);
2460 reassociate_stats.constants_eliminated++;
2461
2462 optimize_ops_list (opcode, ops);
2463 return;
2464 }
2465 }
2466 }
2467
2468 eliminate_using_constants (opcode, ops);
2469 oelast = NULL;
2470
2471 for (i = 0; ops->iterate (i, &oe);)
2472 {
2473 bool done = false;
2474
2475 if (eliminate_not_pairs (opcode, ops, i, oe))
2476 return;
2477 if (eliminate_duplicate_pair (opcode, ops, &done, i, oe, oelast)
2478 || (!done && eliminate_plus_minus_pair (opcode, ops, i, oe))
2479 || (!done && eliminate_redundant_comparison (opcode, ops, i, oe)))
2480 {
2481 if (done)
2482 return;
2483 iterate = true;
2484 oelast = NULL;
2485 continue;
2486 }
2487 oelast = oe;
2488 i++;
2489 }
2490
2491 if (iterate)
2492 optimize_ops_list (opcode, ops);
2493 }
2494
2495 /* The following functions are subroutines to optimize_range_tests and allow
2496 it to try to change a logical combination of comparisons into a range
2497 test.
2498
2499 For example, both
2500 X == 2 || X == 5 || X == 3 || X == 4
2501 and
2502 X >= 2 && X <= 5
2503 are converted to
2504 (unsigned) (X - 2) <= 3
2505
2506 For more information see comments above fold_test_range in fold-const.cc,
2507 this implementation is for GIMPLE. */
2508
2509
2510
2511 /* Dump the range entry R to FILE, skipping its expression if SKIP_EXP. */
2512
2513 void
2514 dump_range_entry (FILE *file, struct range_entry *r, bool skip_exp)
2515 {
2516 if (!skip_exp)
2517 print_generic_expr (file, r->exp);
2518 fprintf (file, " %c[", r->in_p ? '+' : '-');
2519 print_generic_expr (file, r->low);
2520 fputs (", ", file);
2521 print_generic_expr (file, r->high);
2522 fputc (']', file);
2523 }
2524
2525 /* Dump the range entry R to STDERR. */
2526
2527 DEBUG_FUNCTION void
2528 debug_range_entry (struct range_entry *r)
2529 {
2530 dump_range_entry (stderr, r, false);
2531 fputc ('\n', stderr);
2532 }
2533
2534 /* This is similar to make_range in fold-const.cc, but on top of
2535 GIMPLE instead of trees. If EXP is non-NULL, it should be
2536 an SSA_NAME and STMT argument is ignored, otherwise STMT
2537 argument should be a GIMPLE_COND. */
2538
2539 void
2540 init_range_entry (struct range_entry *r, tree exp, gimple *stmt)
2541 {
2542 int in_p;
2543 tree low, high;
2544 bool is_bool, strict_overflow_p;
2545
2546 r->exp = NULL_TREE;
2547 r->in_p = false;
2548 r->strict_overflow_p = false;
2549 r->low = NULL_TREE;
2550 r->high = NULL_TREE;
2551 if (exp != NULL_TREE
2552 && (TREE_CODE (exp) != SSA_NAME || !INTEGRAL_TYPE_P (TREE_TYPE (exp))))
2553 return;
2554
2555 /* Start with simply saying "EXP != 0" and then look at the code of EXP
2556 and see if we can refine the range. Some of the cases below may not
2557 happen, but it doesn't seem worth worrying about this. We "continue"
2558 the outer loop when we've changed something; otherwise we "break"
2559 the switch, which will "break" the while. */
2560 low = exp ? build_int_cst (TREE_TYPE (exp), 0) : boolean_false_node;
2561 high = low;
2562 in_p = 0;
2563 strict_overflow_p = false;
2564 is_bool = false;
2565 if (exp == NULL_TREE)
2566 is_bool = true;
2567 else if (TYPE_PRECISION (TREE_TYPE (exp)) == 1)
2568 {
2569 if (TYPE_UNSIGNED (TREE_TYPE (exp)))
2570 is_bool = true;
2571 else
2572 return;
2573 }
2574 else if (TREE_CODE (TREE_TYPE (exp)) == BOOLEAN_TYPE)
2575 is_bool = true;
2576
2577 while (1)
2578 {
2579 enum tree_code code;
2580 tree arg0, arg1, exp_type;
2581 tree nexp;
2582 location_t loc;
2583
2584 if (exp != NULL_TREE)
2585 {
2586 if (TREE_CODE (exp) != SSA_NAME
2587 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp))
2588 break;
2589
2590 stmt = SSA_NAME_DEF_STMT (exp);
2591 if (!is_gimple_assign (stmt))
2592 break;
2593
2594 code = gimple_assign_rhs_code (stmt);
2595 arg0 = gimple_assign_rhs1 (stmt);
2596 arg1 = gimple_assign_rhs2 (stmt);
2597 exp_type = TREE_TYPE (exp);
2598 }
2599 else
2600 {
2601 code = gimple_cond_code (stmt);
2602 arg0 = gimple_cond_lhs (stmt);
2603 arg1 = gimple_cond_rhs (stmt);
2604 exp_type = boolean_type_node;
2605 }
2606
2607 if (TREE_CODE (arg0) != SSA_NAME
2608 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (arg0)
2609 || ssa_name_maybe_undef_p (arg0))
2610 break;
2611 loc = gimple_location (stmt);
2612 switch (code)
2613 {
2614 case BIT_NOT_EXPR:
2615 if (TREE_CODE (TREE_TYPE (exp)) == BOOLEAN_TYPE
2616 /* Ensure the range is either +[-,0], +[0,0],
2617 -[-,0], -[0,0] or +[1,-], +[1,1], -[1,-] or
2618 -[1,1]. If it is e.g. +[-,-] or -[-,-]
2619 or similar expression of unconditional true or
2620 false, it should not be negated. */
2621 && ((high && integer_zerop (high))
2622 || (low && integer_onep (low))))
2623 {
2624 in_p = !in_p;
2625 exp = arg0;
2626 continue;
2627 }
2628 break;
2629 case SSA_NAME:
2630 exp = arg0;
2631 continue;
2632 CASE_CONVERT:
2633 if (is_bool)
2634 {
2635 if ((TYPE_PRECISION (exp_type) == 1
2636 || TREE_CODE (exp_type) == BOOLEAN_TYPE)
2637 && TYPE_PRECISION (TREE_TYPE (arg0)) > 1)
2638 return;
2639 }
2640 else if (TYPE_PRECISION (TREE_TYPE (arg0)) == 1)
2641 {
2642 if (TYPE_UNSIGNED (TREE_TYPE (arg0)))
2643 is_bool = true;
2644 else
2645 return;
2646 }
2647 else if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE)
2648 is_bool = true;
2649 goto do_default;
2650 case EQ_EXPR:
2651 case NE_EXPR:
2652 case LT_EXPR:
2653 case LE_EXPR:
2654 case GE_EXPR:
2655 case GT_EXPR:
2656 is_bool = true;
2657 /* FALLTHRU */
2658 default:
2659 if (!is_bool)
2660 return;
2661 do_default:
2662 nexp = make_range_step (loc, code, arg0, arg1, exp_type,
2663 &low, &high, &in_p,
2664 &strict_overflow_p);
2665 if (nexp != NULL_TREE)
2666 {
2667 exp = nexp;
2668 gcc_assert (TREE_CODE (exp) == SSA_NAME);
2669 continue;
2670 }
2671 break;
2672 }
2673 break;
2674 }
2675 if (is_bool)
2676 {
2677 r->exp = exp;
2678 r->in_p = in_p;
2679 r->low = low;
2680 r->high = high;
2681 r->strict_overflow_p = strict_overflow_p;
2682 }
2683 }
2684
2685 /* Comparison function for qsort. Sort entries
2686 without SSA_NAME exp first, then with SSA_NAMEs sorted
2687 by increasing SSA_NAME_VERSION, and for the same SSA_NAMEs
2688 by increasing ->low and if ->low is the same, by increasing
2689 ->high. ->low == NULL_TREE means minimum, ->high == NULL_TREE
2690 maximum. */
2691
2692 static int
2693 range_entry_cmp (const void *a, const void *b)
2694 {
2695 const struct range_entry *p = (const struct range_entry *) a;
2696 const struct range_entry *q = (const struct range_entry *) b;
2697
2698 if (p->exp != NULL_TREE && TREE_CODE (p->exp) == SSA_NAME)
2699 {
2700 if (q->exp != NULL_TREE && TREE_CODE (q->exp) == SSA_NAME)
2701 {
2702 /* Group range_entries for the same SSA_NAME together. */
2703 if (SSA_NAME_VERSION (p->exp) < SSA_NAME_VERSION (q->exp))
2704 return -1;
2705 else if (SSA_NAME_VERSION (p->exp) > SSA_NAME_VERSION (q->exp))
2706 return 1;
2707 /* If ->low is different, NULL low goes first, then by
2708 ascending low. */
2709 if (p->low != NULL_TREE)
2710 {
2711 if (q->low != NULL_TREE)
2712 {
2713 tree tem = fold_binary (LT_EXPR, boolean_type_node,
2714 p->low, q->low);
2715 if (tem && integer_onep (tem))
2716 return -1;
2717 tem = fold_binary (GT_EXPR, boolean_type_node,
2718 p->low, q->low);
2719 if (tem && integer_onep (tem))
2720 return 1;
2721 }
2722 else
2723 return 1;
2724 }
2725 else if (q->low != NULL_TREE)
2726 return -1;
2727 /* If ->high is different, NULL high goes last, before that by
2728 ascending high. */
2729 if (p->high != NULL_TREE)
2730 {
2731 if (q->high != NULL_TREE)
2732 {
2733 tree tem = fold_binary (LT_EXPR, boolean_type_node,
2734 p->high, q->high);
2735 if (tem && integer_onep (tem))
2736 return -1;
2737 tem = fold_binary (GT_EXPR, boolean_type_node,
2738 p->high, q->high);
2739 if (tem && integer_onep (tem))
2740 return 1;
2741 }
2742 else
2743 return -1;
2744 }
2745 else if (q->high != NULL_TREE)
2746 return 1;
2747 /* If both ranges are the same, sort below by ascending idx. */
2748 }
2749 else
2750 return 1;
2751 }
2752 else if (q->exp != NULL_TREE && TREE_CODE (q->exp) == SSA_NAME)
2753 return -1;
2754
2755 if (p->idx < q->idx)
2756 return -1;
2757 else
2758 {
2759 gcc_checking_assert (p->idx > q->idx);
2760 return 1;
2761 }
2762 }
2763
2764 /* Helper function for update_range_test. Force EXPR into an SSA_NAME,
2765 insert needed statements BEFORE or after GSI. */
2766
2767 static tree
2768 force_into_ssa_name (gimple_stmt_iterator *gsi, tree expr, bool before)
2769 {
2770 enum gsi_iterator_update m = before ? GSI_SAME_STMT : GSI_CONTINUE_LINKING;
2771 tree ret = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE, before, m);
2772 if (TREE_CODE (ret) != SSA_NAME)
2773 {
2774 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (ret)), ret);
2775 if (before)
2776 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2777 else
2778 gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
2779 ret = gimple_assign_lhs (g);
2780 }
2781 return ret;
2782 }
2783
2784 /* Helper routine of optimize_range_test.
2785 [EXP, IN_P, LOW, HIGH, STRICT_OVERFLOW_P] is a merged range for
2786 RANGE and OTHERRANGE through OTHERRANGE + COUNT - 1 ranges,
2787 OPCODE and OPS are arguments of optimize_range_tests. If OTHERRANGE
2788 is NULL, OTHERRANGEP should not be and then OTHERRANGEP points to
2789 an array of COUNT pointers to other ranges. Return
2790 true if the range merge has been successful.
2791 If OPCODE is ERROR_MARK, this is called from within
2792 maybe_optimize_range_tests and is performing inter-bb range optimization.
2793 In that case, whether an op is BIT_AND_EXPR or BIT_IOR_EXPR is found in
2794 oe->rank. */
2795
2796 static bool
2797 update_range_test (struct range_entry *range, struct range_entry *otherrange,
2798 struct range_entry **otherrangep,
2799 unsigned int count, enum tree_code opcode,
2800 vec<operand_entry *> *ops, tree exp, gimple_seq seq,
2801 bool in_p, tree low, tree high, bool strict_overflow_p)
2802 {
2803 unsigned int idx = range->idx;
2804 struct range_entry *swap_with = NULL;
2805 basic_block rewrite_bb_first = NULL, rewrite_bb_last = NULL;
2806 if (opcode == ERROR_MARK)
2807 {
2808 /* For inter-bb range test optimization, pick from the range tests
2809 the one which is tested in the earliest condition (one dominating
2810 the others), because otherwise there could be some UB (e.g. signed
2811 overflow) in following bbs that we'd expose which wasn't there in
2812 the original program. See PR104196. */
2813 basic_block orig_range_bb = BASIC_BLOCK_FOR_FN (cfun, (*ops)[idx]->id);
2814 basic_block range_bb = orig_range_bb;
2815 for (unsigned int i = 0; i < count; i++)
2816 {
2817 struct range_entry *this_range;
2818 if (otherrange)
2819 this_range = otherrange + i;
2820 else
2821 this_range = otherrangep[i];
2822 operand_entry *oe = (*ops)[this_range->idx];
2823 basic_block this_bb = BASIC_BLOCK_FOR_FN (cfun, oe->id);
2824 if (range_bb != this_bb
2825 && dominated_by_p (CDI_DOMINATORS, range_bb, this_bb))
2826 {
2827 swap_with = this_range;
2828 range_bb = this_bb;
2829 idx = this_range->idx;
2830 }
2831 }
2832 /* If seq is non-NULL, it can contain statements that use SSA_NAMEs
2833 only defined in later blocks. In this case we can't move the
2834 merged comparison earlier, so instead check if there are any stmts
2835 that might trigger signed integer overflow in between and rewrite
2836 them. But only after we check if the optimization is possible. */
2837 if (seq && swap_with)
2838 {
2839 rewrite_bb_first = range_bb;
2840 rewrite_bb_last = orig_range_bb;
2841 idx = range->idx;
2842 swap_with = NULL;
2843 }
2844 }
2845 operand_entry *oe = (*ops)[idx];
2846 tree op = oe->op;
2847 gimple *stmt = op ? SSA_NAME_DEF_STMT (op)
2848 : last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id));
2849 location_t loc = gimple_location (stmt);
2850 tree optype = op ? TREE_TYPE (op) : boolean_type_node;
2851 tree tem = build_range_check (loc, optype, unshare_expr (exp),
2852 in_p, low, high);
2853 enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
2854 gimple_stmt_iterator gsi;
2855 unsigned int i, uid;
2856
2857 if (tem == NULL_TREE)
2858 return false;
2859
2860 /* If op is default def SSA_NAME, there is no place to insert the
2861 new comparison. Give up, unless we can use OP itself as the
2862 range test. */
2863 if (op && SSA_NAME_IS_DEFAULT_DEF (op))
2864 {
2865 if (op == range->exp
2866 && ((TYPE_PRECISION (optype) == 1 && TYPE_UNSIGNED (optype))
2867 || TREE_CODE (optype) == BOOLEAN_TYPE)
2868 && (op == tem
2869 || (TREE_CODE (tem) == EQ_EXPR
2870 && TREE_OPERAND (tem, 0) == op
2871 && integer_onep (TREE_OPERAND (tem, 1))))
2872 && opcode != BIT_IOR_EXPR
2873 && (opcode != ERROR_MARK || oe->rank != BIT_IOR_EXPR))
2874 {
2875 stmt = NULL;
2876 tem = op;
2877 }
2878 else
2879 return false;
2880 }
2881
2882 if (swap_with)
2883 std::swap (range->idx, swap_with->idx);
2884
2885 if (strict_overflow_p && issue_strict_overflow_warning (wc))
2886 warning_at (loc, OPT_Wstrict_overflow,
2887 "assuming signed overflow does not occur "
2888 "when simplifying range test");
2889
2890 if (dump_file && (dump_flags & TDF_DETAILS))
2891 {
2892 struct range_entry *r;
2893 fprintf (dump_file, "Optimizing range tests ");
2894 dump_range_entry (dump_file, range, false);
2895 for (i = 0; i < count; i++)
2896 {
2897 if (otherrange)
2898 r = otherrange + i;
2899 else
2900 r = otherrangep[i];
2901 if (r->exp
2902 && r->exp != range->exp
2903 && TREE_CODE (r->exp) == SSA_NAME)
2904 {
2905 fprintf (dump_file, " and ");
2906 dump_range_entry (dump_file, r, false);
2907 }
2908 else
2909 {
2910 fprintf (dump_file, " and");
2911 dump_range_entry (dump_file, r, true);
2912 }
2913 }
2914 fprintf (dump_file, "\n into ");
2915 print_generic_expr (dump_file, tem);
2916 fprintf (dump_file, "\n");
2917 }
2918
2919 /* In inter-bb range optimization mode, if we have a seq, we can't
2920 move the merged comparison to the earliest bb from the comparisons
2921 being replaced, so instead rewrite stmts that could trigger signed
2922 integer overflow. */
2923 for (basic_block bb = rewrite_bb_last;
2924 bb != rewrite_bb_first; bb = single_pred (bb))
2925 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
2926 !gsi_end_p (gsi); gsi_next (&gsi))
2927 {
2928 gimple *stmt = gsi_stmt (gsi);
2929 if (is_gimple_assign (stmt))
2930 if (tree lhs = gimple_assign_lhs (stmt))
2931 if ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
2932 || POINTER_TYPE_P (TREE_TYPE (lhs)))
2933 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (lhs)))
2934 {
2935 enum tree_code code = gimple_assign_rhs_code (stmt);
2936 if (arith_code_with_undefined_signed_overflow (code))
2937 {
2938 gimple_stmt_iterator gsip = gsi;
2939 gimple_stmt_iterator gsin = gsi;
2940 gsi_prev (&gsip);
2941 gsi_next (&gsin);
2942 rewrite_to_defined_overflow (&gsi);
2943 unsigned uid = gimple_uid (stmt);
2944 if (gsi_end_p (gsip))
2945 gsip = gsi_after_labels (bb);
2946 else
2947 gsi_next (&gsip);
2948 for (; gsi_stmt (gsip) != gsi_stmt (gsin);
2949 gsi_next (&gsip))
2950 gimple_set_uid (gsi_stmt (gsip), uid);
2951 }
2952 }
2953 }
2954
2955 if (opcode == BIT_IOR_EXPR
2956 || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
2957 tem = invert_truthvalue_loc (loc, tem);
2958
2959 tem = fold_convert_loc (loc, optype, tem);
2960 if (stmt)
2961 {
2962 gsi = gsi_for_stmt (stmt);
2963 uid = gimple_uid (stmt);
2964 }
2965 else
2966 {
2967 gsi = gsi_none ();
2968 uid = 0;
2969 }
2970 if (stmt == NULL)
2971 gcc_checking_assert (tem == op);
2972 /* In rare cases range->exp can be equal to lhs of stmt.
2973 In that case we have to insert after the stmt rather then before
2974 it. If stmt is a PHI, insert it at the start of the basic block. */
2975 else if (op != range->exp)
2976 {
2977 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
2978 tem = force_into_ssa_name (&gsi, tem, true);
2979 gsi_prev (&gsi);
2980 }
2981 else if (gimple_code (stmt) != GIMPLE_PHI)
2982 {
2983 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
2984 tem = force_into_ssa_name (&gsi, tem, false);
2985 }
2986 else
2987 {
2988 gsi = gsi_after_labels (gimple_bb (stmt));
2989 if (!gsi_end_p (gsi))
2990 uid = gimple_uid (gsi_stmt (gsi));
2991 else
2992 {
2993 gsi = gsi_start_bb (gimple_bb (stmt));
2994 uid = 1;
2995 while (!gsi_end_p (gsi))
2996 {
2997 uid = gimple_uid (gsi_stmt (gsi));
2998 gsi_next (&gsi);
2999 }
3000 }
3001 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
3002 tem = force_into_ssa_name (&gsi, tem, true);
3003 if (gsi_end_p (gsi))
3004 gsi = gsi_last_bb (gimple_bb (stmt));
3005 else
3006 gsi_prev (&gsi);
3007 }
3008 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
3009 if (gimple_uid (gsi_stmt (gsi)))
3010 break;
3011 else
3012 gimple_set_uid (gsi_stmt (gsi), uid);
3013
3014 oe->op = tem;
3015 range->exp = exp;
3016 range->low = low;
3017 range->high = high;
3018 range->in_p = in_p;
3019 range->strict_overflow_p = false;
3020
3021 for (i = 0; i < count; i++)
3022 {
3023 if (otherrange)
3024 range = otherrange + i;
3025 else
3026 range = otherrangep[i];
3027 oe = (*ops)[range->idx];
3028 /* Now change all the other range test immediate uses, so that
3029 those tests will be optimized away. */
3030 if (opcode == ERROR_MARK)
3031 {
3032 if (oe->op)
3033 oe->op = build_int_cst (TREE_TYPE (oe->op),
3034 oe->rank == BIT_IOR_EXPR ? 0 : 1);
3035 else
3036 oe->op = (oe->rank == BIT_IOR_EXPR
3037 ? boolean_false_node : boolean_true_node);
3038 }
3039 else
3040 oe->op = error_mark_node;
3041 range->exp = NULL_TREE;
3042 range->low = NULL_TREE;
3043 range->high = NULL_TREE;
3044 }
3045 return true;
3046 }
3047
3048 /* Optimize X == CST1 || X == CST2
3049 if popcount (CST1 ^ CST2) == 1 into
3050 (X & ~(CST1 ^ CST2)) == (CST1 & ~(CST1 ^ CST2)).
3051 Similarly for ranges. E.g.
3052 X != 2 && X != 3 && X != 10 && X != 11
3053 will be transformed by the previous optimization into
3054 !((X - 2U) <= 1U || (X - 10U) <= 1U)
3055 and this loop can transform that into
3056 !(((X & ~8) - 2U) <= 1U). */
3057
3058 static bool
3059 optimize_range_tests_xor (enum tree_code opcode, tree type,
3060 tree lowi, tree lowj, tree highi, tree highj,
3061 vec<operand_entry *> *ops,
3062 struct range_entry *rangei,
3063 struct range_entry *rangej)
3064 {
3065 tree lowxor, highxor, tem, exp;
3066 /* Check lowi ^ lowj == highi ^ highj and
3067 popcount (lowi ^ lowj) == 1. */
3068 lowxor = fold_binary (BIT_XOR_EXPR, type, lowi, lowj);
3069 if (lowxor == NULL_TREE || TREE_CODE (lowxor) != INTEGER_CST)
3070 return false;
3071 if (!integer_pow2p (lowxor))
3072 return false;
3073 highxor = fold_binary (BIT_XOR_EXPR, type, highi, highj);
3074 if (!tree_int_cst_equal (lowxor, highxor))
3075 return false;
3076
3077 exp = rangei->exp;
3078 scalar_int_mode mode = as_a <scalar_int_mode> (TYPE_MODE (type));
3079 int prec = GET_MODE_PRECISION (mode);
3080 if (TYPE_PRECISION (type) < prec
3081 || (wi::to_wide (TYPE_MIN_VALUE (type))
3082 != wi::min_value (prec, TYPE_SIGN (type)))
3083 || (wi::to_wide (TYPE_MAX_VALUE (type))
3084 != wi::max_value (prec, TYPE_SIGN (type))))
3085 {
3086 type = build_nonstandard_integer_type (prec, TYPE_UNSIGNED (type));
3087 exp = fold_convert (type, exp);
3088 lowxor = fold_convert (type, lowxor);
3089 lowi = fold_convert (type, lowi);
3090 highi = fold_convert (type, highi);
3091 }
3092 tem = fold_build1 (BIT_NOT_EXPR, type, lowxor);
3093 exp = fold_build2 (BIT_AND_EXPR, type, exp, tem);
3094 lowj = fold_build2 (BIT_AND_EXPR, type, lowi, tem);
3095 highj = fold_build2 (BIT_AND_EXPR, type, highi, tem);
3096 if (update_range_test (rangei, rangej, NULL, 1, opcode, ops, exp,
3097 NULL, rangei->in_p, lowj, highj,
3098 rangei->strict_overflow_p
3099 || rangej->strict_overflow_p))
3100 return true;
3101 return false;
3102 }
3103
3104 /* Optimize X == CST1 || X == CST2
3105 if popcount (CST2 - CST1) == 1 into
3106 ((X - CST1) & ~(CST2 - CST1)) == 0.
3107 Similarly for ranges. E.g.
3108 X == 43 || X == 76 || X == 44 || X == 78 || X == 77 || X == 46
3109 || X == 75 || X == 45
3110 will be transformed by the previous optimization into
3111 (X - 43U) <= 3U || (X - 75U) <= 3U
3112 and this loop can transform that into
3113 ((X - 43U) & ~(75U - 43U)) <= 3U. */
3114 static bool
3115 optimize_range_tests_diff (enum tree_code opcode, tree type,
3116 tree lowi, tree lowj, tree highi, tree highj,
3117 vec<operand_entry *> *ops,
3118 struct range_entry *rangei,
3119 struct range_entry *rangej)
3120 {
3121 tree tem1, tem2, mask;
3122 /* Check highi - lowi == highj - lowj. */
3123 tem1 = fold_binary (MINUS_EXPR, type, highi, lowi);
3124 if (tem1 == NULL_TREE || TREE_CODE (tem1) != INTEGER_CST)
3125 return false;
3126 tem2 = fold_binary (MINUS_EXPR, type, highj, lowj);
3127 if (!tree_int_cst_equal (tem1, tem2))
3128 return false;
3129 /* Check popcount (lowj - lowi) == 1. */
3130 tem1 = fold_binary (MINUS_EXPR, type, lowj, lowi);
3131 if (tem1 == NULL_TREE || TREE_CODE (tem1) != INTEGER_CST)
3132 return false;
3133 if (!integer_pow2p (tem1))
3134 return false;
3135
3136 scalar_int_mode mode = as_a <scalar_int_mode> (TYPE_MODE (type));
3137 int prec = GET_MODE_PRECISION (mode);
3138 if (TYPE_PRECISION (type) < prec
3139 || (wi::to_wide (TYPE_MIN_VALUE (type))
3140 != wi::min_value (prec, TYPE_SIGN (type)))
3141 || (wi::to_wide (TYPE_MAX_VALUE (type))
3142 != wi::max_value (prec, TYPE_SIGN (type))))
3143 type = build_nonstandard_integer_type (prec, 1);
3144 else
3145 type = unsigned_type_for (type);
3146 tem1 = fold_convert (type, tem1);
3147 tem2 = fold_convert (type, tem2);
3148 lowi = fold_convert (type, lowi);
3149 mask = fold_build1 (BIT_NOT_EXPR, type, tem1);
3150 tem1 = fold_build2 (MINUS_EXPR, type,
3151 fold_convert (type, rangei->exp), lowi);
3152 tem1 = fold_build2 (BIT_AND_EXPR, type, tem1, mask);
3153 lowj = build_int_cst (type, 0);
3154 if (update_range_test (rangei, rangej, NULL, 1, opcode, ops, tem1,
3155 NULL, rangei->in_p, lowj, tem2,
3156 rangei->strict_overflow_p
3157 || rangej->strict_overflow_p))
3158 return true;
3159 return false;
3160 }
3161
3162 /* It does some common checks for function optimize_range_tests_xor and
3163 optimize_range_tests_diff.
3164 If OPTIMIZE_XOR is TRUE, it calls optimize_range_tests_xor.
3165 Else it calls optimize_range_tests_diff. */
3166
3167 static bool
3168 optimize_range_tests_1 (enum tree_code opcode, int first, int length,
3169 bool optimize_xor, vec<operand_entry *> *ops,
3170 struct range_entry *ranges)
3171 {
3172 int i, j;
3173 bool any_changes = false;
3174 for (i = first; i < length; i++)
3175 {
3176 tree lowi, highi, lowj, highj, type, tem;
3177
3178 if (ranges[i].exp == NULL_TREE || ranges[i].in_p)
3179 continue;
3180 type = TREE_TYPE (ranges[i].exp);
3181 if (!INTEGRAL_TYPE_P (type))
3182 continue;
3183 lowi = ranges[i].low;
3184 if (lowi == NULL_TREE)
3185 lowi = TYPE_MIN_VALUE (type);
3186 highi = ranges[i].high;
3187 if (highi == NULL_TREE)
3188 continue;
3189 for (j = i + 1; j < length && j < i + 64; j++)
3190 {
3191 bool changes;
3192 if (ranges[i].exp != ranges[j].exp || ranges[j].in_p)
3193 continue;
3194 lowj = ranges[j].low;
3195 if (lowj == NULL_TREE)
3196 continue;
3197 highj = ranges[j].high;
3198 if (highj == NULL_TREE)
3199 highj = TYPE_MAX_VALUE (type);
3200 /* Check lowj > highi. */
3201 tem = fold_binary (GT_EXPR, boolean_type_node,
3202 lowj, highi);
3203 if (tem == NULL_TREE || !integer_onep (tem))
3204 continue;
3205 if (optimize_xor)
3206 changes = optimize_range_tests_xor (opcode, type, lowi, lowj,
3207 highi, highj, ops,
3208 ranges + i, ranges + j);
3209 else
3210 changes = optimize_range_tests_diff (opcode, type, lowi, lowj,
3211 highi, highj, ops,
3212 ranges + i, ranges + j);
3213 if (changes)
3214 {
3215 any_changes = true;
3216 break;
3217 }
3218 }
3219 }
3220 return any_changes;
3221 }
3222
3223 /* Helper function of optimize_range_tests_to_bit_test. Handle a single
3224 range, EXP, LOW, HIGH, compute bit mask of bits to test and return
3225 EXP on success, NULL otherwise. */
3226
3227 static tree
3228 extract_bit_test_mask (tree exp, int prec, tree totallow, tree low, tree high,
3229 wide_int *mask, tree *totallowp)
3230 {
3231 tree tem = int_const_binop (MINUS_EXPR, high, low);
3232 if (tem == NULL_TREE
3233 || TREE_CODE (tem) != INTEGER_CST
3234 || TREE_OVERFLOW (tem)
3235 || tree_int_cst_sgn (tem) == -1
3236 || compare_tree_int (tem, prec) != -1)
3237 return NULL_TREE;
3238
3239 unsigned HOST_WIDE_INT max = tree_to_uhwi (tem) + 1;
3240 *mask = wi::shifted_mask (0, max, false, prec);
3241 if (TREE_CODE (exp) == BIT_AND_EXPR
3242 && TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
3243 {
3244 widest_int msk = wi::to_widest (TREE_OPERAND (exp, 1));
3245 msk = wi::zext (~msk, TYPE_PRECISION (TREE_TYPE (exp)));
3246 if (wi::popcount (msk) == 1
3247 && wi::ltu_p (msk, prec - max))
3248 {
3249 *mask |= wi::shifted_mask (msk.to_uhwi (), max, false, prec);
3250 max += msk.to_uhwi ();
3251 exp = TREE_OPERAND (exp, 0);
3252 if (integer_zerop (low)
3253 && TREE_CODE (exp) == PLUS_EXPR
3254 && TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
3255 {
3256 tree ret = TREE_OPERAND (exp, 0);
3257 STRIP_NOPS (ret);
3258 widest_int bias
3259 = wi::neg (wi::sext (wi::to_widest (TREE_OPERAND (exp, 1)),
3260 TYPE_PRECISION (TREE_TYPE (low))));
3261 tree tbias = wide_int_to_tree (TREE_TYPE (ret), bias);
3262 if (totallowp)
3263 {
3264 *totallowp = tbias;
3265 return ret;
3266 }
3267 else if (!tree_int_cst_lt (totallow, tbias))
3268 return NULL_TREE;
3269 bias = wi::to_widest (tbias);
3270 bias -= wi::to_widest (totallow);
3271 if (bias >= 0 && bias < prec - max)
3272 {
3273 *mask = wi::lshift (*mask, bias);
3274 return ret;
3275 }
3276 }
3277 }
3278 }
3279 if (totallowp)
3280 return exp;
3281 if (!tree_int_cst_lt (totallow, low))
3282 return exp;
3283 tem = int_const_binop (MINUS_EXPR, low, totallow);
3284 if (tem == NULL_TREE
3285 || TREE_CODE (tem) != INTEGER_CST
3286 || TREE_OVERFLOW (tem)
3287 || compare_tree_int (tem, prec - max) == 1)
3288 return NULL_TREE;
3289
3290 *mask = wi::lshift (*mask, wi::to_widest (tem));
3291 return exp;
3292 }
3293
3294 /* Attempt to optimize small range tests using bit test.
3295 E.g.
3296 X != 43 && X != 76 && X != 44 && X != 78 && X != 49
3297 && X != 77 && X != 46 && X != 75 && X != 45 && X != 82
3298 has been by earlier optimizations optimized into:
3299 ((X - 43U) & ~32U) > 3U && X != 49 && X != 82
3300 As all the 43 through 82 range is less than 64 numbers,
3301 for 64-bit word targets optimize that into:
3302 (X - 43U) > 40U && ((1 << (X - 43U)) & 0x8F0000004FULL) == 0 */
3303
3304 static bool
3305 optimize_range_tests_to_bit_test (enum tree_code opcode, int first, int length,
3306 vec<operand_entry *> *ops,
3307 struct range_entry *ranges)
3308 {
3309 int i, j;
3310 bool any_changes = false;
3311 int prec = GET_MODE_BITSIZE (word_mode);
3312 auto_vec<struct range_entry *, 64> candidates;
3313
3314 for (i = first; i < length - 1; i++)
3315 {
3316 tree lowi, highi, lowj, highj, type;
3317
3318 if (ranges[i].exp == NULL_TREE || ranges[i].in_p)
3319 continue;
3320 type = TREE_TYPE (ranges[i].exp);
3321 if (!INTEGRAL_TYPE_P (type))
3322 continue;
3323 lowi = ranges[i].low;
3324 if (lowi == NULL_TREE)
3325 lowi = TYPE_MIN_VALUE (type);
3326 highi = ranges[i].high;
3327 if (highi == NULL_TREE)
3328 continue;
3329 wide_int mask;
3330 tree exp = extract_bit_test_mask (ranges[i].exp, prec, lowi, lowi,
3331 highi, &mask, &lowi);
3332 if (exp == NULL_TREE)
3333 continue;
3334 bool strict_overflow_p = ranges[i].strict_overflow_p;
3335 candidates.truncate (0);
3336 int end = MIN (i + 64, length);
3337 for (j = i + 1; j < end; j++)
3338 {
3339 tree exp2;
3340 if (ranges[j].exp == NULL_TREE || ranges[j].in_p)
3341 continue;
3342 if (ranges[j].exp == exp)
3343 ;
3344 else if (TREE_CODE (ranges[j].exp) == BIT_AND_EXPR)
3345 {
3346 exp2 = TREE_OPERAND (ranges[j].exp, 0);
3347 if (exp2 == exp)
3348 ;
3349 else if (TREE_CODE (exp2) == PLUS_EXPR)
3350 {
3351 exp2 = TREE_OPERAND (exp2, 0);
3352 STRIP_NOPS (exp2);
3353 if (exp2 != exp)
3354 continue;
3355 }
3356 else
3357 continue;
3358 }
3359 else
3360 continue;
3361 lowj = ranges[j].low;
3362 if (lowj == NULL_TREE)
3363 continue;
3364 highj = ranges[j].high;
3365 if (highj == NULL_TREE)
3366 highj = TYPE_MAX_VALUE (TREE_TYPE (lowj));
3367 wide_int mask2;
3368 exp2 = extract_bit_test_mask (ranges[j].exp, prec, lowi, lowj,
3369 highj, &mask2, NULL);
3370 if (exp2 != exp)
3371 continue;
3372 mask |= mask2;
3373 strict_overflow_p |= ranges[j].strict_overflow_p;
3374 candidates.safe_push (&ranges[j]);
3375 }
3376
3377 /* If every possible relative value of the expression is a valid shift
3378 amount, then we can merge the entry test in the bit test. In this
3379 case, if we would need otherwise 2 or more comparisons, then use
3380 the bit test; in the other cases, the threshold is 3 comparisons. */
3381 bool entry_test_needed;
3382 int_range_max r;
3383 if (TREE_CODE (exp) == SSA_NAME
3384 && get_range_query (cfun)->range_of_expr (r, exp)
3385 && !r.undefined_p ()
3386 && !r.varying_p ()
3387 && wi::leu_p (r.upper_bound () - r.lower_bound (), prec - 1))
3388 {
3389 wide_int min = r.lower_bound ();
3390 wide_int ilowi = wi::to_wide (lowi);
3391 if (wi::lt_p (min, ilowi, TYPE_SIGN (TREE_TYPE (lowi))))
3392 {
3393 lowi = wide_int_to_tree (TREE_TYPE (lowi), min);
3394 mask = wi::lshift (mask, ilowi - min);
3395 }
3396 else if (wi::gt_p (min, ilowi, TYPE_SIGN (TREE_TYPE (lowi))))
3397 {
3398 lowi = wide_int_to_tree (TREE_TYPE (lowi), min);
3399 mask = wi::lrshift (mask, min - ilowi);
3400 }
3401 entry_test_needed = false;
3402 }
3403 else
3404 entry_test_needed = true;
3405 if (candidates.length () >= (entry_test_needed ? 2 : 1))
3406 {
3407 tree high = wide_int_to_tree (TREE_TYPE (lowi),
3408 wi::to_widest (lowi)
3409 + prec - 1 - wi::clz (mask));
3410 operand_entry *oe = (*ops)[ranges[i].idx];
3411 tree op = oe->op;
3412 gimple *stmt = op ? SSA_NAME_DEF_STMT (op)
3413 : last_nondebug_stmt (BASIC_BLOCK_FOR_FN
3414 (cfun, oe->id));
3415 location_t loc = gimple_location (stmt);
3416 tree optype = op ? TREE_TYPE (op) : boolean_type_node;
3417
3418 /* See if it isn't cheaper to pretend the minimum value of the
3419 range is 0, if maximum value is small enough.
3420 We can avoid then subtraction of the minimum value, but the
3421 mask constant could be perhaps more expensive. */
3422 if (compare_tree_int (lowi, 0) > 0
3423 && compare_tree_int (high, prec) < 0
3424 && (entry_test_needed || wi::ltu_p (r.upper_bound (), prec)))
3425 {
3426 int cost_diff;
3427 HOST_WIDE_INT m = tree_to_uhwi (lowi);
3428 rtx reg = gen_raw_REG (word_mode, 10000);
3429 bool speed_p = optimize_bb_for_speed_p (gimple_bb (stmt));
3430 cost_diff = set_src_cost (gen_rtx_PLUS (word_mode, reg,
3431 GEN_INT (-m)),
3432 word_mode, speed_p);
3433 rtx r = immed_wide_int_const (mask, word_mode);
3434 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
3435 word_mode, speed_p);
3436 r = immed_wide_int_const (wi::lshift (mask, m), word_mode);
3437 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
3438 word_mode, speed_p);
3439 if (cost_diff > 0)
3440 {
3441 mask = wi::lshift (mask, m);
3442 lowi = build_zero_cst (TREE_TYPE (lowi));
3443 }
3444 }
3445
3446 tree tem;
3447 if (entry_test_needed)
3448 {
3449 tem = build_range_check (loc, optype, unshare_expr (exp),
3450 false, lowi, high);
3451 if (tem == NULL_TREE || is_gimple_val (tem))
3452 continue;
3453 }
3454 else
3455 tem = NULL_TREE;
3456 tree etype = unsigned_type_for (TREE_TYPE (exp));
3457 exp = fold_build2_loc (loc, MINUS_EXPR, etype,
3458 fold_convert_loc (loc, etype, exp),
3459 fold_convert_loc (loc, etype, lowi));
3460 exp = fold_convert_loc (loc, integer_type_node, exp);
3461 tree word_type = lang_hooks.types.type_for_mode (word_mode, 1);
3462 exp = fold_build2_loc (loc, LSHIFT_EXPR, word_type,
3463 build_int_cst (word_type, 1), exp);
3464 exp = fold_build2_loc (loc, BIT_AND_EXPR, word_type, exp,
3465 wide_int_to_tree (word_type, mask));
3466 exp = fold_build2_loc (loc, EQ_EXPR, optype, exp,
3467 build_zero_cst (word_type));
3468 if (is_gimple_val (exp))
3469 continue;
3470
3471 /* The shift might have undefined behavior if TEM is true,
3472 but reassociate_bb isn't prepared to have basic blocks
3473 split when it is running. So, temporarily emit a code
3474 with BIT_IOR_EXPR instead of &&, and fix it up in
3475 branch_fixup. */
3476 gimple_seq seq = NULL;
3477 if (tem)
3478 {
3479 tem = force_gimple_operand (tem, &seq, true, NULL_TREE);
3480 gcc_assert (TREE_CODE (tem) == SSA_NAME);
3481 gimple_set_visited (SSA_NAME_DEF_STMT (tem), true);
3482 }
3483 gimple_seq seq2;
3484 exp = force_gimple_operand (exp, &seq2, true, NULL_TREE);
3485 gimple_seq_add_seq_without_update (&seq, seq2);
3486 gcc_assert (TREE_CODE (exp) == SSA_NAME);
3487 gimple_set_visited (SSA_NAME_DEF_STMT (exp), true);
3488 if (tem)
3489 {
3490 gimple *g = gimple_build_assign (make_ssa_name (optype),
3491 BIT_IOR_EXPR, tem, exp);
3492 gimple_set_location (g, loc);
3493 gimple_seq_add_stmt_without_update (&seq, g);
3494 exp = gimple_assign_lhs (g);
3495 }
3496 tree val = build_zero_cst (optype);
3497 if (update_range_test (&ranges[i], NULL, candidates.address (),
3498 candidates.length (), opcode, ops, exp,
3499 seq, false, val, val, strict_overflow_p))
3500 {
3501 any_changes = true;
3502 if (tem)
3503 reassoc_branch_fixups.safe_push (tem);
3504 }
3505 else
3506 gimple_seq_discard (seq);
3507 }
3508 }
3509 return any_changes;
3510 }
3511
3512 /* Optimize x != 0 && y != 0 && z != 0 into (x | y | z) != 0
3513 and similarly x != -1 && y != -1 && y != -1 into (x & y & z) != -1.
3514 Also, handle x < C && y < C && z < C where C is power of two as
3515 (x | y | z) < C. And also handle signed x < 0 && y < 0 && z < 0
3516 as (x | y | z) < 0. */
3517
3518 static bool
3519 optimize_range_tests_cmp_bitwise (enum tree_code opcode, int first, int length,
3520 vec<operand_entry *> *ops,
3521 struct range_entry *ranges)
3522 {
3523 int i;
3524 unsigned int b;
3525 bool any_changes = false;
3526 auto_vec<int, 128> buckets;
3527 auto_vec<int, 32> chains;
3528 auto_vec<struct range_entry *, 32> candidates;
3529
3530 for (i = first; i < length; i++)
3531 {
3532 int idx;
3533
3534 if (ranges[i].exp == NULL_TREE
3535 || TREE_CODE (ranges[i].exp) != SSA_NAME
3536 || TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) <= 1
3537 || TREE_CODE (TREE_TYPE (ranges[i].exp)) == BOOLEAN_TYPE)
3538 continue;
3539
3540 if (ranges[i].low != NULL_TREE
3541 && ranges[i].high != NULL_TREE
3542 && ranges[i].in_p
3543 && tree_int_cst_equal (ranges[i].low, ranges[i].high))
3544 {
3545 idx = !integer_zerop (ranges[i].low);
3546 if (idx && !integer_all_onesp (ranges[i].low))
3547 continue;
3548 }
3549 else if (ranges[i].high != NULL_TREE
3550 && TREE_CODE (ranges[i].high) == INTEGER_CST
3551 && ranges[i].in_p)
3552 {
3553 wide_int w = wi::to_wide (ranges[i].high);
3554 int prec = TYPE_PRECISION (TREE_TYPE (ranges[i].exp));
3555 int l = wi::clz (w);
3556 idx = 2;
3557 if (l <= 0
3558 || l >= prec
3559 || w != wi::mask (prec - l, false, prec))
3560 continue;
3561 if (!((TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
3562 && ranges[i].low == NULL_TREE)
3563 || (ranges[i].low
3564 && integer_zerop (ranges[i].low))))
3565 continue;
3566 }
3567 else if (ranges[i].high == NULL_TREE
3568 && ranges[i].low != NULL_TREE
3569 /* Perform this optimization only in the last
3570 reassoc pass, as it interferes with the reassociation
3571 itself or could also with VRP etc. which might not
3572 be able to virtually undo the optimization. */
3573 && !reassoc_insert_powi_p
3574 && !TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
3575 && integer_zerop (ranges[i].low))
3576 idx = 3;
3577 else
3578 continue;
3579
3580 b = TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) * 4 + idx;
3581 if (buckets.length () <= b)
3582 buckets.safe_grow_cleared (b + 1, true);
3583 if (chains.length () <= (unsigned) i)
3584 chains.safe_grow (i + 1, true);
3585 chains[i] = buckets[b];
3586 buckets[b] = i + 1;
3587 }
3588
3589 FOR_EACH_VEC_ELT (buckets, b, i)
3590 if (i && chains[i - 1])
3591 {
3592 int j, k = i;
3593 if ((b % 4) == 2)
3594 {
3595 /* When ranges[X - 1].high + 1 is a power of two,
3596 we need to process the same bucket up to
3597 precision - 1 times, each time split the entries
3598 with the same high bound into one chain and the
3599 rest into another one to be processed later. */
3600 int this_prev = i;
3601 int other_prev = 0;
3602 for (j = chains[i - 1]; j; j = chains[j - 1])
3603 {
3604 if (tree_int_cst_equal (ranges[i - 1].high,
3605 ranges[j - 1].high))
3606 {
3607 chains[this_prev - 1] = j;
3608 this_prev = j;
3609 }
3610 else if (other_prev == 0)
3611 {
3612 buckets[b] = j;
3613 other_prev = j;
3614 }
3615 else
3616 {
3617 chains[other_prev - 1] = j;
3618 other_prev = j;
3619 }
3620 }
3621 chains[this_prev - 1] = 0;
3622 if (other_prev)
3623 chains[other_prev - 1] = 0;
3624 if (chains[i - 1] == 0)
3625 {
3626 if (other_prev)
3627 b--;
3628 continue;
3629 }
3630 }
3631 for (j = chains[i - 1]; j; j = chains[j - 1])
3632 {
3633 gimple *gk = SSA_NAME_DEF_STMT (ranges[k - 1].exp);
3634 gimple *gj = SSA_NAME_DEF_STMT (ranges[j - 1].exp);
3635 if (reassoc_stmt_dominates_stmt_p (gk, gj))
3636 k = j;
3637 }
3638 tree type1 = TREE_TYPE (ranges[k - 1].exp);
3639 tree type2 = NULL_TREE;
3640 bool strict_overflow_p = false;
3641 candidates.truncate (0);
3642 if (POINTER_TYPE_P (type1) || TREE_CODE (type1) == OFFSET_TYPE)
3643 type1 = pointer_sized_int_node;
3644 for (j = i; j; j = chains[j - 1])
3645 {
3646 tree type = TREE_TYPE (ranges[j - 1].exp);
3647 strict_overflow_p |= ranges[j - 1].strict_overflow_p;
3648 if (POINTER_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE)
3649 type = pointer_sized_int_node;
3650 if ((b % 4) == 3)
3651 {
3652 /* For the signed < 0 cases, the types should be
3653 really compatible (all signed with the same precision,
3654 instead put ranges that have different in_p from
3655 k first. */
3656 if (!useless_type_conversion_p (type1, type))
3657 continue;
3658 if (ranges[j - 1].in_p != ranges[k - 1].in_p)
3659 candidates.safe_push (&ranges[j - 1]);
3660 type2 = type1;
3661 continue;
3662 }
3663 if (j == k
3664 || useless_type_conversion_p (type1, type))
3665 ;
3666 else if (type2 == NULL_TREE
3667 || useless_type_conversion_p (type2, type))
3668 {
3669 if (type2 == NULL_TREE)
3670 type2 = type;
3671 candidates.safe_push (&ranges[j - 1]);
3672 }
3673 }
3674 unsigned l = candidates.length ();
3675 for (j = i; j; j = chains[j - 1])
3676 {
3677 tree type = TREE_TYPE (ranges[j - 1].exp);
3678 if (j == k)
3679 continue;
3680 if (POINTER_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE)
3681 type = pointer_sized_int_node;
3682 if ((b % 4) == 3)
3683 {
3684 if (!useless_type_conversion_p (type1, type))
3685 continue;
3686 if (ranges[j - 1].in_p == ranges[k - 1].in_p)
3687 candidates.safe_push (&ranges[j - 1]);
3688 continue;
3689 }
3690 if (useless_type_conversion_p (type1, type))
3691 ;
3692 else if (type2 == NULL_TREE
3693 || useless_type_conversion_p (type2, type))
3694 continue;
3695 candidates.safe_push (&ranges[j - 1]);
3696 }
3697 gimple_seq seq = NULL;
3698 tree op = NULL_TREE;
3699 unsigned int id;
3700 struct range_entry *r;
3701 candidates.safe_push (&ranges[k - 1]);
3702 FOR_EACH_VEC_ELT (candidates, id, r)
3703 {
3704 gimple *g;
3705 enum tree_code code;
3706 if (id == 0)
3707 {
3708 op = r->exp;
3709 continue;
3710 }
3711 if (id == l
3712 || POINTER_TYPE_P (TREE_TYPE (op))
3713 || TREE_CODE (TREE_TYPE (op)) == OFFSET_TYPE)
3714 {
3715 code = (b % 4) == 3 ? BIT_NOT_EXPR : NOP_EXPR;
3716 tree type3 = id >= l ? type1 : pointer_sized_int_node;
3717 if (code == BIT_NOT_EXPR
3718 && TREE_CODE (TREE_TYPE (op)) == OFFSET_TYPE)
3719 {
3720 g = gimple_build_assign (make_ssa_name (type3),
3721 NOP_EXPR, op);
3722 gimple_seq_add_stmt_without_update (&seq, g);
3723 op = gimple_assign_lhs (g);
3724 }
3725 g = gimple_build_assign (make_ssa_name (type3), code, op);
3726 gimple_seq_add_stmt_without_update (&seq, g);
3727 op = gimple_assign_lhs (g);
3728 }
3729 tree type = TREE_TYPE (r->exp);
3730 tree exp = r->exp;
3731 if (POINTER_TYPE_P (type)
3732 || TREE_CODE (type) == OFFSET_TYPE
3733 || (id >= l && !useless_type_conversion_p (type1, type)))
3734 {
3735 tree type3 = id >= l ? type1 : pointer_sized_int_node;
3736 g = gimple_build_assign (make_ssa_name (type3), NOP_EXPR, exp);
3737 gimple_seq_add_stmt_without_update (&seq, g);
3738 exp = gimple_assign_lhs (g);
3739 }
3740 if ((b % 4) == 3)
3741 code = r->in_p ? BIT_IOR_EXPR : BIT_AND_EXPR;
3742 else
3743 code = (b % 4) == 1 ? BIT_AND_EXPR : BIT_IOR_EXPR;
3744 g = gimple_build_assign (make_ssa_name (id >= l ? type1 : type2),
3745 code, op, exp);
3746 gimple_seq_add_stmt_without_update (&seq, g);
3747 op = gimple_assign_lhs (g);
3748 }
3749 type1 = TREE_TYPE (ranges[k - 1].exp);
3750 if (POINTER_TYPE_P (type1) || TREE_CODE (type1) == OFFSET_TYPE)
3751 {
3752 gimple *g
3753 = gimple_build_assign (make_ssa_name (type1), NOP_EXPR, op);
3754 gimple_seq_add_stmt_without_update (&seq, g);
3755 op = gimple_assign_lhs (g);
3756 }
3757 candidates.pop ();
3758 if (update_range_test (&ranges[k - 1], NULL, candidates.address (),
3759 candidates.length (), opcode, ops, op,
3760 seq, ranges[k - 1].in_p, ranges[k - 1].low,
3761 ranges[k - 1].high, strict_overflow_p))
3762 any_changes = true;
3763 else
3764 gimple_seq_discard (seq);
3765 if ((b % 4) == 2 && buckets[b] != i)
3766 /* There is more work to do for this bucket. */
3767 b--;
3768 }
3769
3770 return any_changes;
3771 }
3772
3773 /* Attempt to optimize for signed a and b where b is known to be >= 0:
3774 a >= 0 && a < b into (unsigned) a < (unsigned) b
3775 a >= 0 && a <= b into (unsigned) a <= (unsigned) b */
3776
3777 static bool
3778 optimize_range_tests_var_bound (enum tree_code opcode, int first, int length,
3779 vec<operand_entry *> *ops,
3780 struct range_entry *ranges,
3781 basic_block first_bb)
3782 {
3783 int i;
3784 bool any_changes = false;
3785 hash_map<tree, int> *map = NULL;
3786
3787 for (i = first; i < length; i++)
3788 {
3789 if (ranges[i].exp == NULL_TREE
3790 || TREE_CODE (ranges[i].exp) != SSA_NAME
3791 || !ranges[i].in_p)
3792 continue;
3793
3794 tree type = TREE_TYPE (ranges[i].exp);
3795 if (!INTEGRAL_TYPE_P (type)
3796 || TYPE_UNSIGNED (type)
3797 || ranges[i].low == NULL_TREE
3798 || !integer_zerop (ranges[i].low)
3799 || ranges[i].high != NULL_TREE)
3800 continue;
3801 /* EXP >= 0 here. */
3802 if (map == NULL)
3803 map = new hash_map <tree, int>;
3804 map->put (ranges[i].exp, i);
3805 }
3806
3807 if (map == NULL)
3808 return false;
3809
3810 for (i = 0; i < length; i++)
3811 {
3812 bool in_p = ranges[i].in_p;
3813 if (ranges[i].low == NULL_TREE
3814 || ranges[i].high == NULL_TREE)
3815 continue;
3816 if (!integer_zerop (ranges[i].low)
3817 || !integer_zerop (ranges[i].high))
3818 {
3819 if (ranges[i].exp
3820 && TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) == 1
3821 && TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
3822 && integer_onep (ranges[i].low)
3823 && integer_onep (ranges[i].high))
3824 in_p = !in_p;
3825 else
3826 continue;
3827 }
3828
3829 gimple *stmt;
3830 tree_code ccode;
3831 tree rhs1, rhs2;
3832 if (ranges[i].exp)
3833 {
3834 if (TREE_CODE (ranges[i].exp) != SSA_NAME)
3835 continue;
3836 stmt = SSA_NAME_DEF_STMT (ranges[i].exp);
3837 if (!is_gimple_assign (stmt))
3838 continue;
3839 ccode = gimple_assign_rhs_code (stmt);
3840 rhs1 = gimple_assign_rhs1 (stmt);
3841 rhs2 = gimple_assign_rhs2 (stmt);
3842 }
3843 else
3844 {
3845 operand_entry *oe = (*ops)[ranges[i].idx];
3846 stmt = last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id));
3847 if (gimple_code (stmt) != GIMPLE_COND)
3848 continue;
3849 ccode = gimple_cond_code (stmt);
3850 rhs1 = gimple_cond_lhs (stmt);
3851 rhs2 = gimple_cond_rhs (stmt);
3852 }
3853
3854 if (TREE_CODE (rhs1) != SSA_NAME
3855 || rhs2 == NULL_TREE
3856 || TREE_CODE (rhs2) != SSA_NAME)
3857 continue;
3858
3859 switch (ccode)
3860 {
3861 case GT_EXPR:
3862 case GE_EXPR:
3863 case LT_EXPR:
3864 case LE_EXPR:
3865 break;
3866 default:
3867 continue;
3868 }
3869 if (in_p)
3870 ccode = invert_tree_comparison (ccode, false);
3871 switch (ccode)
3872 {
3873 case GT_EXPR:
3874 case GE_EXPR:
3875 std::swap (rhs1, rhs2);
3876 ccode = swap_tree_comparison (ccode);
3877 break;
3878 case LT_EXPR:
3879 case LE_EXPR:
3880 break;
3881 default:
3882 gcc_unreachable ();
3883 }
3884
3885 int *idx = map->get (rhs1);
3886 if (idx == NULL)
3887 continue;
3888
3889 /* maybe_optimize_range_tests allows statements without side-effects
3890 in the basic blocks as long as they are consumed in the same bb.
3891 Make sure rhs2's def stmt is not among them, otherwise we can't
3892 use safely get_nonzero_bits on it. E.g. in:
3893 # RANGE [-83, 1] NONZERO 173
3894 # k_32 = PHI <k_47(13), k_12(9)>
3895 ...
3896 if (k_32 >= 0)
3897 goto <bb 5>; [26.46%]
3898 else
3899 goto <bb 9>; [73.54%]
3900
3901 <bb 5> [local count: 140323371]:
3902 # RANGE [0, 1] NONZERO 1
3903 _5 = (int) k_32;
3904 # RANGE [0, 4] NONZERO 4
3905 _21 = _5 << 2;
3906 # RANGE [0, 4] NONZERO 4
3907 iftmp.0_44 = (char) _21;
3908 if (k_32 < iftmp.0_44)
3909 goto <bb 6>; [84.48%]
3910 else
3911 goto <bb 9>; [15.52%]
3912 the ranges on _5/_21/iftmp.0_44 are flow sensitive, assume that
3913 k_32 >= 0. If we'd optimize k_32 >= 0 to true and k_32 < iftmp.0_44
3914 to (unsigned) k_32 < (unsigned) iftmp.0_44, then we would execute
3915 those stmts even for negative k_32 and the value ranges would be no
3916 longer guaranteed and so the optimization would be invalid. */
3917 while (opcode == ERROR_MARK)
3918 {
3919 gimple *g = SSA_NAME_DEF_STMT (rhs2);
3920 basic_block bb2 = gimple_bb (g);
3921 if (bb2
3922 && bb2 != first_bb
3923 && dominated_by_p (CDI_DOMINATORS, bb2, first_bb))
3924 {
3925 /* As an exception, handle a few common cases. */
3926 if (gimple_assign_cast_p (g)
3927 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (g))))
3928 {
3929 tree op0 = gimple_assign_rhs1 (g);
3930 if (TYPE_UNSIGNED (TREE_TYPE (op0))
3931 && (TYPE_PRECISION (TREE_TYPE (rhs2))
3932 > TYPE_PRECISION (TREE_TYPE (op0))))
3933 /* Zero-extension is always ok. */
3934 break;
3935 else if (TYPE_PRECISION (TREE_TYPE (rhs2))
3936 == TYPE_PRECISION (TREE_TYPE (op0))
3937 && TREE_CODE (op0) == SSA_NAME)
3938 {
3939 /* Cast from signed to unsigned or vice versa. Retry
3940 with the op0 as new rhs2. */
3941 rhs2 = op0;
3942 continue;
3943 }
3944 }
3945 else if (is_gimple_assign (g)
3946 && gimple_assign_rhs_code (g) == BIT_AND_EXPR
3947 && TREE_CODE (gimple_assign_rhs2 (g)) == INTEGER_CST
3948 && !wi::neg_p (wi::to_wide (gimple_assign_rhs2 (g))))
3949 /* Masking with INTEGER_CST with MSB clear is always ok
3950 too. */
3951 break;
3952 rhs2 = NULL_TREE;
3953 }
3954 break;
3955 }
3956 if (rhs2 == NULL_TREE)
3957 continue;
3958
3959 wide_int nz = get_nonzero_bits (rhs2);
3960 if (wi::neg_p (nz))
3961 continue;
3962
3963 /* We have EXP < RHS2 or EXP <= RHS2 where EXP >= 0
3964 and RHS2 is known to be RHS2 >= 0. */
3965 tree utype = unsigned_type_for (TREE_TYPE (rhs1));
3966
3967 enum warn_strict_overflow_code wc = WARN_STRICT_OVERFLOW_COMPARISON;
3968 if ((ranges[*idx].strict_overflow_p
3969 || ranges[i].strict_overflow_p)
3970 && issue_strict_overflow_warning (wc))
3971 warning_at (gimple_location (stmt), OPT_Wstrict_overflow,
3972 "assuming signed overflow does not occur "
3973 "when simplifying range test");
3974
3975 if (dump_file && (dump_flags & TDF_DETAILS))
3976 {
3977 struct range_entry *r = &ranges[*idx];
3978 fprintf (dump_file, "Optimizing range test ");
3979 print_generic_expr (dump_file, r->exp);
3980 fprintf (dump_file, " +[");
3981 print_generic_expr (dump_file, r->low);
3982 fprintf (dump_file, ", ");
3983 print_generic_expr (dump_file, r->high);
3984 fprintf (dump_file, "] and comparison ");
3985 print_generic_expr (dump_file, rhs1);
3986 fprintf (dump_file, " %s ", op_symbol_code (ccode));
3987 print_generic_expr (dump_file, rhs2);
3988 fprintf (dump_file, "\n into (");
3989 print_generic_expr (dump_file, utype);
3990 fprintf (dump_file, ") ");
3991 print_generic_expr (dump_file, rhs1);
3992 fprintf (dump_file, " %s (", op_symbol_code (ccode));
3993 print_generic_expr (dump_file, utype);
3994 fprintf (dump_file, ") ");
3995 print_generic_expr (dump_file, rhs2);
3996 fprintf (dump_file, "\n");
3997 }
3998
3999 operand_entry *oe = (*ops)[ranges[i].idx];
4000 ranges[i].in_p = 0;
4001 if (opcode == BIT_IOR_EXPR
4002 || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
4003 {
4004 ranges[i].in_p = 1;
4005 ccode = invert_tree_comparison (ccode, false);
4006 }
4007
4008 unsigned int uid = gimple_uid (stmt);
4009 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
4010 gimple *g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, rhs1);
4011 gimple_set_uid (g, uid);
4012 rhs1 = gimple_assign_lhs (g);
4013 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4014 if (!useless_type_conversion_p (utype, TREE_TYPE (rhs2)))
4015 {
4016 g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, rhs2);
4017 gimple_set_uid (g, uid);
4018 rhs2 = gimple_assign_lhs (g);
4019 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4020 }
4021 if (tree_swap_operands_p (rhs1, rhs2))
4022 {
4023 std::swap (rhs1, rhs2);
4024 ccode = swap_tree_comparison (ccode);
4025 }
4026 if (gimple_code (stmt) == GIMPLE_COND)
4027 {
4028 gcond *c = as_a <gcond *> (stmt);
4029 gimple_cond_set_code (c, ccode);
4030 gimple_cond_set_lhs (c, rhs1);
4031 gimple_cond_set_rhs (c, rhs2);
4032 update_stmt (stmt);
4033 }
4034 else
4035 {
4036 tree ctype = oe->op ? TREE_TYPE (oe->op) : boolean_type_node;
4037 if (!INTEGRAL_TYPE_P (ctype)
4038 || (TREE_CODE (ctype) != BOOLEAN_TYPE
4039 && TYPE_PRECISION (ctype) != 1))
4040 ctype = boolean_type_node;
4041 g = gimple_build_assign (make_ssa_name (ctype), ccode, rhs1, rhs2);
4042 gimple_set_uid (g, uid);
4043 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4044 if (oe->op && ctype != TREE_TYPE (oe->op))
4045 {
4046 g = gimple_build_assign (make_ssa_name (TREE_TYPE (oe->op)),
4047 NOP_EXPR, gimple_assign_lhs (g));
4048 gimple_set_uid (g, uid);
4049 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4050 }
4051 ranges[i].exp = gimple_assign_lhs (g);
4052 oe->op = ranges[i].exp;
4053 ranges[i].low = build_zero_cst (TREE_TYPE (ranges[i].exp));
4054 ranges[i].high = ranges[i].low;
4055 }
4056 ranges[i].strict_overflow_p = false;
4057 oe = (*ops)[ranges[*idx].idx];
4058 /* Now change all the other range test immediate uses, so that
4059 those tests will be optimized away. */
4060 if (opcode == ERROR_MARK)
4061 {
4062 if (oe->op)
4063 oe->op = build_int_cst (TREE_TYPE (oe->op),
4064 oe->rank == BIT_IOR_EXPR ? 0 : 1);
4065 else
4066 oe->op = (oe->rank == BIT_IOR_EXPR
4067 ? boolean_false_node : boolean_true_node);
4068 }
4069 else
4070 oe->op = error_mark_node;
4071 ranges[*idx].exp = NULL_TREE;
4072 ranges[*idx].low = NULL_TREE;
4073 ranges[*idx].high = NULL_TREE;
4074 any_changes = true;
4075 }
4076
4077 delete map;
4078 return any_changes;
4079 }
4080
4081 /* Optimize range tests, similarly how fold_range_test optimizes
4082 it on trees. The tree code for the binary
4083 operation between all the operands is OPCODE.
4084 If OPCODE is ERROR_MARK, optimize_range_tests is called from within
4085 maybe_optimize_range_tests for inter-bb range optimization.
4086 In that case if oe->op is NULL, oe->id is bb->index whose
4087 GIMPLE_COND is && or ||ed into the test, and oe->rank says
4088 the actual opcode.
4089 FIRST_BB is the first basic block if OPCODE is ERROR_MARK. */
4090
4091 static bool
4092 optimize_range_tests (enum tree_code opcode,
4093 vec<operand_entry *> *ops, basic_block first_bb)
4094 {
4095 unsigned int length = ops->length (), i, j, first;
4096 operand_entry *oe;
4097 struct range_entry *ranges;
4098 bool any_changes = false;
4099
4100 if (length == 1)
4101 return false;
4102
4103 ranges = XNEWVEC (struct range_entry, length);
4104 for (i = 0; i < length; i++)
4105 {
4106 oe = (*ops)[i];
4107 ranges[i].idx = i;
4108 init_range_entry (ranges + i, oe->op,
4109 oe->op
4110 ? NULL
4111 : last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id)));
4112 /* For | invert it now, we will invert it again before emitting
4113 the optimized expression. */
4114 if (opcode == BIT_IOR_EXPR
4115 || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
4116 ranges[i].in_p = !ranges[i].in_p;
4117 }
4118
4119 qsort (ranges, length, sizeof (*ranges), range_entry_cmp);
4120 for (i = 0; i < length; i++)
4121 if (ranges[i].exp != NULL_TREE && TREE_CODE (ranges[i].exp) == SSA_NAME)
4122 break;
4123
4124 /* Try to merge ranges. */
4125 for (first = i; i < length; i++)
4126 {
4127 tree low = ranges[i].low;
4128 tree high = ranges[i].high;
4129 int in_p = ranges[i].in_p;
4130 bool strict_overflow_p = ranges[i].strict_overflow_p;
4131 int update_fail_count = 0;
4132
4133 for (j = i + 1; j < length; j++)
4134 {
4135 if (ranges[i].exp != ranges[j].exp)
4136 break;
4137 if (!merge_ranges (&in_p, &low, &high, in_p, low, high,
4138 ranges[j].in_p, ranges[j].low, ranges[j].high))
4139 break;
4140 strict_overflow_p |= ranges[j].strict_overflow_p;
4141 }
4142
4143 if (j == i + 1)
4144 continue;
4145
4146 if (update_range_test (ranges + i, ranges + i + 1, NULL, j - i - 1,
4147 opcode, ops, ranges[i].exp, NULL, in_p,
4148 low, high, strict_overflow_p))
4149 {
4150 i = j - 1;
4151 any_changes = true;
4152 }
4153 /* Avoid quadratic complexity if all merge_ranges calls would succeed,
4154 while update_range_test would fail. */
4155 else if (update_fail_count == 64)
4156 i = j - 1;
4157 else
4158 ++update_fail_count;
4159 }
4160
4161 any_changes |= optimize_range_tests_1 (opcode, first, length, true,
4162 ops, ranges);
4163
4164 if (BRANCH_COST (optimize_function_for_speed_p (cfun), false) >= 2)
4165 any_changes |= optimize_range_tests_1 (opcode, first, length, false,
4166 ops, ranges);
4167 if (lshift_cheap_p (optimize_function_for_speed_p (cfun)))
4168 any_changes |= optimize_range_tests_to_bit_test (opcode, first, length,
4169 ops, ranges);
4170 any_changes |= optimize_range_tests_var_bound (opcode, first, length, ops,
4171 ranges, first_bb);
4172 any_changes |= optimize_range_tests_cmp_bitwise (opcode, first, length,
4173 ops, ranges);
4174
4175 if (any_changes && opcode != ERROR_MARK)
4176 {
4177 j = 0;
4178 FOR_EACH_VEC_ELT (*ops, i, oe)
4179 {
4180 if (oe->op == error_mark_node)
4181 continue;
4182 else if (i != j)
4183 (*ops)[j] = oe;
4184 j++;
4185 }
4186 ops->truncate (j);
4187 }
4188
4189 XDELETEVEC (ranges);
4190 return any_changes;
4191 }
4192
4193 /* A subroutine of optimize_vec_cond_expr to extract and canonicalize
4194 the operands of the VEC_COND_EXPR. Returns ERROR_MARK on failure,
4195 otherwise the comparison code. TYPE is a return value that is set
4196 to type of comparison. */
4197
4198 static tree_code
4199 ovce_extract_ops (tree var, gassign **rets, bool *reti, tree *type,
4200 tree *lhs, tree *rhs, gassign **vcond)
4201 {
4202 if (TREE_CODE (var) != SSA_NAME)
4203 return ERROR_MARK;
4204
4205 gassign *stmt = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (var));
4206 if (stmt == NULL)
4207 return ERROR_MARK;
4208 if (vcond)
4209 *vcond = stmt;
4210
4211 /* ??? If we start creating more COND_EXPR, we could perform
4212 this same optimization with them. For now, simplify. */
4213 if (gimple_assign_rhs_code (stmt) != VEC_COND_EXPR)
4214 return ERROR_MARK;
4215
4216 tree cond = gimple_assign_rhs1 (stmt);
4217 tree_code cmp = TREE_CODE (cond);
4218 if (cmp != SSA_NAME)
4219 return ERROR_MARK;
4220
4221 gassign *assign = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (cond));
4222 if (assign == NULL
4223 || TREE_CODE_CLASS (gimple_assign_rhs_code (assign)) != tcc_comparison)
4224 return ERROR_MARK;
4225
4226 cmp = gimple_assign_rhs_code (assign);
4227 if (lhs)
4228 *lhs = gimple_assign_rhs1 (assign);
4229 if (rhs)
4230 *rhs = gimple_assign_rhs2 (assign);
4231
4232 /* ??? For now, allow only canonical true and false result vectors.
4233 We could expand this to other constants should the need arise,
4234 but at the moment we don't create them. */
4235 tree t = gimple_assign_rhs2 (stmt);
4236 tree f = gimple_assign_rhs3 (stmt);
4237 bool inv;
4238 if (integer_all_onesp (t))
4239 inv = false;
4240 else if (integer_all_onesp (f))
4241 {
4242 cmp = invert_tree_comparison (cmp, false);
4243 inv = true;
4244 }
4245 else
4246 return ERROR_MARK;
4247 if (!integer_zerop (f))
4248 return ERROR_MARK;
4249
4250 /* Success! */
4251 if (rets)
4252 *rets = assign;
4253 if (reti)
4254 *reti = inv;
4255 if (type)
4256 *type = TREE_TYPE (cond);
4257 return cmp;
4258 }
4259
4260 /* Optimize the condition of VEC_COND_EXPRs which have been combined
4261 with OPCODE (either BIT_AND_EXPR or BIT_IOR_EXPR). */
4262
4263 static bool
4264 optimize_vec_cond_expr (tree_code opcode, vec<operand_entry *> *ops)
4265 {
4266 unsigned int length = ops->length (), i, j;
4267 bool any_changes = false;
4268
4269 if (length == 1)
4270 return false;
4271
4272 for (i = 0; i < length; ++i)
4273 {
4274 tree elt0 = (*ops)[i]->op;
4275
4276 gassign *stmt0, *vcond0;
4277 bool invert;
4278 tree type, lhs0, rhs0;
4279 tree_code cmp0 = ovce_extract_ops (elt0, &stmt0, &invert, &type, &lhs0,
4280 &rhs0, &vcond0);
4281 if (cmp0 == ERROR_MARK)
4282 continue;
4283
4284 for (j = i + 1; j < length; ++j)
4285 {
4286 tree &elt1 = (*ops)[j]->op;
4287
4288 gassign *stmt1, *vcond1;
4289 tree lhs1, rhs1;
4290 tree_code cmp1 = ovce_extract_ops (elt1, &stmt1, NULL, NULL, &lhs1,
4291 &rhs1, &vcond1);
4292 if (cmp1 == ERROR_MARK)
4293 continue;
4294
4295 tree comb;
4296 if (opcode == BIT_AND_EXPR)
4297 comb = maybe_fold_and_comparisons (type, cmp0, lhs0, rhs0,
4298 cmp1, lhs1, rhs1);
4299 else if (opcode == BIT_IOR_EXPR)
4300 comb = maybe_fold_or_comparisons (type, cmp0, lhs0, rhs0,
4301 cmp1, lhs1, rhs1);
4302 else
4303 gcc_unreachable ();
4304 if (comb == NULL)
4305 continue;
4306
4307 /* Success! */
4308 if (dump_file && (dump_flags & TDF_DETAILS))
4309 {
4310 fprintf (dump_file, "Transforming ");
4311 print_generic_expr (dump_file, gimple_assign_lhs (stmt0));
4312 fprintf (dump_file, " %c ", opcode == BIT_AND_EXPR ? '&' : '|');
4313 print_generic_expr (dump_file, gimple_assign_lhs (stmt1));
4314 fprintf (dump_file, " into ");
4315 print_generic_expr (dump_file, comb);
4316 fputc ('\n', dump_file);
4317 }
4318
4319 gimple_stmt_iterator gsi = gsi_for_stmt (vcond0);
4320 tree exp = force_gimple_operand_gsi (&gsi, comb, true, NULL_TREE,
4321 true, GSI_SAME_STMT);
4322 if (invert)
4323 swap_ssa_operands (vcond0, gimple_assign_rhs2_ptr (vcond0),
4324 gimple_assign_rhs3_ptr (vcond0));
4325 gimple_assign_set_rhs1 (vcond0, exp);
4326 update_stmt (vcond0);
4327
4328 elt1 = error_mark_node;
4329 any_changes = true;
4330 }
4331 }
4332
4333 if (any_changes)
4334 {
4335 operand_entry *oe;
4336 j = 0;
4337 FOR_EACH_VEC_ELT (*ops, i, oe)
4338 {
4339 if (oe->op == error_mark_node)
4340 continue;
4341 else if (i != j)
4342 (*ops)[j] = oe;
4343 j++;
4344 }
4345 ops->truncate (j);
4346 }
4347
4348 return any_changes;
4349 }
4350
4351 /* Return true if STMT is a cast like:
4352 <bb N>:
4353 ...
4354 _123 = (int) _234;
4355
4356 <bb M>:
4357 # _345 = PHI <_123(N), 1(...), 1(...)>
4358 where _234 has bool type, _123 has single use and
4359 bb N has a single successor M. This is commonly used in
4360 the last block of a range test.
4361
4362 Also Return true if STMT is tcc_compare like:
4363 <bb N>:
4364 ...
4365 _234 = a_2(D) == 2;
4366
4367 <bb M>:
4368 # _345 = PHI <_234(N), 1(...), 1(...)>
4369 _346 = (int) _345;
4370 where _234 has booltype, single use and
4371 bb N has a single successor M. This is commonly used in
4372 the last block of a range test. */
4373
4374 static bool
4375 final_range_test_p (gimple *stmt)
4376 {
4377 basic_block bb, rhs_bb, lhs_bb;
4378 edge e;
4379 tree lhs, rhs;
4380 use_operand_p use_p;
4381 gimple *use_stmt;
4382
4383 if (!gimple_assign_cast_p (stmt)
4384 && (!is_gimple_assign (stmt)
4385 || (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
4386 != tcc_comparison)))
4387 return false;
4388 bb = gimple_bb (stmt);
4389 if (!single_succ_p (bb))
4390 return false;
4391 e = single_succ_edge (bb);
4392 if (e->flags & EDGE_COMPLEX)
4393 return false;
4394
4395 lhs = gimple_assign_lhs (stmt);
4396 rhs = gimple_assign_rhs1 (stmt);
4397 if (gimple_assign_cast_p (stmt)
4398 && (!INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4399 || TREE_CODE (rhs) != SSA_NAME
4400 || TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE))
4401 return false;
4402
4403 if (!gimple_assign_cast_p (stmt)
4404 && (TREE_CODE (TREE_TYPE (lhs)) != BOOLEAN_TYPE))
4405 return false;
4406
4407 /* Test whether lhs is consumed only by a PHI in the only successor bb. */
4408 if (!single_imm_use (lhs, &use_p, &use_stmt))
4409 return false;
4410
4411 if (gimple_code (use_stmt) != GIMPLE_PHI
4412 || gimple_bb (use_stmt) != e->dest)
4413 return false;
4414
4415 /* And that the rhs is defined in the same loop. */
4416 if (gimple_assign_cast_p (stmt))
4417 {
4418 if (TREE_CODE (rhs) != SSA_NAME
4419 || !(rhs_bb = gimple_bb (SSA_NAME_DEF_STMT (rhs)))
4420 || !flow_bb_inside_loop_p (loop_containing_stmt (stmt), rhs_bb))
4421 return false;
4422 }
4423 else
4424 {
4425 if (TREE_CODE (lhs) != SSA_NAME
4426 || !(lhs_bb = gimple_bb (SSA_NAME_DEF_STMT (lhs)))
4427 || !flow_bb_inside_loop_p (loop_containing_stmt (stmt), lhs_bb))
4428 return false;
4429 }
4430
4431 return true;
4432 }
4433
4434 /* Return true if BB is suitable basic block for inter-bb range test
4435 optimization. If BACKWARD is true, BB should be the only predecessor
4436 of TEST_BB, and *OTHER_BB is either NULL and filled by the routine,
4437 or compared with to find a common basic block to which all conditions
4438 branch to if true resp. false. If BACKWARD is false, TEST_BB should
4439 be the only predecessor of BB. *TEST_SWAPPED_P is set to true if
4440 TEST_BB is a bb ending in condition where the edge to non-*OTHER_BB
4441 block points to an empty block that falls through into *OTHER_BB and
4442 the phi args match that path. */
4443
4444 static bool
4445 suitable_cond_bb (basic_block bb, basic_block test_bb, basic_block *other_bb,
4446 bool *test_swapped_p, bool backward)
4447 {
4448 edge_iterator ei, ei2;
4449 edge e, e2;
4450 gimple *stmt;
4451 gphi_iterator gsi;
4452 bool other_edge_seen = false;
4453 bool is_cond;
4454
4455 if (test_bb == bb)
4456 return false;
4457 /* Check last stmt first. */
4458 stmt = last_nondebug_stmt (bb);
4459 if (stmt == NULL
4460 || (gimple_code (stmt) != GIMPLE_COND
4461 && (backward || !final_range_test_p (stmt)))
4462 || gimple_visited_p (stmt)
4463 || stmt_could_throw_p (cfun, stmt)
4464 || *other_bb == bb)
4465 return false;
4466 is_cond = gimple_code (stmt) == GIMPLE_COND;
4467 if (is_cond)
4468 {
4469 /* If last stmt is GIMPLE_COND, verify that one of the succ edges
4470 goes to the next bb (if BACKWARD, it is TEST_BB), and the other
4471 to *OTHER_BB (if not set yet, try to find it out). */
4472 if (EDGE_COUNT (bb->succs) != 2)
4473 return false;
4474 FOR_EACH_EDGE (e, ei, bb->succs)
4475 {
4476 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
4477 return false;
4478 if (e->dest == test_bb)
4479 {
4480 if (backward)
4481 continue;
4482 else
4483 return false;
4484 }
4485 if (e->dest == bb)
4486 return false;
4487 if (*other_bb == NULL)
4488 {
4489 FOR_EACH_EDGE (e2, ei2, test_bb->succs)
4490 if (!(e2->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
4491 return false;
4492 else if (e->dest == e2->dest)
4493 *other_bb = e->dest;
4494 if (*other_bb == NULL)
4495 return false;
4496 }
4497 if (e->dest == *other_bb)
4498 other_edge_seen = true;
4499 else if (backward)
4500 return false;
4501 }
4502 if (*other_bb == NULL || !other_edge_seen)
4503 return false;
4504 }
4505 else if (single_succ (bb) != *other_bb)
4506 return false;
4507
4508 /* Now check all PHIs of *OTHER_BB. */
4509 e = find_edge (bb, *other_bb);
4510 e2 = find_edge (test_bb, *other_bb);
4511 retry:;
4512 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4513 {
4514 gphi *phi = gsi.phi ();
4515 /* If both BB and TEST_BB end with GIMPLE_COND, all PHI arguments
4516 corresponding to BB and TEST_BB predecessor must be the same. */
4517 if (!operand_equal_p (gimple_phi_arg_def (phi, e->dest_idx),
4518 gimple_phi_arg_def (phi, e2->dest_idx), 0))
4519 {
4520 /* Otherwise, if one of the blocks doesn't end with GIMPLE_COND,
4521 one of the PHIs should have the lhs of the last stmt in
4522 that block as PHI arg and that PHI should have 0 or 1
4523 corresponding to it in all other range test basic blocks
4524 considered. */
4525 if (!is_cond)
4526 {
4527 if (gimple_phi_arg_def (phi, e->dest_idx)
4528 == gimple_assign_lhs (stmt)
4529 && (integer_zerop (gimple_phi_arg_def (phi, e2->dest_idx))
4530 || integer_onep (gimple_phi_arg_def (phi,
4531 e2->dest_idx))))
4532 continue;
4533 }
4534 else
4535 {
4536 gimple *test_last = last_nondebug_stmt (test_bb);
4537 if (gimple_code (test_last) == GIMPLE_COND)
4538 {
4539 if (backward ? e2->src != test_bb : e->src != bb)
4540 return false;
4541
4542 /* For last_bb, handle also:
4543 if (x_3(D) == 3)
4544 goto <bb 6>; [34.00%]
4545 else
4546 goto <bb 7>; [66.00%]
4547
4548 <bb 6> [local count: 79512730]:
4549
4550 <bb 7> [local count: 1073741824]:
4551 # prephitmp_7 = PHI <1(3), 1(4), 0(5), 1(2), 1(6)>
4552 where bb 7 is *OTHER_BB, but the PHI values from the
4553 earlier bbs match the path through the empty bb
4554 in between. */
4555 edge e3;
4556 if (backward)
4557 e3 = EDGE_SUCC (test_bb,
4558 e2 == EDGE_SUCC (test_bb, 0) ? 1 : 0);
4559 else
4560 e3 = EDGE_SUCC (bb,
4561 e == EDGE_SUCC (bb, 0) ? 1 : 0);
4562 if (empty_block_p (e3->dest)
4563 && single_succ_p (e3->dest)
4564 && single_succ (e3->dest) == *other_bb
4565 && single_pred_p (e3->dest)
4566 && single_succ_edge (e3->dest)->flags == EDGE_FALLTHRU)
4567 {
4568 if (backward)
4569 e2 = single_succ_edge (e3->dest);
4570 else
4571 e = single_succ_edge (e3->dest);
4572 if (test_swapped_p)
4573 *test_swapped_p = true;
4574 goto retry;
4575 }
4576 }
4577 else if (gimple_phi_arg_def (phi, e2->dest_idx)
4578 == gimple_assign_lhs (test_last)
4579 && (integer_zerop (gimple_phi_arg_def (phi,
4580 e->dest_idx))
4581 || integer_onep (gimple_phi_arg_def (phi,
4582 e->dest_idx))))
4583 continue;
4584 }
4585
4586 return false;
4587 }
4588 }
4589 return true;
4590 }
4591
4592 /* Return true if BB doesn't have side-effects that would disallow
4593 range test optimization, all SSA_NAMEs set in the bb are consumed
4594 in the bb and there are no PHIs. */
4595
4596 bool
4597 no_side_effect_bb (basic_block bb)
4598 {
4599 gimple_stmt_iterator gsi;
4600 gimple *last;
4601
4602 if (!gimple_seq_empty_p (phi_nodes (bb)))
4603 return false;
4604 last = last_nondebug_stmt (bb);
4605 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4606 {
4607 gimple *stmt = gsi_stmt (gsi);
4608 tree lhs;
4609 imm_use_iterator imm_iter;
4610 use_operand_p use_p;
4611
4612 if (is_gimple_debug (stmt))
4613 continue;
4614 if (gimple_has_side_effects (stmt))
4615 return false;
4616 if (stmt == last)
4617 return true;
4618 if (!is_gimple_assign (stmt))
4619 return false;
4620 lhs = gimple_assign_lhs (stmt);
4621 if (TREE_CODE (lhs) != SSA_NAME)
4622 return false;
4623 if (gimple_assign_rhs_could_trap_p (stmt))
4624 return false;
4625 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
4626 {
4627 gimple *use_stmt = USE_STMT (use_p);
4628 if (is_gimple_debug (use_stmt))
4629 continue;
4630 if (gimple_bb (use_stmt) != bb)
4631 return false;
4632 }
4633 }
4634 return false;
4635 }
4636
4637 /* If VAR is set by CODE (BIT_{AND,IOR}_EXPR) which is reassociable,
4638 return true and fill in *OPS recursively. */
4639
4640 static bool
4641 get_ops (tree var, enum tree_code code, vec<operand_entry *> *ops,
4642 class loop *loop)
4643 {
4644 gimple *stmt = SSA_NAME_DEF_STMT (var);
4645 tree rhs[2];
4646 int i;
4647
4648 if (!is_reassociable_op (stmt, code, loop))
4649 return false;
4650
4651 rhs[0] = gimple_assign_rhs1 (stmt);
4652 rhs[1] = gimple_assign_rhs2 (stmt);
4653 gimple_set_visited (stmt, true);
4654 for (i = 0; i < 2; i++)
4655 if (TREE_CODE (rhs[i]) == SSA_NAME
4656 && !get_ops (rhs[i], code, ops, loop)
4657 && has_single_use (rhs[i]))
4658 {
4659 operand_entry *oe = operand_entry_pool.allocate ();
4660
4661 oe->op = rhs[i];
4662 oe->rank = code;
4663 oe->id = 0;
4664 oe->count = 1;
4665 oe->stmt_to_insert = NULL;
4666 ops->safe_push (oe);
4667 }
4668 return true;
4669 }
4670
4671 /* Find the ops that were added by get_ops starting from VAR, see if
4672 they were changed during update_range_test and if yes, create new
4673 stmts. */
4674
4675 static tree
4676 update_ops (tree var, enum tree_code code, const vec<operand_entry *> &ops,
4677 unsigned int *pidx, class loop *loop)
4678 {
4679 gimple *stmt = SSA_NAME_DEF_STMT (var);
4680 tree rhs[4];
4681 int i;
4682
4683 if (!is_reassociable_op (stmt, code, loop))
4684 return NULL;
4685
4686 rhs[0] = gimple_assign_rhs1 (stmt);
4687 rhs[1] = gimple_assign_rhs2 (stmt);
4688 rhs[2] = rhs[0];
4689 rhs[3] = rhs[1];
4690 for (i = 0; i < 2; i++)
4691 if (TREE_CODE (rhs[i]) == SSA_NAME)
4692 {
4693 rhs[2 + i] = update_ops (rhs[i], code, ops, pidx, loop);
4694 if (rhs[2 + i] == NULL_TREE)
4695 {
4696 if (has_single_use (rhs[i]))
4697 rhs[2 + i] = ops[(*pidx)++]->op;
4698 else
4699 rhs[2 + i] = rhs[i];
4700 }
4701 }
4702 if ((rhs[2] != rhs[0] || rhs[3] != rhs[1])
4703 && (rhs[2] != rhs[1] || rhs[3] != rhs[0]))
4704 {
4705 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
4706 var = make_ssa_name (TREE_TYPE (var));
4707 gassign *g = gimple_build_assign (var, gimple_assign_rhs_code (stmt),
4708 rhs[2], rhs[3]);
4709 gimple_set_uid (g, gimple_uid (stmt));
4710 gimple_set_visited (g, true);
4711 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4712 gimple_stmt_iterator gsi2 = gsi_for_stmt (g);
4713 if (fold_stmt_inplace (&gsi2))
4714 update_stmt (g);
4715 }
4716 return var;
4717 }
4718
4719 /* Structure to track the initial value passed to get_ops and
4720 the range in the ops vector for each basic block. */
4721
4722 struct inter_bb_range_test_entry
4723 {
4724 tree op;
4725 unsigned int first_idx, last_idx;
4726 };
4727
4728 /* Inter-bb range test optimization.
4729
4730 Returns TRUE if a gimple conditional is optimized to a true/false,
4731 otherwise return FALSE.
4732
4733 This indicates to the caller that it should run a CFG cleanup pass
4734 once reassociation is completed. */
4735
4736 static bool
4737 maybe_optimize_range_tests (gimple *stmt)
4738 {
4739 basic_block first_bb = gimple_bb (stmt);
4740 basic_block last_bb = first_bb;
4741 basic_block other_bb = NULL;
4742 basic_block bb;
4743 edge_iterator ei;
4744 edge e;
4745 auto_vec<operand_entry *> ops;
4746 auto_vec<inter_bb_range_test_entry> bbinfo;
4747 bool any_changes = false;
4748 bool cfg_cleanup_needed = false;
4749
4750 /* Consider only basic blocks that end with GIMPLE_COND or
4751 a cast statement satisfying final_range_test_p. All
4752 but the last bb in the first_bb .. last_bb range
4753 should end with GIMPLE_COND. */
4754 if (gimple_code (stmt) == GIMPLE_COND)
4755 {
4756 if (EDGE_COUNT (first_bb->succs) != 2)
4757 return cfg_cleanup_needed;
4758 }
4759 else if (final_range_test_p (stmt))
4760 other_bb = single_succ (first_bb);
4761 else
4762 return cfg_cleanup_needed;
4763
4764 if (stmt_could_throw_p (cfun, stmt))
4765 return cfg_cleanup_needed;
4766
4767 /* As relative ordering of post-dominator sons isn't fixed,
4768 maybe_optimize_range_tests can be called first on any
4769 bb in the range we want to optimize. So, start searching
4770 backwards, if first_bb can be set to a predecessor. */
4771 while (single_pred_p (first_bb))
4772 {
4773 basic_block pred_bb = single_pred (first_bb);
4774 if (!suitable_cond_bb (pred_bb, first_bb, &other_bb, NULL, true))
4775 break;
4776 if (!no_side_effect_bb (first_bb))
4777 break;
4778 first_bb = pred_bb;
4779 }
4780 /* If first_bb is last_bb, other_bb hasn't been computed yet.
4781 Before starting forward search in last_bb successors, find
4782 out the other_bb. */
4783 if (first_bb == last_bb)
4784 {
4785 other_bb = NULL;
4786 /* As non-GIMPLE_COND last stmt always terminates the range,
4787 if forward search didn't discover anything, just give up. */
4788 if (gimple_code (stmt) != GIMPLE_COND)
4789 return cfg_cleanup_needed;
4790 /* Look at both successors. Either it ends with a GIMPLE_COND
4791 and satisfies suitable_cond_bb, or ends with a cast and
4792 other_bb is that cast's successor. */
4793 FOR_EACH_EDGE (e, ei, first_bb->succs)
4794 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))
4795 || e->dest == first_bb)
4796 return cfg_cleanup_needed;
4797 else if (single_pred_p (e->dest))
4798 {
4799 stmt = last_nondebug_stmt (e->dest);
4800 if (stmt
4801 && gimple_code (stmt) == GIMPLE_COND
4802 && EDGE_COUNT (e->dest->succs) == 2)
4803 {
4804 if (suitable_cond_bb (first_bb, e->dest, &other_bb,
4805 NULL, true))
4806 break;
4807 else
4808 other_bb = NULL;
4809 }
4810 else if (stmt
4811 && final_range_test_p (stmt)
4812 && find_edge (first_bb, single_succ (e->dest)))
4813 {
4814 other_bb = single_succ (e->dest);
4815 if (other_bb == first_bb)
4816 other_bb = NULL;
4817 }
4818 }
4819 if (other_bb == NULL)
4820 return cfg_cleanup_needed;
4821 }
4822 /* Now do the forward search, moving last_bb to successor bbs
4823 that aren't other_bb. */
4824 while (EDGE_COUNT (last_bb->succs) == 2)
4825 {
4826 FOR_EACH_EDGE (e, ei, last_bb->succs)
4827 if (e->dest != other_bb)
4828 break;
4829 if (e == NULL)
4830 break;
4831 if (!single_pred_p (e->dest))
4832 break;
4833 if (!suitable_cond_bb (e->dest, last_bb, &other_bb, NULL, false))
4834 break;
4835 if (!no_side_effect_bb (e->dest))
4836 break;
4837 last_bb = e->dest;
4838 }
4839 if (first_bb == last_bb)
4840 return cfg_cleanup_needed;
4841 /* Here basic blocks first_bb through last_bb's predecessor
4842 end with GIMPLE_COND, all of them have one of the edges to
4843 other_bb and another to another block in the range,
4844 all blocks except first_bb don't have side-effects and
4845 last_bb ends with either GIMPLE_COND, or cast satisfying
4846 final_range_test_p. */
4847 for (bb = last_bb; ; bb = single_pred (bb))
4848 {
4849 enum tree_code code;
4850 tree lhs, rhs;
4851 inter_bb_range_test_entry bb_ent;
4852
4853 bb_ent.op = NULL_TREE;
4854 bb_ent.first_idx = ops.length ();
4855 bb_ent.last_idx = bb_ent.first_idx;
4856 e = find_edge (bb, other_bb);
4857 stmt = last_nondebug_stmt (bb);
4858 gimple_set_visited (stmt, true);
4859 if (gimple_code (stmt) != GIMPLE_COND)
4860 {
4861 use_operand_p use_p;
4862 gimple *phi;
4863 edge e2;
4864 unsigned int d;
4865
4866 lhs = gimple_assign_lhs (stmt);
4867 rhs = gimple_assign_rhs1 (stmt);
4868 gcc_assert (bb == last_bb);
4869
4870 /* stmt is
4871 _123 = (int) _234;
4872 OR
4873 _234 = a_2(D) == 2;
4874
4875 followed by:
4876 <bb M>:
4877 # _345 = PHI <_123(N), 1(...), 1(...)>
4878
4879 or 0 instead of 1. If it is 0, the _234
4880 range test is anded together with all the
4881 other range tests, if it is 1, it is ored with
4882 them. */
4883 single_imm_use (lhs, &use_p, &phi);
4884 gcc_assert (gimple_code (phi) == GIMPLE_PHI);
4885 e2 = find_edge (first_bb, other_bb);
4886 d = e2->dest_idx;
4887 gcc_assert (gimple_phi_arg_def (phi, e->dest_idx) == lhs);
4888 if (integer_zerop (gimple_phi_arg_def (phi, d)))
4889 code = BIT_AND_EXPR;
4890 else
4891 {
4892 gcc_checking_assert (integer_onep (gimple_phi_arg_def (phi, d)));
4893 code = BIT_IOR_EXPR;
4894 }
4895
4896 /* If _234 SSA_NAME_DEF_STMT is
4897 _234 = _567 | _789;
4898 (or &, corresponding to 1/0 in the phi arguments,
4899 push into ops the individual range test arguments
4900 of the bitwise or resp. and, recursively. */
4901 if (TREE_CODE (rhs) == SSA_NAME
4902 && (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
4903 != tcc_comparison)
4904 && !get_ops (rhs, code, &ops,
4905 loop_containing_stmt (stmt))
4906 && has_single_use (rhs))
4907 {
4908 /* Otherwise, push the _234 range test itself. */
4909 operand_entry *oe = operand_entry_pool.allocate ();
4910
4911 oe->op = rhs;
4912 oe->rank = code;
4913 oe->id = 0;
4914 oe->count = 1;
4915 oe->stmt_to_insert = NULL;
4916 ops.safe_push (oe);
4917 bb_ent.last_idx++;
4918 bb_ent.op = rhs;
4919 }
4920 else if (is_gimple_assign (stmt)
4921 && (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
4922 == tcc_comparison)
4923 && !get_ops (lhs, code, &ops,
4924 loop_containing_stmt (stmt))
4925 && has_single_use (lhs))
4926 {
4927 operand_entry *oe = operand_entry_pool.allocate ();
4928 oe->op = lhs;
4929 oe->rank = code;
4930 oe->id = 0;
4931 oe->count = 1;
4932 ops.safe_push (oe);
4933 bb_ent.last_idx++;
4934 bb_ent.op = lhs;
4935 }
4936 else
4937 {
4938 bb_ent.last_idx = ops.length ();
4939 bb_ent.op = rhs;
4940 }
4941 bbinfo.safe_push (bb_ent);
4942 for (unsigned int i = bb_ent.first_idx; i < bb_ent.last_idx; ++i)
4943 ops[i]->id = bb->index;
4944 continue;
4945 }
4946 else if (bb == last_bb)
4947 {
4948 /* For last_bb, handle also:
4949 if (x_3(D) == 3)
4950 goto <bb 6>; [34.00%]
4951 else
4952 goto <bb 7>; [66.00%]
4953
4954 <bb 6> [local count: 79512730]:
4955
4956 <bb 7> [local count: 1073741824]:
4957 # prephitmp_7 = PHI <1(3), 1(4), 0(5), 1(2), 1(6)>
4958 where bb 7 is OTHER_BB, but the PHI values from the
4959 earlier bbs match the path through the empty bb
4960 in between. */
4961 bool test_swapped_p = false;
4962 bool ok = suitable_cond_bb (single_pred (last_bb), last_bb,
4963 &other_bb, &test_swapped_p, true);
4964 gcc_assert (ok);
4965 if (test_swapped_p)
4966 e = EDGE_SUCC (bb, e == EDGE_SUCC (bb, 0) ? 1 : 0);
4967 }
4968 /* Otherwise stmt is GIMPLE_COND. */
4969 code = gimple_cond_code (stmt);
4970 lhs = gimple_cond_lhs (stmt);
4971 rhs = gimple_cond_rhs (stmt);
4972 if (TREE_CODE (lhs) == SSA_NAME
4973 && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4974 && ((code != EQ_EXPR && code != NE_EXPR)
4975 || rhs != boolean_false_node
4976 /* Either push into ops the individual bitwise
4977 or resp. and operands, depending on which
4978 edge is other_bb. */
4979 || !get_ops (lhs, (((e->flags & EDGE_TRUE_VALUE) == 0)
4980 ^ (code == EQ_EXPR))
4981 ? BIT_AND_EXPR : BIT_IOR_EXPR, &ops,
4982 loop_containing_stmt (stmt))))
4983 {
4984 /* Or push the GIMPLE_COND stmt itself. */
4985 operand_entry *oe = operand_entry_pool.allocate ();
4986
4987 oe->op = NULL;
4988 oe->rank = (e->flags & EDGE_TRUE_VALUE)
4989 ? BIT_IOR_EXPR : BIT_AND_EXPR;
4990 /* oe->op = NULL signs that there is no SSA_NAME
4991 for the range test, and oe->id instead is the
4992 basic block number, at which's end the GIMPLE_COND
4993 is. */
4994 oe->id = bb->index;
4995 oe->count = 1;
4996 oe->stmt_to_insert = NULL;
4997 ops.safe_push (oe);
4998 bb_ent.op = NULL;
4999 bb_ent.last_idx++;
5000 }
5001 else if (ops.length () > bb_ent.first_idx)
5002 {
5003 bb_ent.op = lhs;
5004 bb_ent.last_idx = ops.length ();
5005 }
5006 bbinfo.safe_push (bb_ent);
5007 for (unsigned int i = bb_ent.first_idx; i < bb_ent.last_idx; ++i)
5008 ops[i]->id = bb->index;
5009 if (bb == first_bb)
5010 break;
5011 }
5012 if (ops.length () > 1)
5013 any_changes = optimize_range_tests (ERROR_MARK, &ops, first_bb);
5014 if (any_changes)
5015 {
5016 unsigned int idx, max_idx = 0;
5017 /* update_ops relies on has_single_use predicates returning the
5018 same values as it did during get_ops earlier. Additionally it
5019 never removes statements, only adds new ones and it should walk
5020 from the single imm use and check the predicate already before
5021 making those changes.
5022 On the other side, the handling of GIMPLE_COND directly can turn
5023 previously multiply used SSA_NAMEs into single use SSA_NAMEs, so
5024 it needs to be done in a separate loop afterwards. */
5025 for (bb = last_bb, idx = 0; ; bb = single_pred (bb), idx++)
5026 {
5027 if (bbinfo[idx].first_idx < bbinfo[idx].last_idx
5028 && bbinfo[idx].op != NULL_TREE)
5029 {
5030 tree new_op;
5031
5032 max_idx = idx;
5033 stmt = last_nondebug_stmt (bb);
5034 new_op = update_ops (bbinfo[idx].op,
5035 (enum tree_code)
5036 ops[bbinfo[idx].first_idx]->rank,
5037 ops, &bbinfo[idx].first_idx,
5038 loop_containing_stmt (stmt));
5039 if (new_op == NULL_TREE)
5040 {
5041 gcc_assert (bb == last_bb);
5042 new_op = ops[bbinfo[idx].first_idx++]->op;
5043 }
5044 if (bbinfo[idx].op != new_op)
5045 {
5046 imm_use_iterator iter;
5047 use_operand_p use_p;
5048 gimple *use_stmt, *cast_or_tcc_cmp_stmt = NULL;
5049
5050 FOR_EACH_IMM_USE_STMT (use_stmt, iter, bbinfo[idx].op)
5051 if (is_gimple_debug (use_stmt))
5052 continue;
5053 else if (gimple_code (use_stmt) == GIMPLE_COND
5054 || gimple_code (use_stmt) == GIMPLE_PHI)
5055 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5056 SET_USE (use_p, new_op);
5057 else if ((is_gimple_assign (use_stmt)
5058 && (TREE_CODE_CLASS
5059 (gimple_assign_rhs_code (use_stmt))
5060 == tcc_comparison)))
5061 cast_or_tcc_cmp_stmt = use_stmt;
5062 else if (gimple_assign_cast_p (use_stmt))
5063 cast_or_tcc_cmp_stmt = use_stmt;
5064 else
5065 gcc_unreachable ();
5066
5067 if (cast_or_tcc_cmp_stmt)
5068 {
5069 gcc_assert (bb == last_bb);
5070 tree lhs = gimple_assign_lhs (cast_or_tcc_cmp_stmt);
5071 tree new_lhs = make_ssa_name (TREE_TYPE (lhs));
5072 enum tree_code rhs_code
5073 = gimple_assign_cast_p (cast_or_tcc_cmp_stmt)
5074 ? gimple_assign_rhs_code (cast_or_tcc_cmp_stmt)
5075 : CONVERT_EXPR;
5076 gassign *g;
5077 if (is_gimple_min_invariant (new_op))
5078 {
5079 new_op = fold_convert (TREE_TYPE (lhs), new_op);
5080 g = gimple_build_assign (new_lhs, new_op);
5081 }
5082 else
5083 g = gimple_build_assign (new_lhs, rhs_code, new_op);
5084 gimple_stmt_iterator gsi
5085 = gsi_for_stmt (cast_or_tcc_cmp_stmt);
5086 gimple_set_uid (g, gimple_uid (cast_or_tcc_cmp_stmt));
5087 gimple_set_visited (g, true);
5088 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
5089 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
5090 if (is_gimple_debug (use_stmt))
5091 continue;
5092 else if (gimple_code (use_stmt) == GIMPLE_COND
5093 || gimple_code (use_stmt) == GIMPLE_PHI)
5094 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
5095 SET_USE (use_p, new_lhs);
5096 else
5097 gcc_unreachable ();
5098 }
5099 }
5100 }
5101 if (bb == first_bb)
5102 break;
5103 }
5104 for (bb = last_bb, idx = 0; ; bb = single_pred (bb), idx++)
5105 {
5106 if (bbinfo[idx].first_idx < bbinfo[idx].last_idx
5107 && bbinfo[idx].op == NULL_TREE
5108 && ops[bbinfo[idx].first_idx]->op != NULL_TREE)
5109 {
5110 gcond *cond_stmt = as_a <gcond *> (*gsi_last_bb (bb));
5111
5112 if (idx > max_idx)
5113 max_idx = idx;
5114
5115 /* If we collapse the conditional to a true/false
5116 condition, then bubble that knowledge up to our caller. */
5117 if (integer_zerop (ops[bbinfo[idx].first_idx]->op))
5118 {
5119 gimple_cond_make_false (cond_stmt);
5120 cfg_cleanup_needed = true;
5121 }
5122 else if (integer_onep (ops[bbinfo[idx].first_idx]->op))
5123 {
5124 gimple_cond_make_true (cond_stmt);
5125 cfg_cleanup_needed = true;
5126 }
5127 else
5128 {
5129 gimple_cond_set_code (cond_stmt, NE_EXPR);
5130 gimple_cond_set_lhs (cond_stmt,
5131 ops[bbinfo[idx].first_idx]->op);
5132 gimple_cond_set_rhs (cond_stmt, boolean_false_node);
5133 }
5134 update_stmt (cond_stmt);
5135 }
5136 if (bb == first_bb)
5137 break;
5138 }
5139
5140 /* The above changes could result in basic blocks after the first
5141 modified one, up to and including last_bb, to be executed even if
5142 they would not be in the original program. If the value ranges of
5143 assignment lhs' in those bbs were dependent on the conditions
5144 guarding those basic blocks which now can change, the VRs might
5145 be incorrect. As no_side_effect_bb should ensure those SSA_NAMEs
5146 are only used within the same bb, it should be not a big deal if
5147 we just reset all the VRs in those bbs. See PR68671. */
5148 for (bb = last_bb, idx = 0; idx < max_idx; bb = single_pred (bb), idx++)
5149 reset_flow_sensitive_info_in_bb (bb);
5150 }
5151 return cfg_cleanup_needed;
5152 }
5153
5154 /* Remove def stmt of VAR if VAR has zero uses and recurse
5155 on rhs1 operand if so. */
5156
5157 static void
5158 remove_visited_stmt_chain (tree var)
5159 {
5160 gimple *stmt;
5161 gimple_stmt_iterator gsi;
5162
5163 while (1)
5164 {
5165 if (TREE_CODE (var) != SSA_NAME || !has_zero_uses (var))
5166 return;
5167 stmt = SSA_NAME_DEF_STMT (var);
5168 if (is_gimple_assign (stmt) && gimple_visited_p (stmt))
5169 {
5170 var = gimple_assign_rhs1 (stmt);
5171 gsi = gsi_for_stmt (stmt);
5172 reassoc_remove_stmt (&gsi);
5173 release_defs (stmt);
5174 }
5175 else
5176 return;
5177 }
5178 }
5179
5180 /* This function checks three consequtive operands in
5181 passed operands vector OPS starting from OPINDEX and
5182 swaps two operands if it is profitable for binary operation
5183 consuming OPINDEX + 1 abnd OPINDEX + 2 operands.
5184
5185 We pair ops with the same rank if possible. */
5186
5187 static void
5188 swap_ops_for_binary_stmt (const vec<operand_entry *> &ops,
5189 unsigned int opindex)
5190 {
5191 operand_entry *oe1, *oe2, *oe3;
5192
5193 oe1 = ops[opindex];
5194 oe2 = ops[opindex + 1];
5195 oe3 = ops[opindex + 2];
5196
5197 if (oe1->rank == oe2->rank && oe2->rank != oe3->rank)
5198 std::swap (*oe1, *oe3);
5199 else if (oe1->rank == oe3->rank && oe2->rank != oe3->rank)
5200 std::swap (*oe1, *oe2);
5201 }
5202
5203 /* If definition of RHS1 or RHS2 dominates STMT, return the later of those
5204 two definitions, otherwise return STMT. Sets INSERT_BEFORE to indicate
5205 whether RHS1 op RHS2 can be inserted before or needs to be inserted
5206 after the returned stmt. */
5207
5208 static inline gimple *
5209 find_insert_point (gimple *stmt, tree rhs1, tree rhs2, bool &insert_before)
5210 {
5211 insert_before = true;
5212 if (TREE_CODE (rhs1) == SSA_NAME
5213 && reassoc_stmt_dominates_stmt_p (stmt, SSA_NAME_DEF_STMT (rhs1)))
5214 {
5215 stmt = SSA_NAME_DEF_STMT (rhs1);
5216 insert_before = false;
5217 }
5218 if (TREE_CODE (rhs2) == SSA_NAME
5219 && reassoc_stmt_dominates_stmt_p (stmt, SSA_NAME_DEF_STMT (rhs2)))
5220 {
5221 stmt = SSA_NAME_DEF_STMT (rhs2);
5222 insert_before = false;
5223 }
5224 return stmt;
5225 }
5226
5227 /* If the stmt that defines operand has to be inserted, insert it
5228 before the use. */
5229 static void
5230 insert_stmt_before_use (gimple *stmt, gimple *stmt_to_insert)
5231 {
5232 gcc_assert (is_gimple_assign (stmt_to_insert));
5233 tree rhs1 = gimple_assign_rhs1 (stmt_to_insert);
5234 tree rhs2 = gimple_assign_rhs2 (stmt_to_insert);
5235 bool insert_before;
5236 gimple *insert_point = find_insert_point (stmt, rhs1, rhs2, insert_before);
5237 gimple_stmt_iterator gsi = gsi_for_stmt (insert_point);
5238 gimple_set_uid (stmt_to_insert, gimple_uid (insert_point));
5239
5240 /* If the insert point is not stmt, then insert_point would be
5241 the point where operand rhs1 or rhs2 is defined. In this case,
5242 stmt_to_insert has to be inserted afterwards. This would
5243 only happen when the stmt insertion point is flexible. */
5244 if (insert_before)
5245 gsi_insert_before (&gsi, stmt_to_insert, GSI_NEW_STMT);
5246 else
5247 insert_stmt_after (stmt_to_insert, insert_point);
5248 }
5249
5250
5251 /* Recursively rewrite our linearized statements so that the operators
5252 match those in OPS[OPINDEX], putting the computation in rank
5253 order. Return new lhs.
5254 CHANGED is true if we shouldn't reuse the lhs SSA_NAME both in
5255 the current stmt and during recursive invocations.
5256 NEXT_CHANGED is true if we shouldn't reuse the lhs SSA_NAME in
5257 recursive invocations. */
5258
5259 static tree
5260 rewrite_expr_tree (gimple *stmt, enum tree_code rhs_code, unsigned int opindex,
5261 const vec<operand_entry *> &ops, bool changed,
5262 bool next_changed)
5263 {
5264 tree rhs1 = gimple_assign_rhs1 (stmt);
5265 tree rhs2 = gimple_assign_rhs2 (stmt);
5266 tree lhs = gimple_assign_lhs (stmt);
5267 operand_entry *oe;
5268
5269 /* The final recursion case for this function is that you have
5270 exactly two operations left.
5271 If we had exactly one op in the entire list to start with, we
5272 would have never called this function, and the tail recursion
5273 rewrites them one at a time. */
5274 if (opindex + 2 == ops.length ())
5275 {
5276 operand_entry *oe1, *oe2;
5277
5278 oe1 = ops[opindex];
5279 oe2 = ops[opindex + 1];
5280
5281 if (rhs1 != oe1->op || rhs2 != oe2->op)
5282 {
5283 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
5284 unsigned int uid = gimple_uid (stmt);
5285
5286 if (dump_file && (dump_flags & TDF_DETAILS))
5287 {
5288 fprintf (dump_file, "Transforming ");
5289 print_gimple_stmt (dump_file, stmt, 0);
5290 }
5291
5292 /* If the stmt that defines operand has to be inserted, insert it
5293 before the use. */
5294 if (oe1->stmt_to_insert)
5295 insert_stmt_before_use (stmt, oe1->stmt_to_insert);
5296 if (oe2->stmt_to_insert)
5297 insert_stmt_before_use (stmt, oe2->stmt_to_insert);
5298 /* Even when changed is false, reassociation could have e.g. removed
5299 some redundant operations, so unless we are just swapping the
5300 arguments or unless there is no change at all (then we just
5301 return lhs), force creation of a new SSA_NAME. */
5302 if (changed || ((rhs1 != oe2->op || rhs2 != oe1->op) && opindex))
5303 {
5304 bool insert_before;
5305 gimple *insert_point
5306 = find_insert_point (stmt, oe1->op, oe2->op, insert_before);
5307 lhs = make_ssa_name (TREE_TYPE (lhs));
5308 stmt
5309 = gimple_build_assign (lhs, rhs_code,
5310 oe1->op, oe2->op);
5311 gimple_set_uid (stmt, uid);
5312 gimple_set_visited (stmt, true);
5313 if (insert_before)
5314 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
5315 else
5316 insert_stmt_after (stmt, insert_point);
5317 }
5318 else
5319 {
5320 bool insert_before;
5321 gcc_checking_assert (find_insert_point (stmt, oe1->op, oe2->op,
5322 insert_before)
5323 == stmt);
5324 gimple_assign_set_rhs1 (stmt, oe1->op);
5325 gimple_assign_set_rhs2 (stmt, oe2->op);
5326 update_stmt (stmt);
5327 }
5328
5329 if (rhs1 != oe1->op && rhs1 != oe2->op)
5330 remove_visited_stmt_chain (rhs1);
5331
5332 if (dump_file && (dump_flags & TDF_DETAILS))
5333 {
5334 fprintf (dump_file, " into ");
5335 print_gimple_stmt (dump_file, stmt, 0);
5336 }
5337 }
5338 return lhs;
5339 }
5340
5341 /* If we hit here, we should have 3 or more ops left. */
5342 gcc_assert (opindex + 2 < ops.length ());
5343
5344 /* Rewrite the next operator. */
5345 oe = ops[opindex];
5346
5347 /* If the stmt that defines operand has to be inserted, insert it
5348 before the use. */
5349 if (oe->stmt_to_insert)
5350 insert_stmt_before_use (stmt, oe->stmt_to_insert);
5351
5352 /* Recurse on the LHS of the binary operator, which is guaranteed to
5353 be the non-leaf side. */
5354 tree new_rhs1
5355 = rewrite_expr_tree (SSA_NAME_DEF_STMT (rhs1), rhs_code, opindex + 1, ops,
5356 changed || oe->op != rhs2 || next_changed,
5357 false);
5358
5359 if (oe->op != rhs2 || new_rhs1 != rhs1)
5360 {
5361 if (dump_file && (dump_flags & TDF_DETAILS))
5362 {
5363 fprintf (dump_file, "Transforming ");
5364 print_gimple_stmt (dump_file, stmt, 0);
5365 }
5366
5367 /* If changed is false, this is either opindex == 0
5368 or all outer rhs2's were equal to corresponding oe->op,
5369 and powi_result is NULL.
5370 That means lhs is equivalent before and after reassociation.
5371 Otherwise ensure the old lhs SSA_NAME is not reused and
5372 create a new stmt as well, so that any debug stmts will be
5373 properly adjusted. */
5374 if (changed)
5375 {
5376 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
5377 unsigned int uid = gimple_uid (stmt);
5378 bool insert_before;
5379 gimple *insert_point = find_insert_point (stmt, new_rhs1, oe->op,
5380 insert_before);
5381
5382 lhs = make_ssa_name (TREE_TYPE (lhs));
5383 stmt = gimple_build_assign (lhs, rhs_code,
5384 new_rhs1, oe->op);
5385 gimple_set_uid (stmt, uid);
5386 gimple_set_visited (stmt, true);
5387 if (insert_before)
5388 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
5389 else
5390 insert_stmt_after (stmt, insert_point);
5391 }
5392 else
5393 {
5394 bool insert_before;
5395 gcc_checking_assert (find_insert_point (stmt, new_rhs1, oe->op,
5396 insert_before)
5397 == stmt);
5398 gimple_assign_set_rhs1 (stmt, new_rhs1);
5399 gimple_assign_set_rhs2 (stmt, oe->op);
5400 update_stmt (stmt);
5401 }
5402
5403 if (dump_file && (dump_flags & TDF_DETAILS))
5404 {
5405 fprintf (dump_file, " into ");
5406 print_gimple_stmt (dump_file, stmt, 0);
5407 }
5408 }
5409 return lhs;
5410 }
5411
5412 /* Find out how many cycles we need to compute statements chain.
5413 OPS_NUM holds number os statements in a chain. CPU_WIDTH is a
5414 maximum number of independent statements we may execute per cycle. */
5415
5416 static int
5417 get_required_cycles (int ops_num, int cpu_width)
5418 {
5419 int res;
5420 int elog;
5421 unsigned int rest;
5422
5423 /* While we have more than 2 * cpu_width operands
5424 we may reduce number of operands by cpu_width
5425 per cycle. */
5426 res = ops_num / (2 * cpu_width);
5427
5428 /* Remained operands count may be reduced twice per cycle
5429 until we have only one operand. */
5430 rest = (unsigned)(ops_num - res * cpu_width);
5431 elog = exact_log2 (rest);
5432 if (elog >= 0)
5433 res += elog;
5434 else
5435 res += floor_log2 (rest) + 1;
5436
5437 return res;
5438 }
5439
5440 /* Given that the target fully pipelines FMA instructions, return the latency
5441 of MULT_EXPRs that can't be hidden by the FMAs. WIDTH is the number of
5442 pipes. */
5443
5444 static inline int
5445 get_mult_latency_consider_fma (int ops_num, int mult_num, int width)
5446 {
5447 gcc_checking_assert (mult_num && mult_num <= ops_num);
5448
5449 /* For each partition, if mult_num == ops_num, there's latency(MULT)*2.
5450 e.g:
5451
5452 A * B + C * D
5453 =>
5454 _1 = A * B;
5455 _2 = .FMA (C, D, _1);
5456
5457 Otherwise there's latency(MULT)*1 in the first FMA. */
5458 return CEIL (ops_num, width) == CEIL (mult_num, width) ? 2 : 1;
5459 }
5460
5461 /* Returns an optimal number of registers to use for computation of
5462 given statements.
5463
5464 LHS is the result ssa name of OPS. MULT_NUM is number of sub-expressions
5465 that are MULT_EXPRs, when OPS are PLUS_EXPRs or MINUS_EXPRs. */
5466
5467 static int
5468 get_reassociation_width (vec<operand_entry *> *ops, int mult_num, tree lhs,
5469 enum tree_code opc, machine_mode mode)
5470 {
5471 int param_width = param_tree_reassoc_width;
5472 int width;
5473 int width_min;
5474 int cycles_best;
5475 int ops_num = ops->length ();
5476
5477 if (param_width > 0)
5478 width = param_width;
5479 else
5480 width = targetm.sched.reassociation_width (opc, mode);
5481
5482 if (width == 1)
5483 return width;
5484
5485 /* Get the minimal time required for sequence computation. */
5486 cycles_best = get_required_cycles (ops_num, width);
5487
5488 /* Check if we may use less width and still compute sequence for
5489 the same time. It will allow us to reduce registers usage.
5490 get_required_cycles is monotonically increasing with lower width
5491 so we can perform a binary search for the minimal width that still
5492 results in the optimal cycle count. */
5493 width_min = 1;
5494
5495 /* If the target fully pipelines FMA instruction, the multiply part can start
5496 already if its operands are ready. Assuming symmetric pipes are used for
5497 FMUL/FADD/FMA, then for a sequence of FMA like:
5498
5499 _8 = .FMA (_2, _3, _1);
5500 _9 = .FMA (_5, _4, _8);
5501 _10 = .FMA (_7, _6, _9);
5502
5503 , if width=1, the latency is latency(MULT) + latency(ADD)*3.
5504 While with width=2:
5505
5506 _8 = _4 * _5;
5507 _9 = .FMA (_2, _3, _1);
5508 _10 = .FMA (_6, _7, _8);
5509 _11 = _9 + _10;
5510
5511 , it is latency(MULT)*2 + latency(ADD)*2. Assuming latency(MULT) >=
5512 latency(ADD), the first variant is preferred.
5513
5514 Find out if we can get a smaller width considering FMA.
5515 Assume FMUL and FMA use the same units that can also do FADD.
5516 For other scenarios, such as when FMUL and FADD are using separated units,
5517 the following code may not apply. */
5518
5519 int width_mult = targetm.sched.reassociation_width (MULT_EXPR, mode);
5520 if (width > 1 && mult_num && param_fully_pipelined_fma
5521 && width_mult <= width)
5522 {
5523 /* Latency of MULT_EXPRs. */
5524 int lat_mul
5525 = get_mult_latency_consider_fma (ops_num, mult_num, width_mult);
5526
5527 /* Quick search might not apply. So start from 1. */
5528 for (int i = 1; i < width_mult; i++)
5529 {
5530 int lat_mul_new
5531 = get_mult_latency_consider_fma (ops_num, mult_num, i);
5532 int lat_add_new = get_required_cycles (ops_num, i);
5533
5534 /* Assume latency(MULT) >= latency(ADD). */
5535 if (lat_mul - lat_mul_new >= lat_add_new - cycles_best)
5536 {
5537 width = i;
5538 break;
5539 }
5540 }
5541 }
5542 else
5543 {
5544 while (width > width_min)
5545 {
5546 int width_mid = (width + width_min) / 2;
5547
5548 if (get_required_cycles (ops_num, width_mid) == cycles_best)
5549 width = width_mid;
5550 else if (width_min < width_mid)
5551 width_min = width_mid;
5552 else
5553 break;
5554 }
5555 }
5556
5557 /* If there's loop dependent FMA result, return width=2 to avoid it. This is
5558 better than skipping these FMA candidates in widening_mul. */
5559 if (width == 1
5560 && maybe_le (tree_to_poly_int64 (TYPE_SIZE (TREE_TYPE (lhs))),
5561 param_avoid_fma_max_bits))
5562 {
5563 /* Look for cross backedge dependency:
5564 1. LHS is a phi argument in the same basic block it is defined.
5565 2. And the result of the phi node is used in OPS. */
5566 basic_block bb = gimple_bb (SSA_NAME_DEF_STMT (lhs));
5567
5568 use_operand_p use_p;
5569 imm_use_iterator iter;
5570 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
5571 if (gphi *phi = dyn_cast<gphi *> (USE_STMT (use_p)))
5572 {
5573 if (gimple_phi_arg_edge (phi, phi_arg_index_from_use (use_p))->src
5574 != bb)
5575 continue;
5576 tree phi_result = gimple_phi_result (phi);
5577 operand_entry *oe;
5578 unsigned int j;
5579 FOR_EACH_VEC_ELT (*ops, j, oe)
5580 {
5581 if (TREE_CODE (oe->op) != SSA_NAME)
5582 continue;
5583
5584 /* Result of phi is operand of PLUS_EXPR. */
5585 if (oe->op == phi_result)
5586 return 2;
5587
5588 /* Check is result of phi is operand of MULT_EXPR. */
5589 gimple *def_stmt = SSA_NAME_DEF_STMT (oe->op);
5590 if (is_gimple_assign (def_stmt)
5591 && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR)
5592 {
5593 tree rhs = gimple_assign_rhs1 (def_stmt);
5594 if (TREE_CODE (rhs) == SSA_NAME)
5595 {
5596 if (rhs == phi_result)
5597 return 2;
5598 def_stmt = SSA_NAME_DEF_STMT (rhs);
5599 }
5600 }
5601 if (is_gimple_assign (def_stmt)
5602 && gimple_assign_rhs_code (def_stmt) == MULT_EXPR)
5603 {
5604 if (gimple_assign_rhs1 (def_stmt) == phi_result
5605 || gimple_assign_rhs2 (def_stmt) == phi_result)
5606 return 2;
5607 }
5608 }
5609 }
5610 }
5611
5612 return width;
5613 }
5614
5615 #define SPECIAL_BIASED_END_STMT 0 /* It is the end stmt of all ops. */
5616 #define BIASED_END_STMT 1 /* It is the end stmt of normal or biased ops. */
5617 #define NORMAL_END_STMT 2 /* It is the end stmt of normal ops. */
5618
5619 /* Rewrite statements with dependency chain with regard the chance to generate
5620 FMA.
5621 For the chain with FMA: Try to keep fma opportunity as much as possible.
5622 For the chain without FMA: Putting the computation in rank order and trying
5623 to allow operations to be executed in parallel.
5624 E.g.
5625 e + f + a * b + c * d;
5626
5627 ssa1 = e + a * b;
5628 ssa2 = f + c * d;
5629 ssa3 = ssa1 + ssa2;
5630
5631 This reassociation approach preserves the chance of fma generation as much
5632 as possible.
5633
5634 Another thing is to avoid adding loop-carried ops to long chains, otherwise
5635 the whole chain will have dependencies across the loop iteration. Just keep
5636 loop-carried ops in a separate chain.
5637 E.g.
5638 x_1 = phi (x_0, x_2)
5639 y_1 = phi (y_0, y_2)
5640
5641 a + b + c + d + e + x1 + y1
5642
5643 SSA1 = a + b;
5644 SSA2 = c + d;
5645 SSA3 = SSA1 + e;
5646 SSA4 = SSA3 + SSA2;
5647 SSA5 = x1 + y1;
5648 SSA6 = SSA4 + SSA5;
5649 */
5650 static void
5651 rewrite_expr_tree_parallel (gassign *stmt, int width, bool has_fma,
5652 const vec<operand_entry *> &ops)
5653 {
5654 enum tree_code opcode = gimple_assign_rhs_code (stmt);
5655 int op_num = ops.length ();
5656 int op_normal_num = op_num;
5657 gcc_assert (op_num > 0);
5658 int stmt_num = op_num - 1;
5659 gimple **stmts = XALLOCAVEC (gimple *, stmt_num);
5660 int i = 0, j = 0;
5661 tree tmp_op[2], op1;
5662 operand_entry *oe;
5663 gimple *stmt1 = NULL;
5664 tree last_rhs1 = gimple_assign_rhs1 (stmt);
5665 int last_rhs1_stmt_index = 0, last_rhs2_stmt_index = 0;
5666 int width_active = 0, width_count = 0;
5667 bool has_biased = false, ops_changed = false;
5668 auto_vec<operand_entry *> ops_normal;
5669 auto_vec<operand_entry *> ops_biased;
5670 vec<operand_entry *> *ops1;
5671
5672 /* We start expression rewriting from the top statements.
5673 So, in this loop we create a full list of statements
5674 we will work with. */
5675 stmts[stmt_num - 1] = stmt;
5676 for (i = stmt_num - 2; i >= 0; i--)
5677 stmts[i] = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmts[i+1]));
5678
5679 /* Avoid adding loop-carried ops to long chains, first filter out the
5680 loop-carried. But we need to make sure that the length of the remainder
5681 is not less than 4, which is the smallest ops length we can break the
5682 dependency. */
5683 FOR_EACH_VEC_ELT (ops, i, oe)
5684 {
5685 if (TREE_CODE (oe->op) == SSA_NAME
5686 && bitmap_bit_p (biased_names, SSA_NAME_VERSION (oe->op))
5687 && op_normal_num > 4)
5688 {
5689 ops_biased.safe_push (oe);
5690 has_biased = true;
5691 op_normal_num --;
5692 }
5693 else
5694 ops_normal.safe_push (oe);
5695 }
5696
5697 /* Width should not be larger than ops length / 2, since we can not create
5698 more parallel dependency chains that exceeds such value. */
5699 int width_normal = op_normal_num / 2;
5700 int width_biased = (op_num - op_normal_num) / 2;
5701 width_normal = width <= width_normal ? width : width_normal;
5702 width_biased = width <= width_biased ? width : width_biased;
5703
5704 ops1 = &ops_normal;
5705 width_count = width_active = width_normal;
5706
5707 /* Build parallel dependency chain according to width. */
5708 for (i = 0; i < stmt_num; i++)
5709 {
5710 if (dump_file && (dump_flags & TDF_DETAILS))
5711 {
5712 fprintf (dump_file, "Transforming ");
5713 print_gimple_stmt (dump_file, stmts[i], 0);
5714 }
5715
5716 /* When the work of normal ops is over, but the loop is not over,
5717 continue to do biased ops. */
5718 if (width_count == 0 && ops1 == &ops_normal)
5719 {
5720 ops1 = &ops_biased;
5721 width_count = width_active = width_biased;
5722 ops_changed = true;
5723 }
5724
5725 /* Swap the operands if no FMA in the chain. */
5726 if (ops1->length () > 2 && !has_fma)
5727 swap_ops_for_binary_stmt (*ops1, ops1->length () - 3);
5728
5729 if (i < width_active
5730 || (ops_changed && i <= (last_rhs1_stmt_index + width_active)))
5731 {
5732 for (j = 0; j < 2; j++)
5733 {
5734 oe = ops1->pop ();
5735 tmp_op[j] = oe->op;
5736 /* If the stmt that defines operand has to be inserted, insert it
5737 before the use. */
5738 stmt1 = oe->stmt_to_insert;
5739 if (stmt1)
5740 insert_stmt_before_use (stmts[i], stmt1);
5741 stmt1 = NULL;
5742 }
5743 stmts[i] = build_and_add_sum (TREE_TYPE (last_rhs1),
5744 tmp_op[1],
5745 tmp_op[0],
5746 opcode);
5747 gimple_set_visited (stmts[i], true);
5748
5749 }
5750 else
5751 {
5752 /* We keep original statement only for the last one. All others are
5753 recreated. */
5754 if (!ops1->length ())
5755 {
5756 /* For biased length equal to 2. */
5757 if (width_count == BIASED_END_STMT && !last_rhs2_stmt_index)
5758 last_rhs2_stmt_index = i - 1;
5759
5760 /* When width_count == 2 and there is no biased, just finish. */
5761 if (width_count == NORMAL_END_STMT && !has_biased)
5762 {
5763 last_rhs1_stmt_index = i - 1;
5764 last_rhs2_stmt_index = i - 2;
5765 }
5766 if (last_rhs1_stmt_index && (last_rhs2_stmt_index || !has_biased))
5767 {
5768 /* We keep original statement only for the last one. All
5769 others are recreated. */
5770 gimple_assign_set_rhs1 (stmts[i], gimple_assign_lhs
5771 (stmts[last_rhs1_stmt_index]));
5772 gimple_assign_set_rhs2 (stmts[i], gimple_assign_lhs
5773 (stmts[last_rhs2_stmt_index]));
5774 update_stmt (stmts[i]);
5775 }
5776 else
5777 {
5778 stmts[i] =
5779 build_and_add_sum (TREE_TYPE (last_rhs1),
5780 gimple_assign_lhs (stmts[i-width_count]),
5781 gimple_assign_lhs
5782 (stmts[i-width_count+1]),
5783 opcode);
5784 gimple_set_visited (stmts[i], true);
5785 width_count--;
5786
5787 /* It is the end of normal or biased ops.
5788 last_rhs1_stmt_index used to record the last stmt index
5789 for normal ops. last_rhs2_stmt_index used to record the
5790 last stmt index for biased ops. */
5791 if (width_count == BIASED_END_STMT)
5792 {
5793 gcc_assert (has_biased);
5794 if (ops_biased.length ())
5795 last_rhs1_stmt_index = i;
5796 else
5797 last_rhs2_stmt_index = i;
5798 width_count--;
5799 }
5800 }
5801 }
5802 else
5803 {
5804 /* Attach the rest ops to the parallel dependency chain. */
5805 oe = ops1->pop ();
5806 op1 = oe->op;
5807 stmt1 = oe->stmt_to_insert;
5808 if (stmt1)
5809 insert_stmt_before_use (stmts[i], stmt1);
5810 stmt1 = NULL;
5811
5812 /* For only one biased ops. */
5813 if (width_count == SPECIAL_BIASED_END_STMT)
5814 {
5815 /* We keep original statement only for the last one. All
5816 others are recreated. */
5817 gcc_assert (has_biased);
5818 gimple_assign_set_rhs1 (stmts[i], gimple_assign_lhs
5819 (stmts[last_rhs1_stmt_index]));
5820 gimple_assign_set_rhs2 (stmts[i], op1);
5821 update_stmt (stmts[i]);
5822 }
5823 else
5824 {
5825 stmts[i] = build_and_add_sum (TREE_TYPE (last_rhs1),
5826 gimple_assign_lhs
5827 (stmts[i-width_active]),
5828 op1,
5829 opcode);
5830 gimple_set_visited (stmts[i], true);
5831 }
5832 }
5833 }
5834
5835 if (dump_file && (dump_flags & TDF_DETAILS))
5836 {
5837 fprintf (dump_file, " into ");
5838 print_gimple_stmt (dump_file, stmts[i], 0);
5839 }
5840 }
5841
5842 remove_visited_stmt_chain (last_rhs1);
5843 }
5844
5845 /* Transform STMT, which is really (A +B) + (C + D) into the left
5846 linear form, ((A+B)+C)+D.
5847 Recurse on D if necessary. */
5848
5849 static void
5850 linearize_expr (gimple *stmt)
5851 {
5852 gimple_stmt_iterator gsi;
5853 gimple *binlhs = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
5854 gimple *binrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
5855 gimple *oldbinrhs = binrhs;
5856 enum tree_code rhscode = gimple_assign_rhs_code (stmt);
5857 gimple *newbinrhs = NULL;
5858 class loop *loop = loop_containing_stmt (stmt);
5859 tree lhs = gimple_assign_lhs (stmt);
5860
5861 gcc_assert (is_reassociable_op (binlhs, rhscode, loop)
5862 && is_reassociable_op (binrhs, rhscode, loop));
5863
5864 gsi = gsi_for_stmt (stmt);
5865
5866 gimple_assign_set_rhs2 (stmt, gimple_assign_rhs1 (binrhs));
5867 binrhs = gimple_build_assign (make_ssa_name (TREE_TYPE (lhs)),
5868 gimple_assign_rhs_code (binrhs),
5869 gimple_assign_lhs (binlhs),
5870 gimple_assign_rhs2 (binrhs));
5871 gimple_assign_set_rhs1 (stmt, gimple_assign_lhs (binrhs));
5872 gsi_insert_before (&gsi, binrhs, GSI_SAME_STMT);
5873 gimple_set_uid (binrhs, gimple_uid (stmt));
5874
5875 if (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME)
5876 newbinrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
5877
5878 if (dump_file && (dump_flags & TDF_DETAILS))
5879 {
5880 fprintf (dump_file, "Linearized: ");
5881 print_gimple_stmt (dump_file, stmt, 0);
5882 }
5883
5884 reassociate_stats.linearized++;
5885 update_stmt (stmt);
5886
5887 gsi = gsi_for_stmt (oldbinrhs);
5888 reassoc_remove_stmt (&gsi);
5889 release_defs (oldbinrhs);
5890
5891 gimple_set_visited (stmt, true);
5892 gimple_set_visited (binlhs, true);
5893 gimple_set_visited (binrhs, true);
5894
5895 /* Tail recurse on the new rhs if it still needs reassociation. */
5896 if (newbinrhs && is_reassociable_op (newbinrhs, rhscode, loop))
5897 /* ??? This should probably be linearize_expr (newbinrhs) but I don't
5898 want to change the algorithm while converting to tuples. */
5899 linearize_expr (stmt);
5900 }
5901
5902 /* If LHS has a single immediate use that is a GIMPLE_ASSIGN statement, return
5903 it. Otherwise, return NULL. */
5904
5905 static gimple *
5906 get_single_immediate_use (tree lhs)
5907 {
5908 use_operand_p immuse;
5909 gimple *immusestmt;
5910
5911 if (TREE_CODE (lhs) == SSA_NAME
5912 && single_imm_use (lhs, &immuse, &immusestmt)
5913 && is_gimple_assign (immusestmt))
5914 return immusestmt;
5915
5916 return NULL;
5917 }
5918
5919 /* Recursively negate the value of TONEGATE, and return the SSA_NAME
5920 representing the negated value. Insertions of any necessary
5921 instructions go before GSI.
5922 This function is recursive in that, if you hand it "a_5" as the
5923 value to negate, and a_5 is defined by "a_5 = b_3 + b_4", it will
5924 transform b_3 + b_4 into a_5 = -b_3 + -b_4. */
5925
5926 static tree
5927 negate_value (tree tonegate, gimple_stmt_iterator *gsip)
5928 {
5929 gimple *negatedefstmt = NULL;
5930 tree resultofnegate;
5931 gimple_stmt_iterator gsi;
5932 unsigned int uid;
5933
5934 /* If we are trying to negate a name, defined by an add, negate the
5935 add operands instead. */
5936 if (TREE_CODE (tonegate) == SSA_NAME)
5937 negatedefstmt = SSA_NAME_DEF_STMT (tonegate);
5938 if (TREE_CODE (tonegate) == SSA_NAME
5939 && is_gimple_assign (negatedefstmt)
5940 && TREE_CODE (gimple_assign_lhs (negatedefstmt)) == SSA_NAME
5941 && has_single_use (gimple_assign_lhs (negatedefstmt))
5942 && gimple_assign_rhs_code (negatedefstmt) == PLUS_EXPR)
5943 {
5944 tree rhs1 = gimple_assign_rhs1 (negatedefstmt);
5945 tree rhs2 = gimple_assign_rhs2 (negatedefstmt);
5946 tree lhs = gimple_assign_lhs (negatedefstmt);
5947 gimple *g;
5948
5949 gsi = gsi_for_stmt (negatedefstmt);
5950 rhs1 = negate_value (rhs1, &gsi);
5951
5952 gsi = gsi_for_stmt (negatedefstmt);
5953 rhs2 = negate_value (rhs2, &gsi);
5954
5955 gsi = gsi_for_stmt (negatedefstmt);
5956 lhs = make_ssa_name (TREE_TYPE (lhs));
5957 gimple_set_visited (negatedefstmt, true);
5958 g = gimple_build_assign (lhs, PLUS_EXPR, rhs1, rhs2);
5959 gimple_set_uid (g, gimple_uid (negatedefstmt));
5960 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
5961 return lhs;
5962 }
5963
5964 tonegate = fold_build1 (NEGATE_EXPR, TREE_TYPE (tonegate), tonegate);
5965 resultofnegate = force_gimple_operand_gsi (gsip, tonegate, true,
5966 NULL_TREE, true, GSI_SAME_STMT);
5967 gsi = *gsip;
5968 uid = gimple_uid (gsi_stmt (gsi));
5969 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
5970 {
5971 gimple *stmt = gsi_stmt (gsi);
5972 if (gimple_uid (stmt) != 0)
5973 break;
5974 gimple_set_uid (stmt, uid);
5975 }
5976 return resultofnegate;
5977 }
5978
5979 /* Return true if we should break up the subtract in STMT into an add
5980 with negate. This is true when we the subtract operands are really
5981 adds, or the subtract itself is used in an add expression. In
5982 either case, breaking up the subtract into an add with negate
5983 exposes the adds to reassociation. */
5984
5985 static bool
5986 should_break_up_subtract (gimple *stmt)
5987 {
5988 tree lhs = gimple_assign_lhs (stmt);
5989 tree binlhs = gimple_assign_rhs1 (stmt);
5990 tree binrhs = gimple_assign_rhs2 (stmt);
5991 gimple *immusestmt;
5992 class loop *loop = loop_containing_stmt (stmt);
5993
5994 if (TREE_CODE (binlhs) == SSA_NAME
5995 && is_reassociable_op (SSA_NAME_DEF_STMT (binlhs), PLUS_EXPR, loop))
5996 return true;
5997
5998 if (TREE_CODE (binrhs) == SSA_NAME
5999 && is_reassociable_op (SSA_NAME_DEF_STMT (binrhs), PLUS_EXPR, loop))
6000 return true;
6001
6002 if (TREE_CODE (lhs) == SSA_NAME
6003 && (immusestmt = get_single_immediate_use (lhs))
6004 && is_gimple_assign (immusestmt)
6005 && (gimple_assign_rhs_code (immusestmt) == PLUS_EXPR
6006 || (gimple_assign_rhs_code (immusestmt) == MINUS_EXPR
6007 && gimple_assign_rhs1 (immusestmt) == lhs)
6008 || gimple_assign_rhs_code (immusestmt) == MULT_EXPR))
6009 return true;
6010 return false;
6011 }
6012
6013 /* Transform STMT from A - B into A + -B. */
6014
6015 static void
6016 break_up_subtract (gimple *stmt, gimple_stmt_iterator *gsip)
6017 {
6018 tree rhs1 = gimple_assign_rhs1 (stmt);
6019 tree rhs2 = gimple_assign_rhs2 (stmt);
6020
6021 if (dump_file && (dump_flags & TDF_DETAILS))
6022 {
6023 fprintf (dump_file, "Breaking up subtract ");
6024 print_gimple_stmt (dump_file, stmt, 0);
6025 }
6026
6027 rhs2 = negate_value (rhs2, gsip);
6028 gimple_assign_set_rhs_with_ops (gsip, PLUS_EXPR, rhs1, rhs2);
6029 update_stmt (stmt);
6030 }
6031
6032 /* Determine whether STMT is a builtin call that raises an SSA name
6033 to an integer power and has only one use. If so, and this is early
6034 reassociation and unsafe math optimizations are permitted, place
6035 the SSA name in *BASE and the exponent in *EXPONENT, and return TRUE.
6036 If any of these conditions does not hold, return FALSE. */
6037
6038 static bool
6039 acceptable_pow_call (gcall *stmt, tree *base, HOST_WIDE_INT *exponent)
6040 {
6041 tree arg1;
6042 REAL_VALUE_TYPE c, cint;
6043
6044 switch (gimple_call_combined_fn (stmt))
6045 {
6046 CASE_CFN_POW:
6047 if (flag_errno_math)
6048 return false;
6049
6050 *base = gimple_call_arg (stmt, 0);
6051 arg1 = gimple_call_arg (stmt, 1);
6052
6053 if (TREE_CODE (arg1) != REAL_CST)
6054 return false;
6055
6056 c = TREE_REAL_CST (arg1);
6057
6058 if (REAL_EXP (&c) > HOST_BITS_PER_WIDE_INT)
6059 return false;
6060
6061 *exponent = real_to_integer (&c);
6062 real_from_integer (&cint, VOIDmode, *exponent, SIGNED);
6063 if (!real_identical (&c, &cint))
6064 return false;
6065
6066 break;
6067
6068 CASE_CFN_POWI:
6069 *base = gimple_call_arg (stmt, 0);
6070 arg1 = gimple_call_arg (stmt, 1);
6071
6072 if (!tree_fits_shwi_p (arg1))
6073 return false;
6074
6075 *exponent = tree_to_shwi (arg1);
6076 break;
6077
6078 default:
6079 return false;
6080 }
6081
6082 /* Expanding negative exponents is generally unproductive, so we don't
6083 complicate matters with those. Exponents of zero and one should
6084 have been handled by expression folding. */
6085 if (*exponent < 2 || TREE_CODE (*base) != SSA_NAME)
6086 return false;
6087
6088 return true;
6089 }
6090
6091 /* Try to derive and add operand entry for OP to *OPS. Return false if
6092 unsuccessful. */
6093
6094 static bool
6095 try_special_add_to_ops (vec<operand_entry *> *ops,
6096 enum tree_code code,
6097 tree op, gimple* def_stmt)
6098 {
6099 tree base = NULL_TREE;
6100 HOST_WIDE_INT exponent = 0;
6101
6102 if (TREE_CODE (op) != SSA_NAME
6103 || ! has_single_use (op))
6104 return false;
6105
6106 if (code == MULT_EXPR
6107 && reassoc_insert_powi_p
6108 && flag_unsafe_math_optimizations
6109 && is_gimple_call (def_stmt)
6110 && acceptable_pow_call (as_a <gcall *> (def_stmt), &base, &exponent))
6111 {
6112 add_repeat_to_ops_vec (ops, base, exponent);
6113 gimple_set_visited (def_stmt, true);
6114 return true;
6115 }
6116 else if (code == MULT_EXPR
6117 && is_gimple_assign (def_stmt)
6118 && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
6119 && !HONOR_SNANS (TREE_TYPE (op))
6120 && (!HONOR_SIGNED_ZEROS (TREE_TYPE (op))
6121 || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (op)))
6122 && (!FLOAT_TYPE_P (TREE_TYPE (op))
6123 || !DECIMAL_FLOAT_MODE_P (element_mode (op))))
6124 {
6125 tree rhs1 = gimple_assign_rhs1 (def_stmt);
6126 tree cst = build_minus_one_cst (TREE_TYPE (op));
6127 add_to_ops_vec (ops, rhs1);
6128 add_to_ops_vec (ops, cst);
6129 gimple_set_visited (def_stmt, true);
6130 return true;
6131 }
6132
6133 return false;
6134 }
6135
6136 /* Recursively linearize a binary expression that is the RHS of STMT.
6137 Place the operands of the expression tree in the vector named OPS. */
6138
6139 static void
6140 linearize_expr_tree (vec<operand_entry *> *ops, gimple *stmt,
6141 bool is_associative, bool set_visited)
6142 {
6143 tree binlhs = gimple_assign_rhs1 (stmt);
6144 tree binrhs = gimple_assign_rhs2 (stmt);
6145 gimple *binlhsdef = NULL, *binrhsdef = NULL;
6146 bool binlhsisreassoc = false;
6147 bool binrhsisreassoc = false;
6148 enum tree_code rhscode = gimple_assign_rhs_code (stmt);
6149 class loop *loop = loop_containing_stmt (stmt);
6150
6151 if (set_visited)
6152 gimple_set_visited (stmt, true);
6153
6154 if (TREE_CODE (binlhs) == SSA_NAME)
6155 {
6156 binlhsdef = SSA_NAME_DEF_STMT (binlhs);
6157 binlhsisreassoc = (is_reassociable_op (binlhsdef, rhscode, loop)
6158 && !stmt_could_throw_p (cfun, binlhsdef));
6159 }
6160
6161 if (TREE_CODE (binrhs) == SSA_NAME)
6162 {
6163 binrhsdef = SSA_NAME_DEF_STMT (binrhs);
6164 binrhsisreassoc = (is_reassociable_op (binrhsdef, rhscode, loop)
6165 && !stmt_could_throw_p (cfun, binrhsdef));
6166 }
6167
6168 /* If the LHS is not reassociable, but the RHS is, we need to swap
6169 them. If neither is reassociable, there is nothing we can do, so
6170 just put them in the ops vector. If the LHS is reassociable,
6171 linearize it. If both are reassociable, then linearize the RHS
6172 and the LHS. */
6173
6174 if (!binlhsisreassoc)
6175 {
6176 /* If this is not a associative operation like division, give up. */
6177 if (!is_associative)
6178 {
6179 add_to_ops_vec (ops, binrhs);
6180 return;
6181 }
6182
6183 if (!binrhsisreassoc)
6184 {
6185 bool swap = false;
6186 if (try_special_add_to_ops (ops, rhscode, binrhs, binrhsdef))
6187 /* If we add ops for the rhs we expect to be able to recurse
6188 to it via the lhs during expression rewrite so swap
6189 operands. */
6190 swap = true;
6191 else
6192 add_to_ops_vec (ops, binrhs);
6193
6194 if (!try_special_add_to_ops (ops, rhscode, binlhs, binlhsdef))
6195 add_to_ops_vec (ops, binlhs);
6196
6197 if (!swap)
6198 return;
6199 }
6200
6201 if (dump_file && (dump_flags & TDF_DETAILS))
6202 {
6203 fprintf (dump_file, "swapping operands of ");
6204 print_gimple_stmt (dump_file, stmt, 0);
6205 }
6206
6207 swap_ssa_operands (stmt,
6208 gimple_assign_rhs1_ptr (stmt),
6209 gimple_assign_rhs2_ptr (stmt));
6210 update_stmt (stmt);
6211
6212 if (dump_file && (dump_flags & TDF_DETAILS))
6213 {
6214 fprintf (dump_file, " is now ");
6215 print_gimple_stmt (dump_file, stmt, 0);
6216 }
6217 if (!binrhsisreassoc)
6218 return;
6219
6220 /* We want to make it so the lhs is always the reassociative op,
6221 so swap. */
6222 std::swap (binlhs, binrhs);
6223 }
6224 else if (binrhsisreassoc)
6225 {
6226 linearize_expr (stmt);
6227 binlhs = gimple_assign_rhs1 (stmt);
6228 binrhs = gimple_assign_rhs2 (stmt);
6229 }
6230
6231 gcc_assert (TREE_CODE (binrhs) != SSA_NAME
6232 || !is_reassociable_op (SSA_NAME_DEF_STMT (binrhs),
6233 rhscode, loop));
6234 linearize_expr_tree (ops, SSA_NAME_DEF_STMT (binlhs),
6235 is_associative, set_visited);
6236
6237 if (!try_special_add_to_ops (ops, rhscode, binrhs, binrhsdef))
6238 add_to_ops_vec (ops, binrhs);
6239 }
6240
6241 /* Repropagate the negates back into subtracts, since no other pass
6242 currently does it. */
6243
6244 static void
6245 repropagate_negates (void)
6246 {
6247 unsigned int i = 0;
6248 tree negate;
6249
6250 FOR_EACH_VEC_ELT (plus_negates, i, negate)
6251 {
6252 gimple *user = get_single_immediate_use (negate);
6253 if (!user || !is_gimple_assign (user))
6254 continue;
6255
6256 tree negateop = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (negate));
6257 if (TREE_CODE (negateop) == SSA_NAME
6258 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (negateop))
6259 continue;
6260
6261 /* The negate operand can be either operand of a PLUS_EXPR
6262 (it can be the LHS if the RHS is a constant for example).
6263
6264 Force the negate operand to the RHS of the PLUS_EXPR, then
6265 transform the PLUS_EXPR into a MINUS_EXPR. */
6266 if (gimple_assign_rhs_code (user) == PLUS_EXPR)
6267 {
6268 /* If the negated operand appears on the LHS of the
6269 PLUS_EXPR, exchange the operands of the PLUS_EXPR
6270 to force the negated operand to the RHS of the PLUS_EXPR. */
6271 if (gimple_assign_rhs1 (user) == negate)
6272 {
6273 swap_ssa_operands (user,
6274 gimple_assign_rhs1_ptr (user),
6275 gimple_assign_rhs2_ptr (user));
6276 }
6277
6278 /* Now transform the PLUS_EXPR into a MINUS_EXPR and replace
6279 the RHS of the PLUS_EXPR with the operand of the NEGATE_EXPR. */
6280 if (gimple_assign_rhs2 (user) == negate)
6281 {
6282 tree rhs1 = gimple_assign_rhs1 (user);
6283 gimple_stmt_iterator gsi = gsi_for_stmt (user);
6284 gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, rhs1,
6285 negateop);
6286 update_stmt (user);
6287 }
6288 }
6289 else if (gimple_assign_rhs_code (user) == MINUS_EXPR)
6290 {
6291 if (gimple_assign_rhs1 (user) == negate)
6292 {
6293 /* We have
6294 x = -negateop
6295 y = x - b
6296 which we transform into
6297 x = negateop + b
6298 y = -x .
6299 This pushes down the negate which we possibly can merge
6300 into some other operation, hence insert it into the
6301 plus_negates vector. */
6302 gimple *feed = SSA_NAME_DEF_STMT (negate);
6303 tree b = gimple_assign_rhs2 (user);
6304 gimple_stmt_iterator gsi = gsi_for_stmt (feed);
6305 gimple_stmt_iterator gsi2 = gsi_for_stmt (user);
6306 tree x = make_ssa_name (TREE_TYPE (gimple_assign_lhs (feed)));
6307 gimple *g = gimple_build_assign (x, PLUS_EXPR, negateop, b);
6308 gsi_insert_before (&gsi2, g, GSI_SAME_STMT);
6309 gimple_assign_set_rhs_with_ops (&gsi2, NEGATE_EXPR, x);
6310 user = gsi_stmt (gsi2);
6311 update_stmt (user);
6312 reassoc_remove_stmt (&gsi);
6313 release_defs (feed);
6314 plus_negates.safe_push (gimple_assign_lhs (user));
6315 }
6316 else
6317 {
6318 /* Transform "x = -negateop; y = b - x" into "y = b + negateop",
6319 getting rid of one operation. */
6320 tree rhs1 = gimple_assign_rhs1 (user);
6321 gimple_stmt_iterator gsi = gsi_for_stmt (user);
6322 gimple_assign_set_rhs_with_ops (&gsi, PLUS_EXPR, rhs1, negateop);
6323 update_stmt (gsi_stmt (gsi));
6324 }
6325 }
6326 }
6327 }
6328
6329 /* Break up subtract operations in block BB.
6330
6331 We do this top down because we don't know whether the subtract is
6332 part of a possible chain of reassociation except at the top.
6333
6334 IE given
6335 d = f + g
6336 c = a + e
6337 b = c - d
6338 q = b - r
6339 k = t - q
6340
6341 we want to break up k = t - q, but we won't until we've transformed q
6342 = b - r, which won't be broken up until we transform b = c - d.
6343
6344 En passant, clear the GIMPLE visited flag on every statement
6345 and set UIDs within each basic block. */
6346
6347 static void
6348 break_up_subtract_bb (basic_block bb)
6349 {
6350 gimple_stmt_iterator gsi;
6351 unsigned int uid = 1;
6352
6353 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6354 {
6355 gimple *stmt = gsi_stmt (gsi);
6356 gimple_set_visited (stmt, false);
6357 gimple_set_uid (stmt, uid++);
6358
6359 if (!is_gimple_assign (stmt)
6360 || !can_reassociate_type_p (TREE_TYPE (gimple_assign_lhs (stmt)))
6361 || !can_reassociate_op_p (gimple_assign_lhs (stmt)))
6362 continue;
6363
6364 /* Look for simple gimple subtract operations. */
6365 if (gimple_assign_rhs_code (stmt) == MINUS_EXPR)
6366 {
6367 if (!can_reassociate_op_p (gimple_assign_rhs1 (stmt))
6368 || !can_reassociate_op_p (gimple_assign_rhs2 (stmt)))
6369 continue;
6370
6371 /* Check for a subtract used only in an addition. If this
6372 is the case, transform it into add of a negate for better
6373 reassociation. IE transform C = A-B into C = A + -B if C
6374 is only used in an addition. */
6375 if (should_break_up_subtract (stmt))
6376 break_up_subtract (stmt, &gsi);
6377 }
6378 else if (gimple_assign_rhs_code (stmt) == NEGATE_EXPR
6379 && can_reassociate_op_p (gimple_assign_rhs1 (stmt)))
6380 plus_negates.safe_push (gimple_assign_lhs (stmt));
6381 }
6382 }
6383
6384 /* Used for repeated factor analysis. */
6385 struct repeat_factor
6386 {
6387 /* An SSA name that occurs in a multiply chain. */
6388 tree factor;
6389
6390 /* Cached rank of the factor. */
6391 unsigned rank;
6392
6393 /* Number of occurrences of the factor in the chain. */
6394 HOST_WIDE_INT count;
6395
6396 /* An SSA name representing the product of this factor and
6397 all factors appearing later in the repeated factor vector. */
6398 tree repr;
6399 };
6400
6401
6402 static vec<repeat_factor> repeat_factor_vec;
6403
6404 /* Used for sorting the repeat factor vector. Sort primarily by
6405 ascending occurrence count, secondarily by descending rank. */
6406
6407 static int
6408 compare_repeat_factors (const void *x1, const void *x2)
6409 {
6410 const repeat_factor *rf1 = (const repeat_factor *) x1;
6411 const repeat_factor *rf2 = (const repeat_factor *) x2;
6412
6413 if (rf1->count < rf2->count)
6414 return -1;
6415 else if (rf1->count > rf2->count)
6416 return 1;
6417
6418 if (rf1->rank < rf2->rank)
6419 return 1;
6420 else if (rf1->rank > rf2->rank)
6421 return -1;
6422
6423 return 0;
6424 }
6425
6426 /* Look for repeated operands in OPS in the multiply tree rooted at
6427 STMT. Replace them with an optimal sequence of multiplies and powi
6428 builtin calls, and remove the used operands from OPS. Return an
6429 SSA name representing the value of the replacement sequence. */
6430
6431 static tree
6432 attempt_builtin_powi (gimple *stmt, vec<operand_entry *> *ops)
6433 {
6434 unsigned i, j, vec_len;
6435 int ii;
6436 operand_entry *oe;
6437 repeat_factor *rf1, *rf2;
6438 repeat_factor rfnew;
6439 tree result = NULL_TREE;
6440 tree target_ssa, iter_result;
6441 tree type = TREE_TYPE (gimple_get_lhs (stmt));
6442 tree powi_fndecl = mathfn_built_in (type, BUILT_IN_POWI);
6443 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
6444 gimple *mul_stmt, *pow_stmt;
6445
6446 /* Nothing to do if BUILT_IN_POWI doesn't exist for this type and
6447 target, unless type is integral. */
6448 if (!powi_fndecl && !INTEGRAL_TYPE_P (type))
6449 return NULL_TREE;
6450
6451 /* Allocate the repeated factor vector. */
6452 repeat_factor_vec.create (10);
6453
6454 /* Scan the OPS vector for all SSA names in the product and build
6455 up a vector of occurrence counts for each factor. */
6456 FOR_EACH_VEC_ELT (*ops, i, oe)
6457 {
6458 if (TREE_CODE (oe->op) == SSA_NAME)
6459 {
6460 FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
6461 {
6462 if (rf1->factor == oe->op)
6463 {
6464 rf1->count += oe->count;
6465 break;
6466 }
6467 }
6468
6469 if (j >= repeat_factor_vec.length ())
6470 {
6471 rfnew.factor = oe->op;
6472 rfnew.rank = oe->rank;
6473 rfnew.count = oe->count;
6474 rfnew.repr = NULL_TREE;
6475 repeat_factor_vec.safe_push (rfnew);
6476 }
6477 }
6478 }
6479
6480 /* Sort the repeated factor vector by (a) increasing occurrence count,
6481 and (b) decreasing rank. */
6482 repeat_factor_vec.qsort (compare_repeat_factors);
6483
6484 /* It is generally best to combine as many base factors as possible
6485 into a product before applying __builtin_powi to the result.
6486 However, the sort order chosen for the repeated factor vector
6487 allows us to cache partial results for the product of the base
6488 factors for subsequent use. When we already have a cached partial
6489 result from a previous iteration, it is best to make use of it
6490 before looking for another __builtin_pow opportunity.
6491
6492 As an example, consider x * x * y * y * y * z * z * z * z.
6493 We want to first compose the product x * y * z, raise it to the
6494 second power, then multiply this by y * z, and finally multiply
6495 by z. This can be done in 5 multiplies provided we cache y * z
6496 for use in both expressions:
6497
6498 t1 = y * z
6499 t2 = t1 * x
6500 t3 = t2 * t2
6501 t4 = t1 * t3
6502 result = t4 * z
6503
6504 If we instead ignored the cached y * z and first multiplied by
6505 the __builtin_pow opportunity z * z, we would get the inferior:
6506
6507 t1 = y * z
6508 t2 = t1 * x
6509 t3 = t2 * t2
6510 t4 = z * z
6511 t5 = t3 * t4
6512 result = t5 * y */
6513
6514 vec_len = repeat_factor_vec.length ();
6515
6516 /* Repeatedly look for opportunities to create a builtin_powi call. */
6517 while (true)
6518 {
6519 HOST_WIDE_INT power;
6520
6521 /* First look for the largest cached product of factors from
6522 preceding iterations. If found, create a builtin_powi for
6523 it if the minimum occurrence count for its factors is at
6524 least 2, or just use this cached product as our next
6525 multiplicand if the minimum occurrence count is 1. */
6526 FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
6527 {
6528 if (rf1->repr && rf1->count > 0)
6529 break;
6530 }
6531
6532 if (j < vec_len)
6533 {
6534 power = rf1->count;
6535
6536 if (power == 1)
6537 {
6538 iter_result = rf1->repr;
6539
6540 if (dump_file && (dump_flags & TDF_DETAILS))
6541 {
6542 unsigned elt;
6543 repeat_factor *rf;
6544 fputs ("Multiplying by cached product ", dump_file);
6545 for (elt = j; elt < vec_len; elt++)
6546 {
6547 rf = &repeat_factor_vec[elt];
6548 print_generic_expr (dump_file, rf->factor);
6549 if (elt < vec_len - 1)
6550 fputs (" * ", dump_file);
6551 }
6552 fputs ("\n", dump_file);
6553 }
6554 }
6555 else
6556 {
6557 if (INTEGRAL_TYPE_P (type))
6558 {
6559 gcc_assert (power > 1);
6560 gimple_stmt_iterator gsip = gsi;
6561 gsi_prev (&gsip);
6562 iter_result = powi_as_mults (&gsi, gimple_location (stmt),
6563 rf1->repr, power);
6564 gimple_stmt_iterator gsic = gsi;
6565 while (gsi_stmt (gsic) != gsi_stmt (gsip))
6566 {
6567 gimple_set_uid (gsi_stmt (gsic), gimple_uid (stmt));
6568 gimple_set_visited (gsi_stmt (gsic), true);
6569 gsi_prev (&gsic);
6570 }
6571 }
6572 else
6573 {
6574 iter_result = make_temp_ssa_name (type, NULL, "reassocpow");
6575 pow_stmt
6576 = gimple_build_call (powi_fndecl, 2, rf1->repr,
6577 build_int_cst (integer_type_node,
6578 power));
6579 gimple_call_set_lhs (pow_stmt, iter_result);
6580 gimple_set_location (pow_stmt, gimple_location (stmt));
6581 gimple_set_uid (pow_stmt, gimple_uid (stmt));
6582 gsi_insert_before (&gsi, pow_stmt, GSI_SAME_STMT);
6583 }
6584
6585 if (dump_file && (dump_flags & TDF_DETAILS))
6586 {
6587 unsigned elt;
6588 repeat_factor *rf;
6589 fputs ("Building __builtin_pow call for cached product (",
6590 dump_file);
6591 for (elt = j; elt < vec_len; elt++)
6592 {
6593 rf = &repeat_factor_vec[elt];
6594 print_generic_expr (dump_file, rf->factor);
6595 if (elt < vec_len - 1)
6596 fputs (" * ", dump_file);
6597 }
6598 fprintf (dump_file, ")^" HOST_WIDE_INT_PRINT_DEC"\n",
6599 power);
6600 }
6601 }
6602 }
6603 else
6604 {
6605 /* Otherwise, find the first factor in the repeated factor
6606 vector whose occurrence count is at least 2. If no such
6607 factor exists, there are no builtin_powi opportunities
6608 remaining. */
6609 FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
6610 {
6611 if (rf1->count >= 2)
6612 break;
6613 }
6614
6615 if (j >= vec_len)
6616 break;
6617
6618 power = rf1->count;
6619
6620 if (dump_file && (dump_flags & TDF_DETAILS))
6621 {
6622 unsigned elt;
6623 repeat_factor *rf;
6624 fputs ("Building __builtin_pow call for (", dump_file);
6625 for (elt = j; elt < vec_len; elt++)
6626 {
6627 rf = &repeat_factor_vec[elt];
6628 print_generic_expr (dump_file, rf->factor);
6629 if (elt < vec_len - 1)
6630 fputs (" * ", dump_file);
6631 }
6632 fprintf (dump_file, ")^" HOST_WIDE_INT_PRINT_DEC"\n", power);
6633 }
6634
6635 reassociate_stats.pows_created++;
6636
6637 /* Visit each element of the vector in reverse order (so that
6638 high-occurrence elements are visited first, and within the
6639 same occurrence count, lower-ranked elements are visited
6640 first). Form a linear product of all elements in this order
6641 whose occurrencce count is at least that of element J.
6642 Record the SSA name representing the product of each element
6643 with all subsequent elements in the vector. */
6644 if (j == vec_len - 1)
6645 rf1->repr = rf1->factor;
6646 else
6647 {
6648 for (ii = vec_len - 2; ii >= (int)j; ii--)
6649 {
6650 tree op1, op2;
6651
6652 rf1 = &repeat_factor_vec[ii];
6653 rf2 = &repeat_factor_vec[ii + 1];
6654
6655 /* Init the last factor's representative to be itself. */
6656 if (!rf2->repr)
6657 rf2->repr = rf2->factor;
6658
6659 op1 = rf1->factor;
6660 op2 = rf2->repr;
6661
6662 target_ssa = make_temp_ssa_name (type, NULL, "reassocpow");
6663 mul_stmt = gimple_build_assign (target_ssa, MULT_EXPR,
6664 op1, op2);
6665 gimple_set_location (mul_stmt, gimple_location (stmt));
6666 gimple_set_uid (mul_stmt, gimple_uid (stmt));
6667 gsi_insert_before (&gsi, mul_stmt, GSI_SAME_STMT);
6668 rf1->repr = target_ssa;
6669
6670 /* Don't reprocess the multiply we just introduced. */
6671 gimple_set_visited (mul_stmt, true);
6672 }
6673 }
6674
6675 /* Form a call to __builtin_powi for the maximum product
6676 just formed, raised to the power obtained earlier. */
6677 rf1 = &repeat_factor_vec[j];
6678 if (INTEGRAL_TYPE_P (type))
6679 {
6680 gcc_assert (power > 1);
6681 gimple_stmt_iterator gsip = gsi;
6682 gsi_prev (&gsip);
6683 iter_result = powi_as_mults (&gsi, gimple_location (stmt),
6684 rf1->repr, power);
6685 gimple_stmt_iterator gsic = gsi;
6686 while (gsi_stmt (gsic) != gsi_stmt (gsip))
6687 {
6688 gimple_set_uid (gsi_stmt (gsic), gimple_uid (stmt));
6689 gimple_set_visited (gsi_stmt (gsic), true);
6690 gsi_prev (&gsic);
6691 }
6692 }
6693 else
6694 {
6695 iter_result = make_temp_ssa_name (type, NULL, "reassocpow");
6696 pow_stmt = gimple_build_call (powi_fndecl, 2, rf1->repr,
6697 build_int_cst (integer_type_node,
6698 power));
6699 gimple_call_set_lhs (pow_stmt, iter_result);
6700 gimple_set_location (pow_stmt, gimple_location (stmt));
6701 gimple_set_uid (pow_stmt, gimple_uid (stmt));
6702 gsi_insert_before (&gsi, pow_stmt, GSI_SAME_STMT);
6703 }
6704 }
6705
6706 /* If we previously formed at least one other builtin_powi call,
6707 form the product of this one and those others. */
6708 if (result)
6709 {
6710 tree new_result = make_temp_ssa_name (type, NULL, "reassocpow");
6711 mul_stmt = gimple_build_assign (new_result, MULT_EXPR,
6712 result, iter_result);
6713 gimple_set_location (mul_stmt, gimple_location (stmt));
6714 gimple_set_uid (mul_stmt, gimple_uid (stmt));
6715 gsi_insert_before (&gsi, mul_stmt, GSI_SAME_STMT);
6716 gimple_set_visited (mul_stmt, true);
6717 result = new_result;
6718 }
6719 else
6720 result = iter_result;
6721
6722 /* Decrement the occurrence count of each element in the product
6723 by the count found above, and remove this many copies of each
6724 factor from OPS. */
6725 for (i = j; i < vec_len; i++)
6726 {
6727 unsigned k = power;
6728 unsigned n;
6729
6730 rf1 = &repeat_factor_vec[i];
6731 rf1->count -= power;
6732
6733 FOR_EACH_VEC_ELT_REVERSE (*ops, n, oe)
6734 {
6735 if (oe->op == rf1->factor)
6736 {
6737 if (oe->count <= k)
6738 {
6739 ops->ordered_remove (n);
6740 k -= oe->count;
6741
6742 if (k == 0)
6743 break;
6744 }
6745 else
6746 {
6747 oe->count -= k;
6748 break;
6749 }
6750 }
6751 }
6752 }
6753 }
6754
6755 /* At this point all elements in the repeated factor vector have a
6756 remaining occurrence count of 0 or 1, and those with a count of 1
6757 don't have cached representatives. Re-sort the ops vector and
6758 clean up. */
6759 ops->qsort (sort_by_operand_rank);
6760 repeat_factor_vec.release ();
6761
6762 /* Return the final product computed herein. Note that there may
6763 still be some elements with single occurrence count left in OPS;
6764 those will be handled by the normal reassociation logic. */
6765 return result;
6766 }
6767
6768 /* Attempt to optimize
6769 CST1 * copysign (CST2, y) -> copysign (CST1 * CST2, y) if CST1 > 0, or
6770 CST1 * copysign (CST2, y) -> -copysign (CST1 * CST2, y) if CST1 < 0. */
6771
6772 static void
6773 attempt_builtin_copysign (vec<operand_entry *> *ops)
6774 {
6775 operand_entry *oe;
6776 unsigned int i;
6777 unsigned int length = ops->length ();
6778 tree cst = ops->last ()->op;
6779
6780 if (length == 1 || TREE_CODE (cst) != REAL_CST)
6781 return;
6782
6783 FOR_EACH_VEC_ELT (*ops, i, oe)
6784 {
6785 if (TREE_CODE (oe->op) == SSA_NAME
6786 && has_single_use (oe->op))
6787 {
6788 gimple *def_stmt = SSA_NAME_DEF_STMT (oe->op);
6789 if (gcall *old_call = dyn_cast <gcall *> (def_stmt))
6790 {
6791 tree arg0, arg1;
6792 switch (gimple_call_combined_fn (old_call))
6793 {
6794 CASE_CFN_COPYSIGN:
6795 CASE_CFN_COPYSIGN_FN:
6796 arg0 = gimple_call_arg (old_call, 0);
6797 arg1 = gimple_call_arg (old_call, 1);
6798 /* The first argument of copysign must be a constant,
6799 otherwise there's nothing to do. */
6800 if (TREE_CODE (arg0) == REAL_CST)
6801 {
6802 tree type = TREE_TYPE (arg0);
6803 tree mul = const_binop (MULT_EXPR, type, cst, arg0);
6804 /* If we couldn't fold to a single constant, skip it.
6805 That happens e.g. for inexact multiplication when
6806 -frounding-math. */
6807 if (mul == NULL_TREE)
6808 break;
6809 /* Instead of adjusting OLD_CALL, let's build a new
6810 call to not leak the LHS and prevent keeping bogus
6811 debug statements. DCE will clean up the old call. */
6812 gcall *new_call;
6813 if (gimple_call_internal_p (old_call))
6814 new_call = gimple_build_call_internal
6815 (IFN_COPYSIGN, 2, mul, arg1);
6816 else
6817 new_call = gimple_build_call
6818 (gimple_call_fndecl (old_call), 2, mul, arg1);
6819 tree lhs = make_ssa_name (type);
6820 gimple_call_set_lhs (new_call, lhs);
6821 gimple_set_location (new_call,
6822 gimple_location (old_call));
6823 insert_stmt_after (new_call, old_call);
6824 /* We've used the constant, get rid of it. */
6825 ops->pop ();
6826 bool cst1_neg = real_isneg (TREE_REAL_CST_PTR (cst));
6827 /* Handle the CST1 < 0 case by negating the result. */
6828 if (cst1_neg)
6829 {
6830 tree negrhs = make_ssa_name (TREE_TYPE (lhs));
6831 gimple *negate_stmt
6832 = gimple_build_assign (negrhs, NEGATE_EXPR, lhs);
6833 insert_stmt_after (negate_stmt, new_call);
6834 oe->op = negrhs;
6835 }
6836 else
6837 oe->op = lhs;
6838 if (dump_file && (dump_flags & TDF_DETAILS))
6839 {
6840 fprintf (dump_file, "Optimizing copysign: ");
6841 print_generic_expr (dump_file, cst);
6842 fprintf (dump_file, " * COPYSIGN (");
6843 print_generic_expr (dump_file, arg0);
6844 fprintf (dump_file, ", ");
6845 print_generic_expr (dump_file, arg1);
6846 fprintf (dump_file, ") into %sCOPYSIGN (",
6847 cst1_neg ? "-" : "");
6848 print_generic_expr (dump_file, mul);
6849 fprintf (dump_file, ", ");
6850 print_generic_expr (dump_file, arg1);
6851 fprintf (dump_file, "\n");
6852 }
6853 return;
6854 }
6855 break;
6856 default:
6857 break;
6858 }
6859 }
6860 }
6861 }
6862 }
6863
6864 /* Transform STMT at *GSI into a copy by replacing its rhs with NEW_RHS. */
6865
6866 static void
6867 transform_stmt_to_copy (gimple_stmt_iterator *gsi, gimple *stmt, tree new_rhs)
6868 {
6869 tree rhs1;
6870
6871 if (dump_file && (dump_flags & TDF_DETAILS))
6872 {
6873 fprintf (dump_file, "Transforming ");
6874 print_gimple_stmt (dump_file, stmt, 0);
6875 }
6876
6877 rhs1 = gimple_assign_rhs1 (stmt);
6878 gimple_assign_set_rhs_from_tree (gsi, new_rhs);
6879 update_stmt (stmt);
6880 remove_visited_stmt_chain (rhs1);
6881
6882 if (dump_file && (dump_flags & TDF_DETAILS))
6883 {
6884 fprintf (dump_file, " into ");
6885 print_gimple_stmt (dump_file, stmt, 0);
6886 }
6887 }
6888
6889 /* Transform STMT at *GSI into a multiply of RHS1 and RHS2. */
6890
6891 static void
6892 transform_stmt_to_multiply (gimple_stmt_iterator *gsi, gimple *stmt,
6893 tree rhs1, tree rhs2)
6894 {
6895 if (dump_file && (dump_flags & TDF_DETAILS))
6896 {
6897 fprintf (dump_file, "Transforming ");
6898 print_gimple_stmt (dump_file, stmt, 0);
6899 }
6900
6901 gimple_assign_set_rhs_with_ops (gsi, MULT_EXPR, rhs1, rhs2);
6902 update_stmt (gsi_stmt (*gsi));
6903 remove_visited_stmt_chain (rhs1);
6904
6905 if (dump_file && (dump_flags & TDF_DETAILS))
6906 {
6907 fprintf (dump_file, " into ");
6908 print_gimple_stmt (dump_file, stmt, 0);
6909 }
6910 }
6911
6912 /* Rearrange ops may have more FMA when the chain may has more than 2 FMAs.
6913 Put no-mult ops and mult ops alternately at the end of the queue, which is
6914 conducive to generating more FMA and reducing the loss of FMA when breaking
6915 the chain.
6916 E.g.
6917 a * b + c * d + e generates:
6918
6919 _4 = c_9(D) * d_10(D);
6920 _12 = .FMA (a_7(D), b_8(D), _4);
6921 _11 = e_6(D) + _12;
6922
6923 Rearrange ops to -> e + a * b + c * d generates:
6924
6925 _4 = .FMA (c_7(D), d_8(D), _3);
6926 _11 = .FMA (a_5(D), b_6(D), _4);
6927
6928 Return the number of MULT_EXPRs in the chain. */
6929 static int
6930 rank_ops_for_fma (vec<operand_entry *> *ops)
6931 {
6932 operand_entry *oe;
6933 unsigned int i;
6934 unsigned int ops_length = ops->length ();
6935 auto_vec<operand_entry *> ops_mult;
6936 auto_vec<operand_entry *> ops_others;
6937
6938 FOR_EACH_VEC_ELT (*ops, i, oe)
6939 {
6940 if (TREE_CODE (oe->op) == SSA_NAME)
6941 {
6942 gimple *def_stmt = SSA_NAME_DEF_STMT (oe->op);
6943 if (is_gimple_assign (def_stmt))
6944 {
6945 if (gimple_assign_rhs_code (def_stmt) == MULT_EXPR)
6946 ops_mult.safe_push (oe);
6947 /* A negate on the multiplication leads to FNMA. */
6948 else if (gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR
6949 && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME)
6950 {
6951 gimple *neg_def_stmt
6952 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (def_stmt));
6953 if (is_gimple_assign (neg_def_stmt)
6954 && gimple_bb (neg_def_stmt) == gimple_bb (def_stmt)
6955 && gimple_assign_rhs_code (neg_def_stmt) == MULT_EXPR)
6956 ops_mult.safe_push (oe);
6957 else
6958 ops_others.safe_push (oe);
6959 }
6960 else
6961 ops_others.safe_push (oe);
6962 }
6963 else
6964 ops_others.safe_push (oe);
6965 }
6966 else
6967 ops_others.safe_push (oe);
6968 }
6969 /* 1. When ops_mult.length == 2, like the following case,
6970
6971 a * b + c * d + e.
6972
6973 we need to rearrange the ops.
6974
6975 Putting ops that not def from mult in front can generate more FMAs.
6976
6977 2. If all ops are defined with mult, we don't need to rearrange them. */
6978 unsigned mult_num = ops_mult.length ();
6979 if (mult_num >= 2 && mult_num != ops_length)
6980 {
6981 /* Put no-mult ops and mult ops alternately at the end of the
6982 queue, which is conducive to generating more FMA and reducing the
6983 loss of FMA when breaking the chain. */
6984 ops->truncate (0);
6985 ops->splice (ops_mult);
6986 int j, opindex = ops->length ();
6987 int others_length = ops_others.length ();
6988 for (j = 0; j < others_length; j++)
6989 {
6990 oe = ops_others.pop ();
6991 ops->quick_insert (opindex, oe);
6992 if (opindex > 0)
6993 opindex--;
6994 }
6995 }
6996 return mult_num;
6997 }
6998 /* Reassociate expressions in basic block BB and its post-dominator as
6999 children.
7000
7001 Bubble up return status from maybe_optimize_range_tests. */
7002
7003 static bool
7004 reassociate_bb (basic_block bb)
7005 {
7006 gimple_stmt_iterator gsi;
7007 gimple *stmt = last_nondebug_stmt (bb);
7008 bool cfg_cleanup_needed = false;
7009
7010 if (stmt && !gimple_visited_p (stmt))
7011 cfg_cleanup_needed |= maybe_optimize_range_tests (stmt);
7012
7013 bool do_prev = false;
7014 for (gsi = gsi_last_bb (bb);
7015 !gsi_end_p (gsi); do_prev ? gsi_prev (&gsi) : (void) 0)
7016 {
7017 do_prev = true;
7018 stmt = gsi_stmt (gsi);
7019
7020 if (is_gimple_assign (stmt)
7021 && !stmt_could_throw_p (cfun, stmt))
7022 {
7023 tree lhs, rhs1, rhs2;
7024 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
7025
7026 /* If this was part of an already processed statement,
7027 we don't need to touch it again. */
7028 if (gimple_visited_p (stmt))
7029 {
7030 /* This statement might have become dead because of previous
7031 reassociations. */
7032 if (has_zero_uses (gimple_get_lhs (stmt)))
7033 {
7034 reassoc_remove_stmt (&gsi);
7035 release_defs (stmt);
7036 /* We might end up removing the last stmt above which
7037 places the iterator to the end of the sequence.
7038 Reset it to the last stmt in this case and make sure
7039 we don't do gsi_prev in that case. */
7040 if (gsi_end_p (gsi))
7041 {
7042 gsi = gsi_last_bb (bb);
7043 do_prev = false;
7044 }
7045 }
7046 continue;
7047 }
7048
7049 /* If this is not a gimple binary expression, there is
7050 nothing for us to do with it. */
7051 if (get_gimple_rhs_class (rhs_code) != GIMPLE_BINARY_RHS)
7052 continue;
7053
7054 lhs = gimple_assign_lhs (stmt);
7055 rhs1 = gimple_assign_rhs1 (stmt);
7056 rhs2 = gimple_assign_rhs2 (stmt);
7057
7058 /* For non-bit or min/max operations we can't associate
7059 all types. Verify that here. */
7060 if ((rhs_code != BIT_IOR_EXPR
7061 && rhs_code != BIT_AND_EXPR
7062 && rhs_code != BIT_XOR_EXPR
7063 && rhs_code != MIN_EXPR
7064 && rhs_code != MAX_EXPR
7065 && !can_reassociate_type_p (TREE_TYPE (lhs)))
7066 || !can_reassociate_op_p (rhs1)
7067 || !can_reassociate_op_p (rhs2))
7068 continue;
7069
7070 if (associative_tree_code (rhs_code))
7071 {
7072 auto_vec<operand_entry *> ops;
7073 tree powi_result = NULL_TREE;
7074 bool is_vector = VECTOR_TYPE_P (TREE_TYPE (lhs));
7075
7076 /* There may be no immediate uses left by the time we
7077 get here because we may have eliminated them all. */
7078 if (TREE_CODE (lhs) == SSA_NAME && has_zero_uses (lhs))
7079 continue;
7080
7081 gimple_set_visited (stmt, true);
7082 linearize_expr_tree (&ops, stmt, true, true);
7083 ops.qsort (sort_by_operand_rank);
7084 int orig_len = ops.length ();
7085 optimize_ops_list (rhs_code, &ops);
7086 if (undistribute_ops_list (rhs_code, &ops,
7087 loop_containing_stmt (stmt)))
7088 {
7089 ops.qsort (sort_by_operand_rank);
7090 optimize_ops_list (rhs_code, &ops);
7091 }
7092 if (undistribute_bitref_for_vector (rhs_code, &ops,
7093 loop_containing_stmt (stmt)))
7094 {
7095 ops.qsort (sort_by_operand_rank);
7096 optimize_ops_list (rhs_code, &ops);
7097 }
7098 if (rhs_code == PLUS_EXPR
7099 && transform_add_to_multiply (&ops))
7100 ops.qsort (sort_by_operand_rank);
7101
7102 if (rhs_code == BIT_IOR_EXPR || rhs_code == BIT_AND_EXPR)
7103 {
7104 if (is_vector)
7105 optimize_vec_cond_expr (rhs_code, &ops);
7106 else
7107 optimize_range_tests (rhs_code, &ops, NULL);
7108 }
7109
7110 if (rhs_code == MULT_EXPR && !is_vector)
7111 {
7112 attempt_builtin_copysign (&ops);
7113
7114 if (reassoc_insert_powi_p
7115 && (flag_unsafe_math_optimizations
7116 || (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))))
7117 powi_result = attempt_builtin_powi (stmt, &ops);
7118 }
7119
7120 operand_entry *last;
7121 bool negate_result = false;
7122 if (ops.length () > 1
7123 && rhs_code == MULT_EXPR)
7124 {
7125 last = ops.last ();
7126 if ((integer_minus_onep (last->op)
7127 || real_minus_onep (last->op))
7128 && !HONOR_SNANS (TREE_TYPE (lhs))
7129 && (!HONOR_SIGNED_ZEROS (TREE_TYPE (lhs))
7130 || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (lhs))))
7131 {
7132 ops.pop ();
7133 negate_result = true;
7134 }
7135 }
7136
7137 tree new_lhs = lhs;
7138 /* If the operand vector is now empty, all operands were
7139 consumed by the __builtin_powi optimization. */
7140 if (ops.length () == 0)
7141 transform_stmt_to_copy (&gsi, stmt, powi_result);
7142 else if (ops.length () == 1)
7143 {
7144 tree last_op = ops.last ()->op;
7145
7146 /* If the stmt that defines operand has to be inserted, insert it
7147 before the use. */
7148 if (ops.last ()->stmt_to_insert)
7149 insert_stmt_before_use (stmt, ops.last ()->stmt_to_insert);
7150 if (powi_result)
7151 transform_stmt_to_multiply (&gsi, stmt, last_op,
7152 powi_result);
7153 else
7154 transform_stmt_to_copy (&gsi, stmt, last_op);
7155 }
7156 else
7157 {
7158 machine_mode mode = TYPE_MODE (TREE_TYPE (lhs));
7159 int ops_num = ops.length ();
7160 int width = 0;
7161 int mult_num = 0;
7162
7163 /* For binary bit operations, if there are at least 3
7164 operands and the last operand in OPS is a constant,
7165 move it to the front. This helps ensure that we generate
7166 (X & Y) & C rather than (X & C) & Y. The former will
7167 often match a canonical bit test when we get to RTL. */
7168 if (ops.length () > 2
7169 && (rhs_code == BIT_AND_EXPR
7170 || rhs_code == BIT_IOR_EXPR
7171 || rhs_code == BIT_XOR_EXPR)
7172 && TREE_CODE (ops.last ()->op) == INTEGER_CST)
7173 std::swap (*ops[0], *ops[ops_num - 1]);
7174
7175 optimization_type opt_type = bb_optimization_type (bb);
7176
7177 /* If the target support FMA, rank_ops_for_fma will detect if
7178 the chain has fmas and rearrange the ops if so. */
7179 if (direct_internal_fn_supported_p (IFN_FMA,
7180 TREE_TYPE (lhs),
7181 opt_type)
7182 && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
7183 {
7184 mult_num = rank_ops_for_fma (&ops);
7185 }
7186
7187 /* Only rewrite the expression tree to parallel in the
7188 last reassoc pass to avoid useless work back-and-forth
7189 with initial linearization. */
7190 bool has_fma = mult_num >= 2 && mult_num != ops_num;
7191 if (!reassoc_insert_powi_p
7192 && ops.length () > 3
7193 && (width = get_reassociation_width (&ops, mult_num, lhs,
7194 rhs_code, mode))
7195 > 1)
7196 {
7197 if (dump_file && (dump_flags & TDF_DETAILS))
7198 fprintf (dump_file,
7199 "Width = %d was chosen for reassociation\n",
7200 width);
7201 rewrite_expr_tree_parallel (as_a <gassign *> (stmt),
7202 width,
7203 has_fma,
7204 ops);
7205 }
7206 else
7207 {
7208 /* When there are three operands left, we want
7209 to make sure the ones that get the double
7210 binary op are chosen wisely. */
7211 int len = ops.length ();
7212 if (len >= 3
7213 && (!has_fma
7214 /* width > 1 means ranking ops results in better
7215 parallelism. Check current value to avoid
7216 calling get_reassociation_width again. */
7217 || (width != 1
7218 && get_reassociation_width (
7219 &ops, mult_num, lhs, rhs_code, mode)
7220 > 1)))
7221 swap_ops_for_binary_stmt (ops, len - 3);
7222
7223 new_lhs = rewrite_expr_tree (stmt, rhs_code, 0, ops,
7224 powi_result != NULL
7225 || negate_result,
7226 len != orig_len);
7227 }
7228
7229 /* If we combined some repeated factors into a
7230 __builtin_powi call, multiply that result by the
7231 reassociated operands. */
7232 if (powi_result)
7233 {
7234 gimple *mul_stmt, *lhs_stmt = SSA_NAME_DEF_STMT (lhs);
7235 tree type = TREE_TYPE (lhs);
7236 tree target_ssa = make_temp_ssa_name (type, NULL,
7237 "reassocpow");
7238 gimple_set_lhs (lhs_stmt, target_ssa);
7239 update_stmt (lhs_stmt);
7240 if (lhs != new_lhs)
7241 {
7242 target_ssa = new_lhs;
7243 new_lhs = lhs;
7244 }
7245 mul_stmt = gimple_build_assign (lhs, MULT_EXPR,
7246 powi_result, target_ssa);
7247 gimple_set_location (mul_stmt, gimple_location (stmt));
7248 gimple_set_uid (mul_stmt, gimple_uid (stmt));
7249 gsi_insert_after (&gsi, mul_stmt, GSI_NEW_STMT);
7250 }
7251 }
7252
7253 if (negate_result)
7254 {
7255 stmt = SSA_NAME_DEF_STMT (lhs);
7256 tree tmp = make_ssa_name (TREE_TYPE (lhs));
7257 gimple_set_lhs (stmt, tmp);
7258 if (lhs != new_lhs)
7259 tmp = new_lhs;
7260 gassign *neg_stmt = gimple_build_assign (lhs, NEGATE_EXPR,
7261 tmp);
7262 gimple_set_uid (neg_stmt, gimple_uid (stmt));
7263 gsi_insert_after (&gsi, neg_stmt, GSI_NEW_STMT);
7264 update_stmt (stmt);
7265 }
7266 }
7267 }
7268 }
7269
7270 return cfg_cleanup_needed;
7271 }
7272
7273 /* Add jumps around shifts for range tests turned into bit tests.
7274 For each SSA_NAME VAR we have code like:
7275 VAR = ...; // final stmt of range comparison
7276 // bit test here...;
7277 OTHERVAR = ...; // final stmt of the bit test sequence
7278 RES = VAR | OTHERVAR;
7279 Turn the above into:
7280 VAR = ...;
7281 if (VAR != 0)
7282 goto <l3>;
7283 else
7284 goto <l2>;
7285 <l2>:
7286 // bit test here...;
7287 OTHERVAR = ...;
7288 <l3>:
7289 # RES = PHI<1(l1), OTHERVAR(l2)>; */
7290
7291 static void
7292 branch_fixup (void)
7293 {
7294 tree var;
7295 unsigned int i;
7296
7297 FOR_EACH_VEC_ELT (reassoc_branch_fixups, i, var)
7298 {
7299 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
7300 gimple *use_stmt;
7301 use_operand_p use;
7302 bool ok = single_imm_use (var, &use, &use_stmt);
7303 gcc_assert (ok
7304 && is_gimple_assign (use_stmt)
7305 && gimple_assign_rhs_code (use_stmt) == BIT_IOR_EXPR
7306 && gimple_bb (def_stmt) == gimple_bb (use_stmt));
7307
7308 basic_block cond_bb = gimple_bb (def_stmt);
7309 basic_block then_bb = split_block (cond_bb, def_stmt)->dest;
7310 basic_block merge_bb = split_block (then_bb, use_stmt)->dest;
7311
7312 gimple_stmt_iterator gsi = gsi_for_stmt (def_stmt);
7313 gimple *g = gimple_build_cond (NE_EXPR, var,
7314 build_zero_cst (TREE_TYPE (var)),
7315 NULL_TREE, NULL_TREE);
7316 location_t loc = gimple_location (use_stmt);
7317 gimple_set_location (g, loc);
7318 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
7319
7320 edge etrue = make_edge (cond_bb, merge_bb, EDGE_TRUE_VALUE);
7321 etrue->probability = profile_probability::even ();
7322 edge efalse = find_edge (cond_bb, then_bb);
7323 efalse->flags = EDGE_FALSE_VALUE;
7324 efalse->probability -= etrue->probability;
7325 then_bb->count -= etrue->count ();
7326
7327 tree othervar = NULL_TREE;
7328 if (gimple_assign_rhs1 (use_stmt) == var)
7329 othervar = gimple_assign_rhs2 (use_stmt);
7330 else if (gimple_assign_rhs2 (use_stmt) == var)
7331 othervar = gimple_assign_rhs1 (use_stmt);
7332 else
7333 gcc_unreachable ();
7334 tree lhs = gimple_assign_lhs (use_stmt);
7335 gphi *phi = create_phi_node (lhs, merge_bb);
7336 add_phi_arg (phi, build_one_cst (TREE_TYPE (lhs)), etrue, loc);
7337 add_phi_arg (phi, othervar, single_succ_edge (then_bb), loc);
7338 gsi = gsi_for_stmt (use_stmt);
7339 gsi_remove (&gsi, true);
7340
7341 set_immediate_dominator (CDI_DOMINATORS, merge_bb, cond_bb);
7342 set_immediate_dominator (CDI_POST_DOMINATORS, cond_bb, merge_bb);
7343 }
7344 reassoc_branch_fixups.release ();
7345 }
7346
7347 void dump_ops_vector (FILE *file, vec<operand_entry *> ops);
7348 void debug_ops_vector (vec<operand_entry *> ops);
7349
7350 /* Dump the operand entry vector OPS to FILE. */
7351
7352 void
7353 dump_ops_vector (FILE *file, vec<operand_entry *> ops)
7354 {
7355 operand_entry *oe;
7356 unsigned int i;
7357
7358 FOR_EACH_VEC_ELT (ops, i, oe)
7359 {
7360 fprintf (file, "Op %d -> rank: %d, tree: ", i, oe->rank);
7361 print_generic_expr (file, oe->op);
7362 fprintf (file, "\n");
7363 }
7364 }
7365
7366 /* Dump the operand entry vector OPS to STDERR. */
7367
7368 DEBUG_FUNCTION void
7369 debug_ops_vector (vec<operand_entry *> ops)
7370 {
7371 dump_ops_vector (stderr, ops);
7372 }
7373
7374 /* Bubble up return status from reassociate_bb. */
7375
7376 static bool
7377 do_reassoc ()
7378 {
7379 bool cfg_cleanup_needed = false;
7380 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
7381
7382 unsigned sp = 0;
7383 for (auto son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
7384 son; son = next_dom_son (CDI_DOMINATORS, son))
7385 worklist[sp++] = son;
7386 while (sp)
7387 {
7388 basic_block bb = worklist[--sp];
7389 break_up_subtract_bb (bb);
7390 for (auto son = first_dom_son (CDI_DOMINATORS, bb);
7391 son; son = next_dom_son (CDI_DOMINATORS, son))
7392 worklist[sp++] = son;
7393 }
7394
7395 for (auto son = first_dom_son (CDI_POST_DOMINATORS,
7396 EXIT_BLOCK_PTR_FOR_FN (cfun));
7397 son; son = next_dom_son (CDI_POST_DOMINATORS, son))
7398 worklist[sp++] = son;
7399 while (sp)
7400 {
7401 basic_block bb = worklist[--sp];
7402 cfg_cleanup_needed |= reassociate_bb (bb);
7403 for (auto son = first_dom_son (CDI_POST_DOMINATORS, bb);
7404 son; son = next_dom_son (CDI_POST_DOMINATORS, son))
7405 worklist[sp++] = son;
7406 }
7407
7408 free (worklist);
7409 return cfg_cleanup_needed;
7410 }
7411
7412 /* Initialize the reassociation pass. */
7413
7414 static void
7415 init_reassoc (void)
7416 {
7417 int i;
7418 int64_t rank = 2;
7419 int *bbs = XNEWVEC (int, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
7420
7421 /* Find the loops, so that we can prevent moving calculations in
7422 them. */
7423 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
7424
7425 memset (&reassociate_stats, 0, sizeof (reassociate_stats));
7426
7427 next_operand_entry_id = 0;
7428
7429 /* Reverse RPO (Reverse Post Order) will give us something where
7430 deeper loops come later. */
7431 pre_and_rev_post_order_compute (NULL, bbs, false);
7432 bb_rank = XCNEWVEC (int64_t, last_basic_block_for_fn (cfun));
7433 operand_rank = new hash_map<tree, int64_t>;
7434
7435 /* Give each default definition a distinct rank. This includes
7436 parameters and the static chain. Walk backwards over all
7437 SSA names so that we get proper rank ordering according
7438 to tree_swap_operands_p. */
7439 for (i = num_ssa_names - 1; i > 0; --i)
7440 {
7441 tree name = ssa_name (i);
7442 if (name && SSA_NAME_IS_DEFAULT_DEF (name))
7443 insert_operand_rank (name, ++rank);
7444 }
7445
7446 /* Set up rank for each BB */
7447 for (i = 0; i < n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS; i++)
7448 bb_rank[bbs[i]] = ++rank << 16;
7449
7450 free (bbs);
7451 calculate_dominance_info (CDI_POST_DOMINATORS);
7452 plus_negates = vNULL;
7453 mark_ssa_maybe_undefs ();
7454 }
7455
7456 /* Cleanup after the reassociation pass, and print stats if
7457 requested. */
7458
7459 static void
7460 fini_reassoc (void)
7461 {
7462 statistics_counter_event (cfun, "Linearized",
7463 reassociate_stats.linearized);
7464 statistics_counter_event (cfun, "Constants eliminated",
7465 reassociate_stats.constants_eliminated);
7466 statistics_counter_event (cfun, "Ops eliminated",
7467 reassociate_stats.ops_eliminated);
7468 statistics_counter_event (cfun, "Statements rewritten",
7469 reassociate_stats.rewritten);
7470 statistics_counter_event (cfun, "Built-in pow[i] calls encountered",
7471 reassociate_stats.pows_encountered);
7472 statistics_counter_event (cfun, "Built-in powi calls created",
7473 reassociate_stats.pows_created);
7474
7475 delete operand_rank;
7476 bitmap_clear (biased_names);
7477 operand_entry_pool.release ();
7478 free (bb_rank);
7479 plus_negates.release ();
7480 free_dominance_info (CDI_POST_DOMINATORS);
7481 loop_optimizer_finalize ();
7482 }
7483
7484 /* Gate and execute functions for Reassociation. If INSERT_POWI_P, enable
7485 insertion of __builtin_powi calls.
7486
7487 Returns TODO_cfg_cleanup if a CFG cleanup pass is desired due to
7488 optimization of a gimple conditional. Otherwise returns zero. */
7489
7490 static unsigned int
7491 execute_reassoc (bool insert_powi_p, bool bias_loop_carried_phi_ranks_p)
7492 {
7493 reassoc_insert_powi_p = insert_powi_p;
7494 reassoc_bias_loop_carried_phi_ranks_p = bias_loop_carried_phi_ranks_p;
7495
7496 init_reassoc ();
7497
7498 bool cfg_cleanup_needed;
7499 cfg_cleanup_needed = do_reassoc ();
7500 repropagate_negates ();
7501 branch_fixup ();
7502
7503 fini_reassoc ();
7504 return cfg_cleanup_needed ? TODO_cleanup_cfg : 0;
7505 }
7506
7507 namespace {
7508
7509 const pass_data pass_data_reassoc =
7510 {
7511 GIMPLE_PASS, /* type */
7512 "reassoc", /* name */
7513 OPTGROUP_NONE, /* optinfo_flags */
7514 TV_TREE_REASSOC, /* tv_id */
7515 ( PROP_cfg | PROP_ssa ), /* properties_required */
7516 0, /* properties_provided */
7517 0, /* properties_destroyed */
7518 0, /* todo_flags_start */
7519 TODO_update_ssa_only_virtuals, /* todo_flags_finish */
7520 };
7521
7522 class pass_reassoc : public gimple_opt_pass
7523 {
7524 public:
7525 pass_reassoc (gcc::context *ctxt)
7526 : gimple_opt_pass (pass_data_reassoc, ctxt), insert_powi_p (false)
7527 {}
7528
7529 /* opt_pass methods: */
7530 opt_pass * clone () final override { return new pass_reassoc (m_ctxt); }
7531 void set_pass_param (unsigned int n, bool param) final override
7532 {
7533 gcc_assert (n == 0);
7534 insert_powi_p = param;
7535 bias_loop_carried_phi_ranks_p = !param;
7536 }
7537 bool gate (function *) final override { return flag_tree_reassoc != 0; }
7538 unsigned int execute (function *) final override
7539 {
7540 return execute_reassoc (insert_powi_p, bias_loop_carried_phi_ranks_p);
7541 }
7542
7543 private:
7544 /* Enable insertion of __builtin_powi calls during execute_reassoc. See
7545 point 3a in the pass header comment. */
7546 bool insert_powi_p;
7547 bool bias_loop_carried_phi_ranks_p;
7548 }; // class pass_reassoc
7549
7550 } // anon namespace
7551
7552 gimple_opt_pass *
7553 make_pass_reassoc (gcc::context *ctxt)
7554 {
7555 return new pass_reassoc (ctxt);
7556 }