tree-if-conv.c (add_bb_predicate_gimplified_stmts): Use gimple_seq_add_seq_without_up...
[platform/upstream/gcc.git] / gcc / tree-if-conv.c
1 /* If-conversion for vectorizer.
2    Copyright (C) 2004-2016 Free Software Foundation, Inc.
3    Contributed by Devang Patel <dpatel@apple.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 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 /* This pass implements a tree level if-conversion of loops.  Its
22    initial goal is to help the vectorizer to vectorize loops with
23    conditions.
24
25    A short description of if-conversion:
26
27      o Decide if a loop is if-convertible or not.
28      o Walk all loop basic blocks in breadth first order (BFS order).
29        o Remove conditional statements (at the end of basic block)
30          and propagate condition into destination basic blocks'
31          predicate list.
32        o Replace modify expression with conditional modify expression
33          using current basic block's condition.
34      o Merge all basic blocks
35        o Replace phi nodes with conditional modify expr
36        o Merge all basic blocks into header
37
38      Sample transformation:
39
40      INPUT
41      -----
42
43      # i_23 = PHI <0(0), i_18(10)>;
44      <L0>:;
45      j_15 = A[i_23];
46      if (j_15 > 41) goto <L1>; else goto <L17>;
47
48      <L17>:;
49      goto <bb 3> (<L3>);
50
51      <L1>:;
52
53      # iftmp.2_4 = PHI <0(8), 42(2)>;
54      <L3>:;
55      A[i_23] = iftmp.2_4;
56      i_18 = i_23 + 1;
57      if (i_18 <= 15) goto <L19>; else goto <L18>;
58
59      <L19>:;
60      goto <bb 1> (<L0>);
61
62      <L18>:;
63
64      OUTPUT
65      ------
66
67      # i_23 = PHI <0(0), i_18(10)>;
68      <L0>:;
69      j_15 = A[i_23];
70
71      <L3>:;
72      iftmp.2_4 = j_15 > 41 ? 42 : 0;
73      A[i_23] = iftmp.2_4;
74      i_18 = i_23 + 1;
75      if (i_18 <= 15) goto <L19>; else goto <L18>;
76
77      <L19>:;
78      goto <bb 1> (<L0>);
79
80      <L18>:;
81 */
82
83 #include "config.h"
84 #include "system.h"
85 #include "coretypes.h"
86 #include "backend.h"
87 #include "rtl.h"
88 #include "tree.h"
89 #include "gimple.h"
90 #include "cfghooks.h"
91 #include "tree-pass.h"
92 #include "ssa.h"
93 #include "expmed.h"
94 #include "optabs-query.h"
95 #include "gimple-pretty-print.h"
96 #include "alias.h"
97 #include "fold-const.h"
98 #include "stor-layout.h"
99 #include "gimple-fold.h"
100 #include "gimplify.h"
101 #include "gimple-iterator.h"
102 #include "gimplify-me.h"
103 #include "tree-cfg.h"
104 #include "tree-into-ssa.h"
105 #include "tree-ssa.h"
106 #include "cfgloop.h"
107 #include "tree-data-ref.h"
108 #include "tree-scalar-evolution.h"
109 #include "tree-ssa-loop.h"
110 #include "tree-ssa-loop-niter.h"
111 #include "tree-ssa-loop-ivopts.h"
112 #include "tree-ssa-address.h"
113 #include "dbgcnt.h"
114 #include "tree-hash-traits.h"
115 #include "varasm.h"
116 #include "builtins.h"
117 #include "params.h"
118 #include "cfganal.h"
119
120 /* Only handle PHIs with no more arguments unless we are asked to by
121    simd pragma.  */
122 #define MAX_PHI_ARG_NUM \
123   ((unsigned) PARAM_VALUE (PARAM_MAX_TREE_IF_CONVERSION_PHI_ARGS))
124
125 /* Indicate if new load/store that needs to be predicated is introduced
126    during if conversion.  */
127 static bool any_pred_load_store;
128
129 /* Indicate if there are any complicated PHIs that need to be handled in
130    if-conversion.  Complicated PHI has more than two arguments and can't
131    be degenerated to two arguments PHI.  See more information in comment
132    before phi_convertible_by_degenerating_args.  */
133 static bool any_complicated_phi;
134
135 /* Hash for struct innermost_loop_behavior.  It depends on the user to
136    free the memory.  */
137
138 struct innermost_loop_behavior_hash : nofree_ptr_hash <innermost_loop_behavior>
139 {
140   static inline hashval_t hash (const value_type &);
141   static inline bool equal (const value_type &,
142                             const compare_type &);
143 };
144
145 inline hashval_t
146 innermost_loop_behavior_hash::hash (const value_type &e)
147 {
148   hashval_t hash;
149
150   hash = iterative_hash_expr (e->base_address, 0);
151   hash = iterative_hash_expr (e->offset, hash);
152   hash = iterative_hash_expr (e->init, hash);
153   return iterative_hash_expr (e->step, hash);
154 }
155
156 inline bool
157 innermost_loop_behavior_hash::equal (const value_type &e1,
158                                      const compare_type &e2)
159 {
160   if ((e1->base_address && !e2->base_address)
161       || (!e1->base_address && e2->base_address)
162       || (!e1->offset && e2->offset)
163       || (e1->offset && !e2->offset)
164       || (!e1->init && e2->init)
165       || (e1->init && !e2->init)
166       || (!e1->step && e2->step)
167       || (e1->step && !e2->step))
168     return false;
169
170   if (e1->base_address && e2->base_address
171       && !operand_equal_p (e1->base_address, e2->base_address, 0))
172     return false;
173   if (e1->offset && e2->offset
174       && !operand_equal_p (e1->offset, e2->offset, 0))
175     return false;
176   if (e1->init && e2->init
177       && !operand_equal_p (e1->init, e2->init, 0))
178     return false;
179   if (e1->step && e2->step
180       && !operand_equal_p (e1->step, e2->step, 0))
181     return false;
182
183   return true;
184 }
185
186 /* List of basic blocks in if-conversion-suitable order.  */
187 static basic_block *ifc_bbs;
188
189 /* Hash table to store <DR's innermost loop behavior, DR> pairs.  */
190 static hash_map<innermost_loop_behavior_hash,
191                 data_reference_p> *innermost_DR_map;
192
193 /* Hash table to store <base reference, DR> pairs.  */
194 static hash_map<tree_operand_hash, data_reference_p> *baseref_DR_map;
195
196 /* Structure used to predicate basic blocks.  This is attached to the
197    ->aux field of the BBs in the loop to be if-converted.  */
198 struct bb_predicate {
199
200   /* The condition under which this basic block is executed.  */
201   tree predicate;
202
203   /* PREDICATE is gimplified, and the sequence of statements is
204      recorded here, in order to avoid the duplication of computations
205      that occur in previous conditions.  See PR44483.  */
206   gimple_seq predicate_gimplified_stmts;
207 };
208
209 /* Returns true when the basic block BB has a predicate.  */
210
211 static inline bool
212 bb_has_predicate (basic_block bb)
213 {
214   return bb->aux != NULL;
215 }
216
217 /* Returns the gimplified predicate for basic block BB.  */
218
219 static inline tree
220 bb_predicate (basic_block bb)
221 {
222   return ((struct bb_predicate *) bb->aux)->predicate;
223 }
224
225 /* Sets the gimplified predicate COND for basic block BB.  */
226
227 static inline void
228 set_bb_predicate (basic_block bb, tree cond)
229 {
230   gcc_assert ((TREE_CODE (cond) == TRUTH_NOT_EXPR
231                && is_gimple_condexpr (TREE_OPERAND (cond, 0)))
232               || is_gimple_condexpr (cond));
233   ((struct bb_predicate *) bb->aux)->predicate = cond;
234 }
235
236 /* Returns the sequence of statements of the gimplification of the
237    predicate for basic block BB.  */
238
239 static inline gimple_seq
240 bb_predicate_gimplified_stmts (basic_block bb)
241 {
242   return ((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts;
243 }
244
245 /* Sets the sequence of statements STMTS of the gimplification of the
246    predicate for basic block BB.  */
247
248 static inline void
249 set_bb_predicate_gimplified_stmts (basic_block bb, gimple_seq stmts)
250 {
251   ((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts = stmts;
252 }
253
254 /* Adds the sequence of statements STMTS to the sequence of statements
255    of the predicate for basic block BB.  */
256
257 static inline void
258 add_bb_predicate_gimplified_stmts (basic_block bb, gimple_seq stmts)
259 {
260   gimple_seq_add_seq_without_update
261     (&(((struct bb_predicate *) bb->aux)->predicate_gimplified_stmts), stmts);
262 }
263
264 /* Initializes to TRUE the predicate of basic block BB.  */
265
266 static inline void
267 init_bb_predicate (basic_block bb)
268 {
269   bb->aux = XNEW (struct bb_predicate);
270   set_bb_predicate_gimplified_stmts (bb, NULL);
271   set_bb_predicate (bb, boolean_true_node);
272 }
273
274 /* Release the SSA_NAMEs associated with the predicate of basic block BB,
275    but don't actually free it.  */
276
277 static inline void
278 release_bb_predicate (basic_block bb)
279 {
280   gimple_seq stmts = bb_predicate_gimplified_stmts (bb);
281   if (stmts)
282     {
283       if (flag_checking)
284         for (gimple_stmt_iterator i = gsi_start (stmts);
285              !gsi_end_p (i); gsi_next (&i))
286           gcc_assert (! gimple_use_ops (gsi_stmt (i)));
287
288       set_bb_predicate_gimplified_stmts (bb, NULL);
289     }
290 }
291
292 /* Free the predicate of basic block BB.  */
293
294 static inline void
295 free_bb_predicate (basic_block bb)
296 {
297   if (!bb_has_predicate (bb))
298     return;
299
300   release_bb_predicate (bb);
301   free (bb->aux);
302   bb->aux = NULL;
303 }
304
305 /* Reinitialize predicate of BB with the true predicate.  */
306
307 static inline void
308 reset_bb_predicate (basic_block bb)
309 {
310   if (!bb_has_predicate (bb))
311     init_bb_predicate (bb);
312   else
313     {
314       release_bb_predicate (bb);
315       set_bb_predicate (bb, boolean_true_node);
316     }
317 }
318
319 /* Returns a new SSA_NAME of type TYPE that is assigned the value of
320    the expression EXPR.  Inserts the statement created for this
321    computation before GSI and leaves the iterator GSI at the same
322    statement.  */
323
324 static tree
325 ifc_temp_var (tree type, tree expr, gimple_stmt_iterator *gsi)
326 {
327   tree new_name = make_temp_ssa_name (type, NULL, "_ifc_");
328   gimple *stmt = gimple_build_assign (new_name, expr);
329   gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
330   return new_name;
331 }
332
333 /* Return true when COND is a false predicate.  */
334
335 static inline bool
336 is_false_predicate (tree cond)
337 {
338   return (cond != NULL_TREE
339           && (cond == boolean_false_node
340               || integer_zerop (cond)));
341 }
342
343 /* Return true when COND is a true predicate.  */
344
345 static inline bool
346 is_true_predicate (tree cond)
347 {
348   return (cond == NULL_TREE
349           || cond == boolean_true_node
350           || integer_onep (cond));
351 }
352
353 /* Returns true when BB has a predicate that is not trivial: true or
354    NULL_TREE.  */
355
356 static inline bool
357 is_predicated (basic_block bb)
358 {
359   return !is_true_predicate (bb_predicate (bb));
360 }
361
362 /* Parses the predicate COND and returns its comparison code and
363    operands OP0 and OP1.  */
364
365 static enum tree_code
366 parse_predicate (tree cond, tree *op0, tree *op1)
367 {
368   gimple *s;
369
370   if (TREE_CODE (cond) == SSA_NAME
371       && is_gimple_assign (s = SSA_NAME_DEF_STMT (cond)))
372     {
373       if (TREE_CODE_CLASS (gimple_assign_rhs_code (s)) == tcc_comparison)
374         {
375           *op0 = gimple_assign_rhs1 (s);
376           *op1 = gimple_assign_rhs2 (s);
377           return gimple_assign_rhs_code (s);
378         }
379
380       else if (gimple_assign_rhs_code (s) == TRUTH_NOT_EXPR)
381         {
382           tree op = gimple_assign_rhs1 (s);
383           tree type = TREE_TYPE (op);
384           enum tree_code code = parse_predicate (op, op0, op1);
385
386           return code == ERROR_MARK ? ERROR_MARK
387             : invert_tree_comparison (code, HONOR_NANS (type));
388         }
389
390       return ERROR_MARK;
391     }
392
393   if (COMPARISON_CLASS_P (cond))
394     {
395       *op0 = TREE_OPERAND (cond, 0);
396       *op1 = TREE_OPERAND (cond, 1);
397       return TREE_CODE (cond);
398     }
399
400   return ERROR_MARK;
401 }
402
403 /* Returns the fold of predicate C1 OR C2 at location LOC.  */
404
405 static tree
406 fold_or_predicates (location_t loc, tree c1, tree c2)
407 {
408   tree op1a, op1b, op2a, op2b;
409   enum tree_code code1 = parse_predicate (c1, &op1a, &op1b);
410   enum tree_code code2 = parse_predicate (c2, &op2a, &op2b);
411
412   if (code1 != ERROR_MARK && code2 != ERROR_MARK)
413     {
414       tree t = maybe_fold_or_comparisons (code1, op1a, op1b,
415                                           code2, op2a, op2b);
416       if (t)
417         return t;
418     }
419
420   return fold_build2_loc (loc, TRUTH_OR_EXPR, boolean_type_node, c1, c2);
421 }
422
423 /* Returns either a COND_EXPR or the folded expression if the folded
424    expression is a MIN_EXPR, a MAX_EXPR, an ABS_EXPR,
425    a constant or a SSA_NAME. */
426
427 static tree
428 fold_build_cond_expr (tree type, tree cond, tree rhs, tree lhs)
429 {
430   tree rhs1, lhs1, cond_expr;
431
432   /* If COND is comparison r != 0 and r has boolean type, convert COND
433      to SSA_NAME to accept by vect bool pattern.  */
434   if (TREE_CODE (cond) == NE_EXPR)
435     {
436       tree op0 = TREE_OPERAND (cond, 0);
437       tree op1 = TREE_OPERAND (cond, 1);
438       if (TREE_CODE (op0) == SSA_NAME
439           && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
440           && (integer_zerop (op1)))
441         cond = op0;
442     }
443   cond_expr = fold_ternary (COND_EXPR, type, cond, rhs, lhs);
444
445   if (cond_expr == NULL_TREE)
446     return build3 (COND_EXPR, type, cond, rhs, lhs);
447
448   STRIP_USELESS_TYPE_CONVERSION (cond_expr);
449
450   if (is_gimple_val (cond_expr))
451     return cond_expr;
452
453   if (TREE_CODE (cond_expr) == ABS_EXPR)
454     {
455       rhs1 = TREE_OPERAND (cond_expr, 1);
456       STRIP_USELESS_TYPE_CONVERSION (rhs1);
457       if (is_gimple_val (rhs1))
458         return build1 (ABS_EXPR, type, rhs1);
459     }
460
461   if (TREE_CODE (cond_expr) == MIN_EXPR
462       || TREE_CODE (cond_expr) == MAX_EXPR)
463     {
464       lhs1 = TREE_OPERAND (cond_expr, 0);
465       STRIP_USELESS_TYPE_CONVERSION (lhs1);
466       rhs1 = TREE_OPERAND (cond_expr, 1);
467       STRIP_USELESS_TYPE_CONVERSION (rhs1);
468       if (is_gimple_val (rhs1) && is_gimple_val (lhs1))
469         return build2 (TREE_CODE (cond_expr), type, lhs1, rhs1);
470     }
471   return build3 (COND_EXPR, type, cond, rhs, lhs);
472 }
473
474 /* Add condition NC to the predicate list of basic block BB.  LOOP is
475    the loop to be if-converted. Use predicate of cd-equivalent block
476    for join bb if it exists: we call basic blocks bb1 and bb2 
477    cd-equivalent if they are executed under the same condition.  */
478
479 static inline void
480 add_to_predicate_list (struct loop *loop, basic_block bb, tree nc)
481 {
482   tree bc, *tp;
483   basic_block dom_bb;
484
485   if (is_true_predicate (nc))
486     return;
487
488   /* If dominance tells us this basic block is always executed,
489      don't record any predicates for it.  */
490   if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
491     return;
492
493   dom_bb = get_immediate_dominator (CDI_DOMINATORS, bb);
494   /* We use notion of cd equivalence to get simpler predicate for
495      join block, e.g. if join block has 2 predecessors with predicates
496      p1 & p2 and p1 & !p2, we'd like to get p1 for it instead of
497      p1 & p2 | p1 & !p2.  */
498   if (dom_bb != loop->header
499       && get_immediate_dominator (CDI_POST_DOMINATORS, dom_bb) == bb)
500     {
501       gcc_assert (flow_bb_inside_loop_p (loop, dom_bb));
502       bc = bb_predicate (dom_bb);
503       if (!is_true_predicate (bc))
504         set_bb_predicate (bb, bc);
505       else
506         gcc_assert (is_true_predicate (bb_predicate (bb)));
507       if (dump_file && (dump_flags & TDF_DETAILS))
508         fprintf (dump_file, "Use predicate of bb#%d for bb#%d\n",
509                  dom_bb->index, bb->index);
510       return;
511     }
512
513   if (!is_predicated (bb))
514     bc = nc;
515   else
516     {
517       bc = bb_predicate (bb);
518       bc = fold_or_predicates (EXPR_LOCATION (bc), nc, bc);
519       if (is_true_predicate (bc))
520         {
521           reset_bb_predicate (bb);
522           return;
523         }
524     }
525
526   /* Allow a TRUTH_NOT_EXPR around the main predicate.  */
527   if (TREE_CODE (bc) == TRUTH_NOT_EXPR)
528     tp = &TREE_OPERAND (bc, 0);
529   else
530     tp = &bc;
531   if (!is_gimple_condexpr (*tp))
532     {
533       gimple_seq stmts;
534       *tp = force_gimple_operand_1 (*tp, &stmts, is_gimple_condexpr, NULL_TREE);
535       add_bb_predicate_gimplified_stmts (bb, stmts);
536     }
537   set_bb_predicate (bb, bc);
538 }
539
540 /* Add the condition COND to the previous condition PREV_COND, and add
541    this to the predicate list of the destination of edge E.  LOOP is
542    the loop to be if-converted.  */
543
544 static void
545 add_to_dst_predicate_list (struct loop *loop, edge e,
546                            tree prev_cond, tree cond)
547 {
548   if (!flow_bb_inside_loop_p (loop, e->dest))
549     return;
550
551   if (!is_true_predicate (prev_cond))
552     cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
553                         prev_cond, cond);
554
555   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, e->dest))
556     add_to_predicate_list (loop, e->dest, cond);
557 }
558
559 /* Return true if one of the successor edges of BB exits LOOP.  */
560
561 static bool
562 bb_with_exit_edge_p (struct loop *loop, basic_block bb)
563 {
564   edge e;
565   edge_iterator ei;
566
567   FOR_EACH_EDGE (e, ei, bb->succs)
568     if (loop_exit_edge_p (loop, e))
569       return true;
570
571   return false;
572 }
573
574 /* Given PHI which has more than two arguments, this function checks if
575    it's if-convertible by degenerating its arguments.  Specifically, if
576    below two conditions are satisfied:
577
578      1) Number of PHI arguments with different values equals to 2 and one
579         argument has the only occurrence.
580      2) The edge corresponding to the unique argument isn't critical edge.
581
582    Such PHI can be handled as PHIs have only two arguments.  For example,
583    below PHI:
584
585      res = PHI <A_1(e1), A_1(e2), A_2(e3)>;
586
587    can be transformed into:
588
589      res = (predicate of e3) ? A_2 : A_1;
590
591    Return TRUE if it is the case, FALSE otherwise.  */
592
593 static bool
594 phi_convertible_by_degenerating_args (gphi *phi)
595 {
596   edge e;
597   tree arg, t1 = NULL, t2 = NULL;
598   unsigned int i, i1 = 0, i2 = 0, n1 = 0, n2 = 0;
599   unsigned int num_args = gimple_phi_num_args (phi);
600
601   gcc_assert (num_args > 2);
602
603   for (i = 0; i < num_args; i++)
604     {
605       arg = gimple_phi_arg_def (phi, i);
606       if (t1 == NULL || operand_equal_p (t1, arg, 0))
607         {
608           n1++;
609           i1 = i;
610           t1 = arg;
611         }
612       else if (t2 == NULL || operand_equal_p (t2, arg, 0))
613         {
614           n2++;
615           i2 = i;
616           t2 = arg;
617         }
618       else
619         return false;
620     }
621
622   if (n1 != 1 && n2 != 1)
623     return false;
624
625   /* Check if the edge corresponding to the unique arg is critical.  */
626   e = gimple_phi_arg_edge (phi, (n1 == 1) ? i1 : i2);
627   if (EDGE_COUNT (e->src->succs) > 1)
628     return false;
629
630   return true;
631 }
632
633 /* Return true when PHI is if-convertible.  PHI is part of loop LOOP
634    and it belongs to basic block BB.  Note at this point, it is sure
635    that PHI is if-convertible.  This function updates global variable
636    ANY_COMPLICATED_PHI if PHI is complicated.  */
637
638 static bool
639 if_convertible_phi_p (struct loop *loop, basic_block bb, gphi *phi)
640 {
641   if (dump_file && (dump_flags & TDF_DETAILS))
642     {
643       fprintf (dump_file, "-------------------------\n");
644       print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
645     }
646
647   if (bb != loop->header
648       && gimple_phi_num_args (phi) > 2
649       && !phi_convertible_by_degenerating_args (phi))
650     any_complicated_phi = true;
651
652   return true;
653 }
654
655 /* Records the status of a data reference.  This struct is attached to
656    each DR->aux field.  */
657
658 struct ifc_dr {
659   bool rw_unconditionally;
660   bool w_unconditionally;
661   bool written_at_least_once;
662
663   tree rw_predicate;
664   tree w_predicate;
665   tree base_w_predicate;
666 };
667
668 #define IFC_DR(DR) ((struct ifc_dr *) (DR)->aux)
669 #define DR_BASE_W_UNCONDITIONALLY(DR) (IFC_DR (DR)->written_at_least_once)
670 #define DR_RW_UNCONDITIONALLY(DR) (IFC_DR (DR)->rw_unconditionally)
671 #define DR_W_UNCONDITIONALLY(DR) (IFC_DR (DR)->w_unconditionally)
672
673 /* Iterates over DR's and stores refs, DR and base refs, DR pairs in
674    HASH tables.  While storing them in HASH table, it checks if the
675    reference is unconditionally read or written and stores that as a flag
676    information.  For base reference it checks if it is written atlest once
677    unconditionally and stores it as flag information along with DR.
678    In other words for every data reference A in STMT there exist other
679    accesses to a data reference with the same base with predicates that
680    add up (OR-up) to the true predicate: this ensures that the data
681    reference A is touched (read or written) on every iteration of the
682    if-converted loop.  */
683 static void
684 hash_memrefs_baserefs_and_store_DRs_read_written_info (data_reference_p a)
685 {
686
687   data_reference_p *master_dr, *base_master_dr;
688   tree base_ref = DR_BASE_OBJECT (a);
689   innermost_loop_behavior *innermost = &DR_INNERMOST (a);
690   tree ca = bb_predicate (gimple_bb (DR_STMT (a)));
691   bool exist1, exist2;
692
693   master_dr = &innermost_DR_map->get_or_insert (innermost, &exist1);
694   if (!exist1)
695     *master_dr = a;
696
697   if (DR_IS_WRITE (a))
698     {
699       IFC_DR (*master_dr)->w_predicate
700         = fold_or_predicates (UNKNOWN_LOCATION, ca,
701                               IFC_DR (*master_dr)->w_predicate);
702       if (is_true_predicate (IFC_DR (*master_dr)->w_predicate))
703         DR_W_UNCONDITIONALLY (*master_dr) = true;
704     }
705   IFC_DR (*master_dr)->rw_predicate
706     = fold_or_predicates (UNKNOWN_LOCATION, ca,
707                           IFC_DR (*master_dr)->rw_predicate);
708   if (is_true_predicate (IFC_DR (*master_dr)->rw_predicate))
709     DR_RW_UNCONDITIONALLY (*master_dr) = true;
710
711   if (DR_IS_WRITE (a))
712     {
713       base_master_dr = &baseref_DR_map->get_or_insert (base_ref, &exist2);
714       if (!exist2)
715         *base_master_dr = a;
716       IFC_DR (*base_master_dr)->base_w_predicate
717         = fold_or_predicates (UNKNOWN_LOCATION, ca,
718                               IFC_DR (*base_master_dr)->base_w_predicate);
719       if (is_true_predicate (IFC_DR (*base_master_dr)->base_w_predicate))
720         DR_BASE_W_UNCONDITIONALLY (*base_master_dr) = true;
721     }
722 }
723
724 /* Return TRUE if can prove the index IDX of an array reference REF is
725    within array bound.  Return false otherwise.  */
726
727 static bool
728 idx_within_array_bound (tree ref, tree *idx, void *dta)
729 {
730   bool overflow;
731   widest_int niter, valid_niter, delta, wi_step;
732   tree ev, init, step;
733   tree low, high;
734   struct loop *loop = (struct loop*) dta;
735
736   /* Only support within-bound access for array references.  */
737   if (TREE_CODE (ref) != ARRAY_REF)
738     return false;
739
740   /* For arrays at the end of the structure, we are not guaranteed that they
741      do not really extend over their declared size.  However, for arrays of
742      size greater than one, this is unlikely to be intended.  */
743   if (array_at_struct_end_p (ref))
744     return false;
745
746   ev = analyze_scalar_evolution (loop, *idx);
747   ev = instantiate_parameters (loop, ev);
748   init = initial_condition (ev);
749   step = evolution_part_in_loop_num (ev, loop->num);
750
751   if (!init || TREE_CODE (init) != INTEGER_CST
752       || (step && TREE_CODE (step) != INTEGER_CST))
753     return false;
754
755   low = array_ref_low_bound (ref);
756   high = array_ref_up_bound (ref);
757
758   /* The case of nonconstant bounds could be handled, but it would be
759      complicated.  */
760   if (TREE_CODE (low) != INTEGER_CST
761       || !high || TREE_CODE (high) != INTEGER_CST)
762     return false;
763
764   /* Check if the intial idx is within bound.  */
765   if (wi::to_widest (init) < wi::to_widest (low)
766       || wi::to_widest (init) > wi::to_widest (high))
767     return false;
768
769   /* The idx is always within bound.  */
770   if (!step || integer_zerop (step))
771     return true;
772
773   if (!max_loop_iterations (loop, &niter))
774     return false;
775
776   if (wi::to_widest (step) < 0)
777     {
778       delta = wi::to_widest (init) - wi::to_widest (low);
779       wi_step = -wi::to_widest (step);
780     }
781   else
782     {
783       delta = wi::to_widest (high) - wi::to_widest (init);
784       wi_step = wi::to_widest (step);
785     }
786
787   valid_niter = wi::div_floor (delta, wi_step, SIGNED, &overflow);
788   /* The iteration space of idx is within array bound.  */
789   if (!overflow && niter <= valid_niter)
790     return true;
791
792   return false;
793 }
794
795 /* Return TRUE if ref is a within bound array reference.  */
796
797 static bool
798 ref_within_array_bound (gimple *stmt, tree ref)
799 {
800   struct loop *loop = loop_containing_stmt (stmt);
801
802   gcc_assert (loop != NULL);
803   return for_each_index (&ref, idx_within_array_bound, loop);
804 }
805
806
807 /* Given a memory reference expression T, return TRUE if base object
808    it refers to is writable.  The base object of a memory reference
809    is the main object being referenced, which is returned by function
810    get_base_address.  */
811
812 static bool
813 base_object_writable (tree ref)
814 {
815   tree base_tree = get_base_address (ref);
816
817   return (base_tree
818           && DECL_P (base_tree)
819           && decl_binds_to_current_def_p (base_tree)
820           && !TREE_READONLY (base_tree));
821 }
822
823 /* Return true when the memory references of STMT won't trap in the
824    if-converted code.  There are two things that we have to check for:
825
826    - writes to memory occur to writable memory: if-conversion of
827    memory writes transforms the conditional memory writes into
828    unconditional writes, i.e. "if (cond) A[i] = foo" is transformed
829    into "A[i] = cond ? foo : A[i]", and as the write to memory may not
830    be executed at all in the original code, it may be a readonly
831    memory.  To check that A is not const-qualified, we check that
832    there exists at least an unconditional write to A in the current
833    function.
834
835    - reads or writes to memory are valid memory accesses for every
836    iteration.  To check that the memory accesses are correctly formed
837    and that we are allowed to read and write in these locations, we
838    check that the memory accesses to be if-converted occur at every
839    iteration unconditionally.
840
841    Returns true for the memory reference in STMT, same memory reference
842    is read or written unconditionally atleast once and the base memory
843    reference is written unconditionally once.  This is to check reference
844    will not write fault.  Also retuns true if the memory reference is
845    unconditionally read once then we are conditionally writing to memory
846    which is defined as read and write and is bound to the definition
847    we are seeing.  */
848 static bool
849 ifcvt_memrefs_wont_trap (gimple *stmt, vec<data_reference_p> drs)
850 {
851   data_reference_p *master_dr, *base_master_dr;
852   data_reference_p a = drs[gimple_uid (stmt) - 1];
853
854   tree base = DR_BASE_OBJECT (a);
855   innermost_loop_behavior *innermost = &DR_INNERMOST (a);
856
857   gcc_assert (DR_STMT (a) == stmt);
858   gcc_assert (DR_BASE_ADDRESS (a) || DR_OFFSET (a)
859               || DR_INIT (a) || DR_STEP (a));
860
861   master_dr = innermost_DR_map->get (innermost);
862   gcc_assert (master_dr != NULL);
863
864   base_master_dr = baseref_DR_map->get (base);
865
866   /* If a is unconditionally written to it doesn't trap.  */
867   if (DR_W_UNCONDITIONALLY (*master_dr))
868     return true;
869
870   /* If a is unconditionally accessed then ...
871
872      Even a is conditional access, we can treat it as an unconditional
873      one if it's an array reference and all its index are within array
874      bound.  */
875   if (DR_RW_UNCONDITIONALLY (*master_dr)
876       || ref_within_array_bound (stmt, DR_REF (a)))
877     {
878       /* an unconditional read won't trap.  */
879       if (DR_IS_READ (a))
880         return true;
881
882       /* an unconditionaly write won't trap if the base is written
883          to unconditionally.  */
884       if (base_master_dr
885           && DR_BASE_W_UNCONDITIONALLY (*base_master_dr))
886         return PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES);
887       /* or the base is known to be not readonly.  */
888       else if (base_object_writable (DR_REF (a)))
889         return PARAM_VALUE (PARAM_ALLOW_STORE_DATA_RACES);
890     }
891
892   return false;
893 }
894
895 /* Return true if STMT could be converted into a masked load or store
896    (conditional load or store based on a mask computed from bb predicate).  */
897
898 static bool
899 ifcvt_can_use_mask_load_store (gimple *stmt)
900 {
901   tree lhs, ref;
902   machine_mode mode;
903   basic_block bb = gimple_bb (stmt);
904   bool is_load;
905
906   if (!(flag_tree_loop_vectorize || bb->loop_father->force_vectorize)
907       || bb->loop_father->dont_vectorize
908       || !gimple_assign_single_p (stmt)
909       || gimple_has_volatile_ops (stmt))
910     return false;
911
912   /* Check whether this is a load or store.  */
913   lhs = gimple_assign_lhs (stmt);
914   if (gimple_store_p (stmt))
915     {
916       if (!is_gimple_val (gimple_assign_rhs1 (stmt)))
917         return false;
918       is_load = false;
919       ref = lhs;
920     }
921   else if (gimple_assign_load_p (stmt))
922     {
923       is_load = true;
924       ref = gimple_assign_rhs1 (stmt);
925     }
926   else
927     return false;
928
929   if (may_be_nonaddressable_p (ref))
930     return false;
931
932   /* Mask should be integer mode of the same size as the load/store
933      mode.  */
934   mode = TYPE_MODE (TREE_TYPE (lhs));
935   if (int_mode_for_mode (mode) == BLKmode
936       || VECTOR_MODE_P (mode))
937     return false;
938
939   if (can_vec_mask_load_store_p (mode, VOIDmode, is_load))
940     return true;
941
942   return false;
943 }
944
945 /* Return true when STMT is if-convertible.
946
947    GIMPLE_ASSIGN statement is not if-convertible if,
948    - it is not movable,
949    - it could trap,
950    - LHS is not var decl.  */
951
952 static bool
953 if_convertible_gimple_assign_stmt_p (gimple *stmt,
954                                      vec<data_reference_p> refs)
955 {
956   tree lhs = gimple_assign_lhs (stmt);
957
958   if (dump_file && (dump_flags & TDF_DETAILS))
959     {
960       fprintf (dump_file, "-------------------------\n");
961       print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
962     }
963
964   if (!is_gimple_reg_type (TREE_TYPE (lhs)))
965     return false;
966
967   /* Some of these constrains might be too conservative.  */
968   if (stmt_ends_bb_p (stmt)
969       || gimple_has_volatile_ops (stmt)
970       || (TREE_CODE (lhs) == SSA_NAME
971           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
972       || gimple_has_side_effects (stmt))
973     {
974       if (dump_file && (dump_flags & TDF_DETAILS))
975         fprintf (dump_file, "stmt not suitable for ifcvt\n");
976       return false;
977     }
978
979   /* tree-into-ssa.c uses GF_PLF_1, so avoid it, because
980      in between if_convertible_loop_p and combine_blocks
981      we can perform loop versioning.  */
982   gimple_set_plf (stmt, GF_PLF_2, false);
983
984   if ((! gimple_vuse (stmt)
985        || gimple_could_trap_p_1 (stmt, false, false)
986        || ! ifcvt_memrefs_wont_trap (stmt, refs))
987       && gimple_could_trap_p (stmt))
988     {
989       if (ifcvt_can_use_mask_load_store (stmt))
990         {
991           gimple_set_plf (stmt, GF_PLF_2, true);
992           any_pred_load_store = true;
993           return true;
994         }
995       if (dump_file && (dump_flags & TDF_DETAILS))
996         fprintf (dump_file, "tree could trap...\n");
997       return false;
998     }
999
1000   /* When if-converting stores force versioning, likewise if we
1001      ended up generating store data races.  */
1002   if (gimple_vdef (stmt))
1003     any_pred_load_store = true;
1004
1005   return true;
1006 }
1007
1008 /* Return true when STMT is if-convertible.
1009
1010    A statement is if-convertible if:
1011    - it is an if-convertible GIMPLE_ASSIGN,
1012    - it is a GIMPLE_LABEL or a GIMPLE_COND,
1013    - it is builtins call.  */
1014
1015 static bool
1016 if_convertible_stmt_p (gimple *stmt, vec<data_reference_p> refs)
1017 {
1018   switch (gimple_code (stmt))
1019     {
1020     case GIMPLE_LABEL:
1021     case GIMPLE_DEBUG:
1022     case GIMPLE_COND:
1023       return true;
1024
1025     case GIMPLE_ASSIGN:
1026       return if_convertible_gimple_assign_stmt_p (stmt, refs);
1027
1028     case GIMPLE_CALL:
1029       {
1030         tree fndecl = gimple_call_fndecl (stmt);
1031         if (fndecl)
1032           {
1033             int flags = gimple_call_flags (stmt);
1034             if ((flags & ECF_CONST)
1035                 && !(flags & ECF_LOOPING_CONST_OR_PURE)
1036                 /* We can only vectorize some builtins at the moment,
1037                    so restrict if-conversion to those.  */
1038                 && DECL_BUILT_IN (fndecl))
1039               return true;
1040           }
1041         return false;
1042       }
1043
1044     default:
1045       /* Don't know what to do with 'em so don't do anything.  */
1046       if (dump_file && (dump_flags & TDF_DETAILS))
1047         {
1048           fprintf (dump_file, "don't know what to do\n");
1049           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1050         }
1051       return false;
1052       break;
1053     }
1054
1055   return true;
1056 }
1057
1058 /* Assumes that BB has more than 1 predecessors.
1059    Returns false if at least one successor is not on critical edge
1060    and true otherwise.  */
1061
1062 static inline bool
1063 all_preds_critical_p (basic_block bb)
1064 {
1065   edge e;
1066   edge_iterator ei;
1067
1068   FOR_EACH_EDGE (e, ei, bb->preds)
1069     if (EDGE_COUNT (e->src->succs) == 1)
1070       return false;
1071   return true;
1072 }
1073
1074 /* Returns true if at least one successor in on critical edge.  */
1075 static inline bool
1076 has_pred_critical_p (basic_block bb)
1077 {
1078   edge e;
1079   edge_iterator ei;
1080
1081   FOR_EACH_EDGE (e, ei, bb->preds)
1082     if (EDGE_COUNT (e->src->succs) > 1)
1083       return true;
1084   return false;
1085 }
1086
1087 /* Return true when BB is if-convertible.  This routine does not check
1088    basic block's statements and phis.
1089
1090    A basic block is not if-convertible if:
1091    - it is non-empty and it is after the exit block (in BFS order),
1092    - it is after the exit block but before the latch,
1093    - its edges are not normal.
1094
1095    EXIT_BB is the basic block containing the exit of the LOOP.  BB is
1096    inside LOOP.  */
1097
1098 static bool
1099 if_convertible_bb_p (struct loop *loop, basic_block bb, basic_block exit_bb)
1100 {
1101   edge e;
1102   edge_iterator ei;
1103
1104   if (dump_file && (dump_flags & TDF_DETAILS))
1105     fprintf (dump_file, "----------[%d]-------------\n", bb->index);
1106
1107   if (EDGE_COUNT (bb->succs) > 2)
1108     return false;
1109
1110   if (exit_bb)
1111     {
1112       if (bb != loop->latch)
1113         {
1114           if (dump_file && (dump_flags & TDF_DETAILS))
1115             fprintf (dump_file, "basic block after exit bb but before latch\n");
1116           return false;
1117         }
1118       else if (!empty_block_p (bb))
1119         {
1120           if (dump_file && (dump_flags & TDF_DETAILS))
1121             fprintf (dump_file, "non empty basic block after exit bb\n");
1122           return false;
1123         }
1124       else if (bb == loop->latch
1125                && bb != exit_bb
1126                && !dominated_by_p (CDI_DOMINATORS, bb, exit_bb))
1127           {
1128             if (dump_file && (dump_flags & TDF_DETAILS))
1129               fprintf (dump_file, "latch is not dominated by exit_block\n");
1130             return false;
1131           }
1132     }
1133
1134   /* Be less adventurous and handle only normal edges.  */
1135   FOR_EACH_EDGE (e, ei, bb->succs)
1136     if (e->flags & (EDGE_EH | EDGE_ABNORMAL | EDGE_IRREDUCIBLE_LOOP))
1137       {
1138         if (dump_file && (dump_flags & TDF_DETAILS))
1139           fprintf (dump_file, "Difficult to handle edges\n");
1140         return false;
1141       }
1142
1143   return true;
1144 }
1145
1146 /* Return true when all predecessor blocks of BB are visited.  The
1147    VISITED bitmap keeps track of the visited blocks.  */
1148
1149 static bool
1150 pred_blocks_visited_p (basic_block bb, bitmap *visited)
1151 {
1152   edge e;
1153   edge_iterator ei;
1154   FOR_EACH_EDGE (e, ei, bb->preds)
1155     if (!bitmap_bit_p (*visited, e->src->index))
1156       return false;
1157
1158   return true;
1159 }
1160
1161 /* Get body of a LOOP in suitable order for if-conversion.  It is
1162    caller's responsibility to deallocate basic block list.
1163    If-conversion suitable order is, breadth first sort (BFS) order
1164    with an additional constraint: select a block only if all its
1165    predecessors are already selected.  */
1166
1167 static basic_block *
1168 get_loop_body_in_if_conv_order (const struct loop *loop)
1169 {
1170   basic_block *blocks, *blocks_in_bfs_order;
1171   basic_block bb;
1172   bitmap visited;
1173   unsigned int index = 0;
1174   unsigned int visited_count = 0;
1175
1176   gcc_assert (loop->num_nodes);
1177   gcc_assert (loop->latch != EXIT_BLOCK_PTR_FOR_FN (cfun));
1178
1179   blocks = XCNEWVEC (basic_block, loop->num_nodes);
1180   visited = BITMAP_ALLOC (NULL);
1181
1182   blocks_in_bfs_order = get_loop_body_in_bfs_order (loop);
1183
1184   index = 0;
1185   while (index < loop->num_nodes)
1186     {
1187       bb = blocks_in_bfs_order [index];
1188
1189       if (bb->flags & BB_IRREDUCIBLE_LOOP)
1190         {
1191           free (blocks_in_bfs_order);
1192           BITMAP_FREE (visited);
1193           free (blocks);
1194           return NULL;
1195         }
1196
1197       if (!bitmap_bit_p (visited, bb->index))
1198         {
1199           if (pred_blocks_visited_p (bb, &visited)
1200               || bb == loop->header)
1201             {
1202               /* This block is now visited.  */
1203               bitmap_set_bit (visited, bb->index);
1204               blocks[visited_count++] = bb;
1205             }
1206         }
1207
1208       index++;
1209
1210       if (index == loop->num_nodes
1211           && visited_count != loop->num_nodes)
1212         /* Not done yet.  */
1213         index = 0;
1214     }
1215   free (blocks_in_bfs_order);
1216   BITMAP_FREE (visited);
1217   return blocks;
1218 }
1219
1220 /* Returns true when the analysis of the predicates for all the basic
1221    blocks in LOOP succeeded.
1222
1223    predicate_bbs first allocates the predicates of the basic blocks.
1224    These fields are then initialized with the tree expressions
1225    representing the predicates under which a basic block is executed
1226    in the LOOP.  As the loop->header is executed at each iteration, it
1227    has the "true" predicate.  Other statements executed under a
1228    condition are predicated with that condition, for example
1229
1230    | if (x)
1231    |   S1;
1232    | else
1233    |   S2;
1234
1235    S1 will be predicated with "x", and
1236    S2 will be predicated with "!x".  */
1237
1238 static void
1239 predicate_bbs (loop_p loop)
1240 {
1241   unsigned int i;
1242
1243   for (i = 0; i < loop->num_nodes; i++)
1244     init_bb_predicate (ifc_bbs[i]);
1245
1246   for (i = 0; i < loop->num_nodes; i++)
1247     {
1248       basic_block bb = ifc_bbs[i];
1249       tree cond;
1250       gimple *stmt;
1251
1252       /* The loop latch and loop exit block are always executed and
1253          have no extra conditions to be processed: skip them.  */
1254       if (bb == loop->latch
1255           || bb_with_exit_edge_p (loop, bb))
1256         {
1257           reset_bb_predicate (bb);
1258           continue;
1259         }
1260
1261       cond = bb_predicate (bb);
1262       stmt = last_stmt (bb);
1263       if (stmt && gimple_code (stmt) == GIMPLE_COND)
1264         {
1265           tree c2;
1266           edge true_edge, false_edge;
1267           location_t loc = gimple_location (stmt);
1268           tree c = build2_loc (loc, gimple_cond_code (stmt),
1269                                     boolean_type_node,
1270                                     gimple_cond_lhs (stmt),
1271                                     gimple_cond_rhs (stmt));
1272
1273           /* Add new condition into destination's predicate list.  */
1274           extract_true_false_edges_from_block (gimple_bb (stmt),
1275                                                &true_edge, &false_edge);
1276
1277           /* If C is true, then TRUE_EDGE is taken.  */
1278           add_to_dst_predicate_list (loop, true_edge, unshare_expr (cond),
1279                                      unshare_expr (c));
1280
1281           /* If C is false, then FALSE_EDGE is taken.  */
1282           c2 = build1_loc (loc, TRUTH_NOT_EXPR, boolean_type_node,
1283                            unshare_expr (c));
1284           add_to_dst_predicate_list (loop, false_edge,
1285                                      unshare_expr (cond), c2);
1286
1287           cond = NULL_TREE;
1288         }
1289
1290       /* If current bb has only one successor, then consider it as an
1291          unconditional goto.  */
1292       if (single_succ_p (bb))
1293         {
1294           basic_block bb_n = single_succ (bb);
1295
1296           /* The successor bb inherits the predicate of its
1297              predecessor.  If there is no predicate in the predecessor
1298              bb, then consider the successor bb as always executed.  */
1299           if (cond == NULL_TREE)
1300             cond = boolean_true_node;
1301
1302           add_to_predicate_list (loop, bb_n, cond);
1303         }
1304     }
1305
1306   /* The loop header is always executed.  */
1307   reset_bb_predicate (loop->header);
1308   gcc_assert (bb_predicate_gimplified_stmts (loop->header) == NULL
1309               && bb_predicate_gimplified_stmts (loop->latch) == NULL);
1310 }
1311
1312 /* Return true when LOOP is if-convertible.  This is a helper function
1313    for if_convertible_loop_p.  REFS and DDRS are initialized and freed
1314    in if_convertible_loop_p.  */
1315
1316 static bool
1317 if_convertible_loop_p_1 (struct loop *loop, vec<data_reference_p> *refs)
1318 {
1319   unsigned int i;
1320   basic_block exit_bb = NULL;
1321
1322   if (find_data_references_in_loop (loop, refs) == chrec_dont_know)
1323     return false;
1324
1325   calculate_dominance_info (CDI_DOMINATORS);
1326
1327   /* Allow statements that can be handled during if-conversion.  */
1328   ifc_bbs = get_loop_body_in_if_conv_order (loop);
1329   if (!ifc_bbs)
1330     {
1331       if (dump_file && (dump_flags & TDF_DETAILS))
1332         fprintf (dump_file, "Irreducible loop\n");
1333       return false;
1334     }
1335
1336   for (i = 0; i < loop->num_nodes; i++)
1337     {
1338       basic_block bb = ifc_bbs[i];
1339
1340       if (!if_convertible_bb_p (loop, bb, exit_bb))
1341         return false;
1342
1343       if (bb_with_exit_edge_p (loop, bb))
1344         exit_bb = bb;
1345     }
1346
1347   for (i = 0; i < loop->num_nodes; i++)
1348     {
1349       basic_block bb = ifc_bbs[i];
1350       gimple_stmt_iterator gsi;
1351
1352       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1353         switch (gimple_code (gsi_stmt (gsi)))
1354           {
1355           case GIMPLE_LABEL:
1356           case GIMPLE_ASSIGN:
1357           case GIMPLE_CALL:
1358           case GIMPLE_DEBUG:
1359           case GIMPLE_COND:
1360             gimple_set_uid (gsi_stmt (gsi), 0);
1361             break;
1362           default:
1363             return false;
1364           }
1365     }
1366
1367   data_reference_p dr;
1368
1369   innermost_DR_map
1370           = new hash_map<innermost_loop_behavior_hash, data_reference_p>;
1371   baseref_DR_map = new hash_map<tree_operand_hash, data_reference_p>;
1372
1373   calculate_dominance_info (CDI_POST_DOMINATORS);
1374   predicate_bbs (loop);
1375
1376   for (i = 0; refs->iterate (i, &dr); i++)
1377     {
1378       tree ref = DR_REF (dr);
1379
1380       dr->aux = XNEW (struct ifc_dr);
1381       DR_BASE_W_UNCONDITIONALLY (dr) = false;
1382       DR_RW_UNCONDITIONALLY (dr) = false;
1383       DR_W_UNCONDITIONALLY (dr) = false;
1384       IFC_DR (dr)->rw_predicate = boolean_false_node;
1385       IFC_DR (dr)->w_predicate = boolean_false_node;
1386       IFC_DR (dr)->base_w_predicate = boolean_false_node;
1387       if (gimple_uid (DR_STMT (dr)) == 0)
1388         gimple_set_uid (DR_STMT (dr), i + 1);
1389
1390       /* If DR doesn't have innermost loop behavior or it's a compound
1391          memory reference, we synthesize its innermost loop behavior
1392          for hashing.  */
1393       if (TREE_CODE (ref) == COMPONENT_REF
1394           || TREE_CODE (ref) == IMAGPART_EXPR
1395           || TREE_CODE (ref) == REALPART_EXPR
1396           || !(DR_BASE_ADDRESS (dr) || DR_OFFSET (dr)
1397                || DR_INIT (dr) || DR_STEP (dr)))
1398         {
1399           while (TREE_CODE (ref) == COMPONENT_REF
1400                  || TREE_CODE (ref) == IMAGPART_EXPR
1401                  || TREE_CODE (ref) == REALPART_EXPR)
1402             ref = TREE_OPERAND (ref, 0);
1403
1404           DR_BASE_ADDRESS (dr) = ref;
1405           DR_OFFSET (dr) = NULL;
1406           DR_INIT (dr) = NULL;
1407           DR_STEP (dr) = NULL;
1408           DR_ALIGNED_TO (dr) = NULL;
1409         }
1410       hash_memrefs_baserefs_and_store_DRs_read_written_info (dr);
1411     }
1412
1413   for (i = 0; i < loop->num_nodes; i++)
1414     {
1415       basic_block bb = ifc_bbs[i];
1416       gimple_stmt_iterator itr;
1417
1418       /* Check the if-convertibility of statements in predicated BBs.  */
1419       if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
1420         for (itr = gsi_start_bb (bb); !gsi_end_p (itr); gsi_next (&itr))
1421           if (!if_convertible_stmt_p (gsi_stmt (itr), *refs))
1422             return false;
1423     }
1424
1425   /* Checking PHIs needs to be done after stmts, as the fact whether there
1426      are any masked loads or stores affects the tests.  */
1427   for (i = 0; i < loop->num_nodes; i++)
1428     {
1429       basic_block bb = ifc_bbs[i];
1430       gphi_iterator itr;
1431
1432       for (itr = gsi_start_phis (bb); !gsi_end_p (itr); gsi_next (&itr))
1433         if (!if_convertible_phi_p (loop, bb, itr.phi ()))
1434           return false;
1435     }
1436
1437   if (dump_file)
1438     fprintf (dump_file, "Applying if-conversion\n");
1439
1440   return true;
1441 }
1442
1443 /* Return true when LOOP is if-convertible.
1444    LOOP is if-convertible if:
1445    - it is innermost,
1446    - it has two or more basic blocks,
1447    - it has only one exit,
1448    - loop header is not the exit edge,
1449    - if its basic blocks and phi nodes are if convertible.  */
1450
1451 static bool
1452 if_convertible_loop_p (struct loop *loop)
1453 {
1454   edge e;
1455   edge_iterator ei;
1456   bool res = false;
1457   vec<data_reference_p> refs;
1458
1459   /* Handle only innermost loop.  */
1460   if (!loop || loop->inner)
1461     {
1462       if (dump_file && (dump_flags & TDF_DETAILS))
1463         fprintf (dump_file, "not innermost loop\n");
1464       return false;
1465     }
1466
1467   /* If only one block, no need for if-conversion.  */
1468   if (loop->num_nodes <= 2)
1469     {
1470       if (dump_file && (dump_flags & TDF_DETAILS))
1471         fprintf (dump_file, "less than 2 basic blocks\n");
1472       return false;
1473     }
1474
1475   /* More than one loop exit is too much to handle.  */
1476   if (!single_exit (loop))
1477     {
1478       if (dump_file && (dump_flags & TDF_DETAILS))
1479         fprintf (dump_file, "multiple exits\n");
1480       return false;
1481     }
1482
1483   /* If one of the loop header's edge is an exit edge then do not
1484      apply if-conversion.  */
1485   FOR_EACH_EDGE (e, ei, loop->header->succs)
1486     if (loop_exit_edge_p (loop, e))
1487       return false;
1488
1489   refs.create (5);
1490   res = if_convertible_loop_p_1 (loop, &refs);
1491
1492   data_reference_p dr;
1493   unsigned int i;
1494   for (i = 0; refs.iterate (i, &dr); i++)
1495     free (dr->aux);
1496
1497   free_data_refs (refs);
1498
1499   delete innermost_DR_map;
1500   innermost_DR_map = NULL;
1501
1502   delete baseref_DR_map;
1503   baseref_DR_map = NULL;
1504
1505   return res;
1506 }
1507
1508 /* Returns true if def-stmt for phi argument ARG is simple increment/decrement
1509    which is in predicated basic block.
1510    In fact, the following PHI pattern is searching:
1511       loop-header:
1512         reduc_1 = PHI <..., reduc_2>
1513       ...
1514         if (...)
1515           reduc_3 = ...
1516         reduc_2 = PHI <reduc_1, reduc_3>
1517
1518    ARG_0 and ARG_1 are correspondent PHI arguments.
1519    REDUC, OP0 and OP1 contain reduction stmt and its operands.
1520    EXTENDED is true if PHI has > 2 arguments.  */
1521
1522 static bool
1523 is_cond_scalar_reduction (gimple *phi, gimple **reduc, tree arg_0, tree arg_1,
1524                           tree *op0, tree *op1, bool extended)
1525 {
1526   tree lhs, r_op1, r_op2;
1527   gimple *stmt;
1528   gimple *header_phi = NULL;
1529   enum tree_code reduction_op;
1530   basic_block bb = gimple_bb (phi);
1531   struct loop *loop = bb->loop_father;
1532   edge latch_e = loop_latch_edge (loop);
1533   imm_use_iterator imm_iter;
1534   use_operand_p use_p;
1535   edge e;
1536   edge_iterator ei;
1537   bool result = false;
1538   if (TREE_CODE (arg_0) != SSA_NAME || TREE_CODE (arg_1) != SSA_NAME)
1539     return false;
1540
1541   if (!extended && gimple_code (SSA_NAME_DEF_STMT (arg_0)) == GIMPLE_PHI)
1542     {
1543       lhs = arg_1;
1544       header_phi = SSA_NAME_DEF_STMT (arg_0);
1545       stmt = SSA_NAME_DEF_STMT (arg_1);
1546     }
1547   else if (gimple_code (SSA_NAME_DEF_STMT (arg_1)) == GIMPLE_PHI)
1548     {
1549       lhs = arg_0;
1550       header_phi = SSA_NAME_DEF_STMT (arg_1);
1551       stmt = SSA_NAME_DEF_STMT (arg_0);
1552     }
1553   else
1554     return false;
1555   if (gimple_bb (header_phi) != loop->header)
1556     return false;
1557
1558   if (PHI_ARG_DEF_FROM_EDGE (header_phi, latch_e) != PHI_RESULT (phi))
1559     return false;
1560
1561   if (gimple_code (stmt) != GIMPLE_ASSIGN
1562       || gimple_has_volatile_ops (stmt))
1563     return false;
1564
1565   if (!flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
1566     return false;
1567
1568   if (!is_predicated (gimple_bb (stmt)))
1569     return false;
1570
1571   /* Check that stmt-block is predecessor of phi-block.  */
1572   FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
1573     if (e->dest == bb)
1574       {
1575         result = true;
1576         break;
1577       }
1578   if (!result)
1579     return false;
1580
1581   if (!has_single_use (lhs))
1582     return false;
1583
1584   reduction_op = gimple_assign_rhs_code (stmt);
1585   if (reduction_op != PLUS_EXPR && reduction_op != MINUS_EXPR)
1586     return false;
1587   r_op1 = gimple_assign_rhs1 (stmt);
1588   r_op2 = gimple_assign_rhs2 (stmt);
1589
1590   /* Make R_OP1 to hold reduction variable.  */
1591   if (r_op2 == PHI_RESULT (header_phi)
1592       && reduction_op == PLUS_EXPR)
1593     std::swap (r_op1, r_op2);
1594   else if (r_op1 != PHI_RESULT (header_phi))
1595     return false;
1596
1597   /* Check that R_OP1 is used in reduction stmt or in PHI only.  */
1598   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, r_op1)
1599     {
1600       gimple *use_stmt = USE_STMT (use_p);
1601       if (is_gimple_debug (use_stmt))
1602         continue;
1603       if (use_stmt == stmt)
1604         continue;
1605       if (gimple_code (use_stmt) != GIMPLE_PHI)
1606         return false;
1607     }
1608
1609   *op0 = r_op1; *op1 = r_op2;
1610   *reduc = stmt;
1611   return true;
1612 }
1613
1614 /* Converts conditional scalar reduction into unconditional form, e.g.
1615      bb_4
1616        if (_5 != 0) goto bb_5 else goto bb_6
1617      end_bb_4
1618      bb_5
1619        res_6 = res_13 + 1;
1620      end_bb_5
1621      bb_6
1622        # res_2 = PHI <res_13(4), res_6(5)>
1623      end_bb_6
1624
1625    will be converted into sequence
1626     _ifc__1 = _5 != 0 ? 1 : 0;
1627     res_2 = res_13 + _ifc__1;
1628   Argument SWAP tells that arguments of conditional expression should be
1629   swapped.
1630   Returns rhs of resulting PHI assignment.  */
1631
1632 static tree
1633 convert_scalar_cond_reduction (gimple *reduc, gimple_stmt_iterator *gsi,
1634                                tree cond, tree op0, tree op1, bool swap)
1635 {
1636   gimple_stmt_iterator stmt_it;
1637   gimple *new_assign;
1638   tree rhs;
1639   tree rhs1 = gimple_assign_rhs1 (reduc);
1640   tree tmp = make_temp_ssa_name (TREE_TYPE (rhs1), NULL, "_ifc_");
1641   tree c;
1642   tree zero = build_zero_cst (TREE_TYPE (rhs1));
1643
1644   if (dump_file && (dump_flags & TDF_DETAILS))
1645     {
1646       fprintf (dump_file, "Found cond scalar reduction.\n");
1647       print_gimple_stmt (dump_file, reduc, 0, TDF_SLIM);
1648     }
1649
1650   /* Build cond expression using COND and constant operand
1651      of reduction rhs.  */
1652   c = fold_build_cond_expr (TREE_TYPE (rhs1),
1653                             unshare_expr (cond),
1654                             swap ? zero : op1,
1655                             swap ? op1 : zero);
1656
1657   /* Create assignment stmt and insert it at GSI.  */
1658   new_assign = gimple_build_assign (tmp, c);
1659   gsi_insert_before (gsi, new_assign, GSI_SAME_STMT);
1660   /* Build rhs for unconditional increment/decrement.  */
1661   rhs = fold_build2 (gimple_assign_rhs_code (reduc),
1662                      TREE_TYPE (rhs1), op0, tmp);
1663
1664   /* Delete original reduction stmt.  */
1665   stmt_it = gsi_for_stmt (reduc);
1666   gsi_remove (&stmt_it, true);
1667   release_defs (reduc);
1668   return rhs;
1669 }
1670
1671 /* Produce condition for all occurrences of ARG in PHI node.  */
1672
1673 static tree
1674 gen_phi_arg_condition (gphi *phi, vec<int> *occur,
1675                        gimple_stmt_iterator *gsi)
1676 {
1677   int len;
1678   int i;
1679   tree cond = NULL_TREE;
1680   tree c;
1681   edge e;
1682
1683   len = occur->length ();
1684   gcc_assert (len > 0);
1685   for (i = 0; i < len; i++)
1686     {
1687       e = gimple_phi_arg_edge (phi, (*occur)[i]);
1688       c = bb_predicate (e->src);
1689       if (is_true_predicate (c))
1690         continue;
1691       c = force_gimple_operand_gsi_1 (gsi, unshare_expr (c),
1692                                       is_gimple_condexpr, NULL_TREE,
1693                                       true, GSI_SAME_STMT);
1694       if (cond != NULL_TREE)
1695         {
1696           /* Must build OR expression.  */
1697           cond = fold_or_predicates (EXPR_LOCATION (c), c, cond);
1698           cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1699                                              is_gimple_condexpr, NULL_TREE,
1700                                              true, GSI_SAME_STMT);
1701         }
1702       else
1703         cond = c;
1704     }
1705   gcc_assert (cond != NULL_TREE);
1706   return cond;
1707 }
1708
1709 /* Replace a scalar PHI node with a COND_EXPR using COND as condition.
1710    This routine can handle PHI nodes with more than two arguments.
1711
1712    For example,
1713      S1: A = PHI <x1(1), x2(5)>
1714    is converted into,
1715      S2: A = cond ? x1 : x2;
1716
1717    The generated code is inserted at GSI that points to the top of
1718    basic block's statement list.
1719    If PHI node has more than two arguments a chain of conditional
1720    expression is produced.  */
1721
1722
1723 static void
1724 predicate_scalar_phi (gphi *phi, gimple_stmt_iterator *gsi)
1725 {
1726   gimple *new_stmt = NULL, *reduc;
1727   tree rhs, res, arg0, arg1, op0, op1, scev;
1728   tree cond;
1729   unsigned int index0;
1730   unsigned int max, args_len;
1731   edge e;
1732   basic_block bb;
1733   unsigned int i;
1734
1735   res = gimple_phi_result (phi);
1736   if (virtual_operand_p (res))
1737     return;
1738
1739   if ((rhs = degenerate_phi_result (phi))
1740       || ((scev = analyze_scalar_evolution (gimple_bb (phi)->loop_father,
1741                                             res))
1742           && !chrec_contains_undetermined (scev)
1743           && scev != res
1744           && (rhs = gimple_phi_arg_def (phi, 0))))
1745     {
1746       if (dump_file && (dump_flags & TDF_DETAILS))
1747         {
1748           fprintf (dump_file, "Degenerate phi!\n");
1749           print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
1750         }
1751       new_stmt = gimple_build_assign (res, rhs);
1752       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1753       update_stmt (new_stmt);
1754       return;
1755     }
1756
1757   bb = gimple_bb (phi);
1758   if (EDGE_COUNT (bb->preds) == 2)
1759     {
1760       /* Predicate ordinary PHI node with 2 arguments.  */
1761       edge first_edge, second_edge;
1762       basic_block true_bb;
1763       first_edge = EDGE_PRED (bb, 0);
1764       second_edge = EDGE_PRED (bb, 1);
1765       cond = bb_predicate (first_edge->src);
1766       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1767         std::swap (first_edge, second_edge);
1768       if (EDGE_COUNT (first_edge->src->succs) > 1)
1769         {
1770           cond = bb_predicate (second_edge->src);
1771           if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1772             cond = TREE_OPERAND (cond, 0);
1773           else
1774             first_edge = second_edge;
1775         }
1776       else
1777         cond = bb_predicate (first_edge->src);
1778       /* Gimplify the condition to a valid cond-expr conditonal operand.  */
1779       cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1780                                          is_gimple_condexpr, NULL_TREE,
1781                                          true, GSI_SAME_STMT);
1782       true_bb = first_edge->src;
1783       if (EDGE_PRED (bb, 1)->src == true_bb)
1784         {
1785           arg0 = gimple_phi_arg_def (phi, 1);
1786           arg1 = gimple_phi_arg_def (phi, 0);
1787         }
1788       else
1789         {
1790           arg0 = gimple_phi_arg_def (phi, 0);
1791           arg1 = gimple_phi_arg_def (phi, 1);
1792         }
1793       if (is_cond_scalar_reduction (phi, &reduc, arg0, arg1,
1794                                     &op0, &op1, false))
1795         /* Convert reduction stmt into vectorizable form.  */
1796         rhs = convert_scalar_cond_reduction (reduc, gsi, cond, op0, op1,
1797                                              true_bb != gimple_bb (reduc));
1798       else
1799         /* Build new RHS using selected condition and arguments.  */
1800         rhs = fold_build_cond_expr (TREE_TYPE (res), unshare_expr (cond),
1801                                     arg0, arg1);
1802       new_stmt = gimple_build_assign (res, rhs);
1803       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1804       update_stmt (new_stmt);
1805
1806       if (dump_file && (dump_flags & TDF_DETAILS))
1807         {
1808           fprintf (dump_file, "new phi replacement stmt\n");
1809           print_gimple_stmt (dump_file, new_stmt, 0, TDF_SLIM);
1810         }
1811       return;
1812     }
1813
1814   /* Create hashmap for PHI node which contain vector of argument indexes
1815      having the same value.  */
1816   bool swap = false;
1817   hash_map<tree_operand_hash, auto_vec<int> > phi_arg_map;
1818   unsigned int num_args = gimple_phi_num_args (phi);
1819   int max_ind = -1;
1820   /* Vector of different PHI argument values.  */
1821   auto_vec<tree> args (num_args);
1822
1823   /* Compute phi_arg_map.  */
1824   for (i = 0; i < num_args; i++)
1825     {
1826       tree arg;
1827
1828       arg = gimple_phi_arg_def (phi, i);
1829       if (!phi_arg_map.get (arg))
1830         args.quick_push (arg);
1831       phi_arg_map.get_or_insert (arg).safe_push (i);
1832     }
1833
1834   /* Determine element with max number of occurrences.  */
1835   max_ind = -1;
1836   max = 1;
1837   args_len = args.length ();
1838   for (i = 0; i < args_len; i++)
1839     {
1840       unsigned int len;
1841       if ((len = phi_arg_map.get (args[i])->length ()) > max)
1842         {
1843           max_ind = (int) i;
1844           max = len;
1845         }
1846     }
1847
1848   /* Put element with max number of occurences to the end of ARGS.  */
1849   if (max_ind != -1 && max_ind +1 != (int) args_len)
1850     std::swap (args[args_len - 1], args[max_ind]);
1851
1852   /* Handle one special case when number of arguments with different values
1853      is equal 2 and one argument has the only occurrence.  Such PHI can be
1854      handled as if would have only 2 arguments.  */
1855   if (args_len == 2 && phi_arg_map.get (args[0])->length () == 1)
1856     {
1857       vec<int> *indexes;
1858       indexes = phi_arg_map.get (args[0]);
1859       index0 = (*indexes)[0];
1860       arg0 = args[0];
1861       arg1 = args[1];
1862       e = gimple_phi_arg_edge (phi, index0);
1863       cond = bb_predicate (e->src);
1864       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
1865         {
1866           swap = true;
1867           cond = TREE_OPERAND (cond, 0);
1868         }
1869       /* Gimplify the condition to a valid cond-expr conditonal operand.  */
1870       cond = force_gimple_operand_gsi_1 (gsi, unshare_expr (cond),
1871                                          is_gimple_condexpr, NULL_TREE,
1872                                          true, GSI_SAME_STMT);
1873       if (!(is_cond_scalar_reduction (phi, &reduc, arg0 , arg1,
1874                                       &op0, &op1, true)))
1875         rhs = fold_build_cond_expr (TREE_TYPE (res), unshare_expr (cond),
1876                                     swap? arg1 : arg0,
1877                                     swap? arg0 : arg1);
1878       else
1879         /* Convert reduction stmt into vectorizable form.  */
1880         rhs = convert_scalar_cond_reduction (reduc, gsi, cond, op0, op1,
1881                                              swap);
1882       new_stmt = gimple_build_assign (res, rhs);
1883       gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1884       update_stmt (new_stmt);
1885     }
1886   else
1887     {
1888       /* Common case.  */
1889       vec<int> *indexes;
1890       tree type = TREE_TYPE (gimple_phi_result (phi));
1891       tree lhs;
1892       arg1 = args[1];
1893       for (i = 0; i < args_len; i++)
1894         {
1895           arg0 = args[i];
1896           indexes = phi_arg_map.get (args[i]);
1897           if (i != args_len - 1)
1898             lhs = make_temp_ssa_name (type, NULL, "_ifc_");
1899           else
1900             lhs = res;
1901           cond = gen_phi_arg_condition (phi, indexes, gsi);
1902           rhs = fold_build_cond_expr (type, unshare_expr (cond),
1903                                       arg0, arg1);
1904           new_stmt = gimple_build_assign (lhs, rhs);
1905           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
1906           update_stmt (new_stmt);
1907           arg1 = lhs;
1908         }
1909     }
1910
1911   if (dump_file && (dump_flags & TDF_DETAILS))
1912     {
1913       fprintf (dump_file, "new extended phi replacement stmt\n");
1914       print_gimple_stmt (dump_file, new_stmt, 0, TDF_SLIM);
1915     }
1916 }
1917
1918 /* Replaces in LOOP all the scalar phi nodes other than those in the
1919    LOOP->header block with conditional modify expressions.  */
1920
1921 static void
1922 predicate_all_scalar_phis (struct loop *loop)
1923 {
1924   basic_block bb;
1925   unsigned int orig_loop_num_nodes = loop->num_nodes;
1926   unsigned int i;
1927
1928   for (i = 1; i < orig_loop_num_nodes; i++)
1929     {
1930       gphi *phi;
1931       gimple_stmt_iterator gsi;
1932       gphi_iterator phi_gsi;
1933       bb = ifc_bbs[i];
1934
1935       if (bb == loop->header)
1936         continue;
1937
1938       phi_gsi = gsi_start_phis (bb);
1939       if (gsi_end_p (phi_gsi))
1940         continue;
1941
1942       gsi = gsi_after_labels (bb);
1943       while (!gsi_end_p (phi_gsi))
1944         {
1945           phi = phi_gsi.phi ();
1946           predicate_scalar_phi (phi, &gsi);
1947           release_phi_node (phi);
1948           gsi_next (&phi_gsi);
1949         }
1950
1951       set_phi_nodes (bb, NULL);
1952     }
1953 }
1954
1955 /* Insert in each basic block of LOOP the statements produced by the
1956    gimplification of the predicates.  */
1957
1958 static void
1959 insert_gimplified_predicates (loop_p loop)
1960 {
1961   unsigned int i;
1962
1963   for (i = 0; i < loop->num_nodes; i++)
1964     {
1965       basic_block bb = ifc_bbs[i];
1966       gimple_seq stmts;
1967       if (!is_predicated (bb))
1968         gcc_assert (bb_predicate_gimplified_stmts (bb) == NULL);
1969       if (!is_predicated (bb))
1970         {
1971           /* Do not insert statements for a basic block that is not
1972              predicated.  Also make sure that the predicate of the
1973              basic block is set to true.  */
1974           reset_bb_predicate (bb);
1975           continue;
1976         }
1977
1978       stmts = bb_predicate_gimplified_stmts (bb);
1979       if (stmts)
1980         {
1981           if (any_pred_load_store)
1982             {
1983               /* Insert the predicate of the BB just after the label,
1984                  as the if-conversion of memory writes will use this
1985                  predicate.  */
1986               gimple_stmt_iterator gsi = gsi_after_labels (bb);
1987               gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
1988             }
1989           else
1990             {
1991               /* Insert the predicate of the BB at the end of the BB
1992                  as this would reduce the register pressure: the only
1993                  use of this predicate will be in successor BBs.  */
1994               gimple_stmt_iterator gsi = gsi_last_bb (bb);
1995
1996               if (gsi_end_p (gsi)
1997                   || stmt_ends_bb_p (gsi_stmt (gsi)))
1998                 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
1999               else
2000                 gsi_insert_seq_after (&gsi, stmts, GSI_SAME_STMT);
2001             }
2002
2003           /* Once the sequence is code generated, set it to NULL.  */
2004           set_bb_predicate_gimplified_stmts (bb, NULL);
2005         }
2006     }
2007 }
2008
2009 /* Helper function for predicate_mem_writes. Returns index of existent
2010    mask if it was created for given SIZE and -1 otherwise.  */
2011
2012 static int
2013 mask_exists (int size, vec<int> vec)
2014 {
2015   unsigned int ix;
2016   int v;
2017   FOR_EACH_VEC_ELT (vec, ix, v)
2018     if (v == size)
2019       return (int) ix;
2020   return -1;
2021 }
2022
2023 /* Predicate each write to memory in LOOP.
2024
2025    This function transforms control flow constructs containing memory
2026    writes of the form:
2027
2028    | for (i = 0; i < N; i++)
2029    |   if (cond)
2030    |     A[i] = expr;
2031
2032    into the following form that does not contain control flow:
2033
2034    | for (i = 0; i < N; i++)
2035    |   A[i] = cond ? expr : A[i];
2036
2037    The original CFG looks like this:
2038
2039    | bb_0
2040    |   i = 0
2041    | end_bb_0
2042    |
2043    | bb_1
2044    |   if (i < N) goto bb_5 else goto bb_2
2045    | end_bb_1
2046    |
2047    | bb_2
2048    |   cond = some_computation;
2049    |   if (cond) goto bb_3 else goto bb_4
2050    | end_bb_2
2051    |
2052    | bb_3
2053    |   A[i] = expr;
2054    |   goto bb_4
2055    | end_bb_3
2056    |
2057    | bb_4
2058    |   goto bb_1
2059    | end_bb_4
2060
2061    insert_gimplified_predicates inserts the computation of the COND
2062    expression at the beginning of the destination basic block:
2063
2064    | bb_0
2065    |   i = 0
2066    | end_bb_0
2067    |
2068    | bb_1
2069    |   if (i < N) goto bb_5 else goto bb_2
2070    | end_bb_1
2071    |
2072    | bb_2
2073    |   cond = some_computation;
2074    |   if (cond) goto bb_3 else goto bb_4
2075    | end_bb_2
2076    |
2077    | bb_3
2078    |   cond = some_computation;
2079    |   A[i] = expr;
2080    |   goto bb_4
2081    | end_bb_3
2082    |
2083    | bb_4
2084    |   goto bb_1
2085    | end_bb_4
2086
2087    predicate_mem_writes is then predicating the memory write as follows:
2088
2089    | bb_0
2090    |   i = 0
2091    | end_bb_0
2092    |
2093    | bb_1
2094    |   if (i < N) goto bb_5 else goto bb_2
2095    | end_bb_1
2096    |
2097    | bb_2
2098    |   if (cond) goto bb_3 else goto bb_4
2099    | end_bb_2
2100    |
2101    | bb_3
2102    |   cond = some_computation;
2103    |   A[i] = cond ? expr : A[i];
2104    |   goto bb_4
2105    | end_bb_3
2106    |
2107    | bb_4
2108    |   goto bb_1
2109    | end_bb_4
2110
2111    and finally combine_blocks removes the basic block boundaries making
2112    the loop vectorizable:
2113
2114    | bb_0
2115    |   i = 0
2116    |   if (i < N) goto bb_5 else goto bb_1
2117    | end_bb_0
2118    |
2119    | bb_1
2120    |   cond = some_computation;
2121    |   A[i] = cond ? expr : A[i];
2122    |   if (i < N) goto bb_5 else goto bb_4
2123    | end_bb_1
2124    |
2125    | bb_4
2126    |   goto bb_1
2127    | end_bb_4
2128 */
2129
2130 static void
2131 predicate_mem_writes (loop_p loop)
2132 {
2133   unsigned int i, orig_loop_num_nodes = loop->num_nodes;
2134   auto_vec<int, 1> vect_sizes;
2135   auto_vec<tree, 1> vect_masks;
2136
2137   for (i = 1; i < orig_loop_num_nodes; i++)
2138     {
2139       gimple_stmt_iterator gsi;
2140       basic_block bb = ifc_bbs[i];
2141       tree cond = bb_predicate (bb);
2142       bool swap;
2143       gimple *stmt;
2144       int index;
2145
2146       if (is_true_predicate (cond) || is_false_predicate (cond))
2147         continue;
2148
2149       swap = false;
2150       if (TREE_CODE (cond) == TRUTH_NOT_EXPR)
2151         {
2152           swap = true;
2153           cond = TREE_OPERAND (cond, 0);
2154         }
2155
2156       vect_sizes.truncate (0);
2157       vect_masks.truncate (0);
2158
2159       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2160         if (!gimple_assign_single_p (stmt = gsi_stmt (gsi)))
2161           continue;
2162         else if (gimple_plf (stmt, GF_PLF_2))
2163           {
2164             tree lhs = gimple_assign_lhs (stmt);
2165             tree rhs = gimple_assign_rhs1 (stmt);
2166             tree ref, addr, ptr, mask;
2167             gimple *new_stmt;
2168             gimple_seq stmts = NULL;
2169             int bitsize = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (lhs)));
2170             ref = TREE_CODE (lhs) == SSA_NAME ? rhs : lhs;
2171             mark_addressable (ref);
2172             addr = force_gimple_operand_gsi (&gsi, build_fold_addr_expr (ref),
2173                                              true, NULL_TREE, true,
2174                                              GSI_SAME_STMT);
2175             if (!vect_sizes.is_empty ()
2176                 && (index = mask_exists (bitsize, vect_sizes)) != -1)
2177               /* Use created mask.  */
2178               mask = vect_masks[index];
2179             else
2180               {
2181                 if (COMPARISON_CLASS_P (cond))
2182                   mask = gimple_build (&stmts, TREE_CODE (cond),
2183                                        boolean_type_node,
2184                                        TREE_OPERAND (cond, 0),
2185                                        TREE_OPERAND (cond, 1));
2186                 else
2187                   {
2188                     gcc_assert (TREE_CODE (cond) == SSA_NAME);
2189                     mask = cond;
2190                   }
2191
2192                 if (swap)
2193                   {
2194                     tree true_val
2195                       = constant_boolean_node (true, TREE_TYPE (mask));
2196                     mask = gimple_build (&stmts, BIT_XOR_EXPR,
2197                                          TREE_TYPE (mask), mask, true_val);
2198                   }
2199                 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
2200
2201                 mask = ifc_temp_var (TREE_TYPE (mask), mask, &gsi);
2202                 /* Save mask and its size for further use.  */
2203                 vect_sizes.safe_push (bitsize);
2204                 vect_masks.safe_push (mask);
2205               }
2206             ptr = build_int_cst (reference_alias_ptr_type (ref),
2207                                  get_object_alignment (ref));
2208             /* Copy points-to info if possible.  */
2209             if (TREE_CODE (addr) == SSA_NAME && !SSA_NAME_PTR_INFO (addr))
2210               copy_ref_info (build2 (MEM_REF, TREE_TYPE (ref), addr, ptr),
2211                              ref);
2212             if (TREE_CODE (lhs) == SSA_NAME)
2213               {
2214                 new_stmt
2215                   = gimple_build_call_internal (IFN_MASK_LOAD, 3, addr,
2216                                                 ptr, mask);
2217                 gimple_call_set_lhs (new_stmt, lhs);
2218               }
2219             else
2220               new_stmt
2221                 = gimple_build_call_internal (IFN_MASK_STORE, 4, addr, ptr,
2222                                               mask, rhs);
2223             gsi_replace (&gsi, new_stmt, true);
2224           }
2225         else if (gimple_vdef (stmt))
2226           {
2227             tree lhs = gimple_assign_lhs (stmt);
2228             tree rhs = gimple_assign_rhs1 (stmt);
2229             tree type = TREE_TYPE (lhs);
2230
2231             lhs = ifc_temp_var (type, unshare_expr (lhs), &gsi);
2232             rhs = ifc_temp_var (type, unshare_expr (rhs), &gsi);
2233             if (swap)
2234               std::swap (lhs, rhs);
2235             cond = force_gimple_operand_gsi_1 (&gsi, unshare_expr (cond),
2236                                                is_gimple_condexpr, NULL_TREE,
2237                                                true, GSI_SAME_STMT);
2238             rhs = fold_build_cond_expr (type, unshare_expr (cond), rhs, lhs);
2239             gimple_assign_set_rhs1 (stmt, ifc_temp_var (type, rhs, &gsi));
2240             update_stmt (stmt);
2241           }
2242     }
2243 }
2244
2245 /* Remove all GIMPLE_CONDs and GIMPLE_LABELs of all the basic blocks
2246    other than the exit and latch of the LOOP.  Also resets the
2247    GIMPLE_DEBUG information.  */
2248
2249 static void
2250 remove_conditions_and_labels (loop_p loop)
2251 {
2252   gimple_stmt_iterator gsi;
2253   unsigned int i;
2254
2255   for (i = 0; i < loop->num_nodes; i++)
2256     {
2257       basic_block bb = ifc_bbs[i];
2258
2259       if (bb_with_exit_edge_p (loop, bb)
2260         || bb == loop->latch)
2261       continue;
2262
2263       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2264         switch (gimple_code (gsi_stmt (gsi)))
2265           {
2266           case GIMPLE_COND:
2267           case GIMPLE_LABEL:
2268             gsi_remove (&gsi, true);
2269             break;
2270
2271           case GIMPLE_DEBUG:
2272             /* ??? Should there be conditional GIMPLE_DEBUG_BINDs?  */
2273             if (gimple_debug_bind_p (gsi_stmt (gsi)))
2274               {
2275                 gimple_debug_bind_reset_value (gsi_stmt (gsi));
2276                 update_stmt (gsi_stmt (gsi));
2277               }
2278             gsi_next (&gsi);
2279             break;
2280
2281           default:
2282             gsi_next (&gsi);
2283           }
2284     }
2285 }
2286
2287 /* Combine all the basic blocks from LOOP into one or two super basic
2288    blocks.  Replace PHI nodes with conditional modify expressions.  */
2289
2290 static void
2291 combine_blocks (struct loop *loop)
2292 {
2293   basic_block bb, exit_bb, merge_target_bb;
2294   unsigned int orig_loop_num_nodes = loop->num_nodes;
2295   unsigned int i;
2296   edge e;
2297   edge_iterator ei;
2298
2299   remove_conditions_and_labels (loop);
2300   insert_gimplified_predicates (loop);
2301   predicate_all_scalar_phis (loop);
2302
2303   if (any_pred_load_store)
2304     predicate_mem_writes (loop);
2305
2306   /* Merge basic blocks: first remove all the edges in the loop,
2307      except for those from the exit block.  */
2308   exit_bb = NULL;
2309   bool *predicated = XNEWVEC (bool, orig_loop_num_nodes);
2310   for (i = 0; i < orig_loop_num_nodes; i++)
2311     {
2312       bb = ifc_bbs[i];
2313       predicated[i] = !is_true_predicate (bb_predicate (bb));
2314       free_bb_predicate (bb);
2315       if (bb_with_exit_edge_p (loop, bb))
2316         {
2317           gcc_assert (exit_bb == NULL);
2318           exit_bb = bb;
2319         }
2320     }
2321   gcc_assert (exit_bb != loop->latch);
2322
2323   for (i = 1; i < orig_loop_num_nodes; i++)
2324     {
2325       bb = ifc_bbs[i];
2326
2327       for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei));)
2328         {
2329           if (e->src == exit_bb)
2330             ei_next (&ei);
2331           else
2332             remove_edge (e);
2333         }
2334     }
2335
2336   if (exit_bb != NULL)
2337     {
2338       if (exit_bb != loop->header)
2339         {
2340           /* Connect this node to loop header.  */
2341           make_edge (loop->header, exit_bb, EDGE_FALLTHRU);
2342           set_immediate_dominator (CDI_DOMINATORS, exit_bb, loop->header);
2343         }
2344
2345       /* Redirect non-exit edges to loop->latch.  */
2346       FOR_EACH_EDGE (e, ei, exit_bb->succs)
2347         {
2348           if (!loop_exit_edge_p (loop, e))
2349             redirect_edge_and_branch (e, loop->latch);
2350         }
2351       set_immediate_dominator (CDI_DOMINATORS, loop->latch, exit_bb);
2352     }
2353   else
2354     {
2355       /* If the loop does not have an exit, reconnect header and latch.  */
2356       make_edge (loop->header, loop->latch, EDGE_FALLTHRU);
2357       set_immediate_dominator (CDI_DOMINATORS, loop->latch, loop->header);
2358     }
2359
2360   merge_target_bb = loop->header;
2361   for (i = 1; i < orig_loop_num_nodes; i++)
2362     {
2363       gimple_stmt_iterator gsi;
2364       gimple_stmt_iterator last;
2365
2366       bb = ifc_bbs[i];
2367
2368       if (bb == exit_bb || bb == loop->latch)
2369         continue;
2370
2371       /* Make stmts member of loop->header and clear range info from all stmts
2372          in BB which is now no longer executed conditional on a predicate we
2373          could have derived it from.  */
2374       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2375         {
2376           gimple *stmt = gsi_stmt (gsi);
2377           gimple_set_bb (stmt, merge_target_bb);
2378           if (predicated[i])
2379             {
2380               ssa_op_iter i;
2381               tree op;
2382               FOR_EACH_SSA_TREE_OPERAND (op, stmt, i, SSA_OP_DEF)
2383                 reset_flow_sensitive_info (op);
2384             }
2385         }
2386
2387       /* Update stmt list.  */
2388       last = gsi_last_bb (merge_target_bb);
2389       gsi_insert_seq_after (&last, bb_seq (bb), GSI_NEW_STMT);
2390       set_bb_seq (bb, NULL);
2391
2392       delete_basic_block (bb);
2393     }
2394
2395   /* If possible, merge loop header to the block with the exit edge.
2396      This reduces the number of basic blocks to two, to please the
2397      vectorizer that handles only loops with two nodes.  */
2398   if (exit_bb
2399       && exit_bb != loop->header
2400       && can_merge_blocks_p (loop->header, exit_bb))
2401     merge_blocks (loop->header, exit_bb);
2402
2403   free (ifc_bbs);
2404   ifc_bbs = NULL;
2405   free (predicated);
2406 }
2407
2408 /* Version LOOP before if-converting it; the original loop
2409    will be if-converted, the new copy of the loop will not,
2410    and the LOOP_VECTORIZED internal call will be guarding which
2411    loop to execute.  The vectorizer pass will fold this
2412    internal call into either true or false.  */
2413
2414 static bool
2415 version_loop_for_if_conversion (struct loop *loop)
2416 {
2417   basic_block cond_bb;
2418   tree cond = make_ssa_name (boolean_type_node);
2419   struct loop *new_loop;
2420   gimple *g;
2421   gimple_stmt_iterator gsi;
2422
2423   g = gimple_build_call_internal (IFN_LOOP_VECTORIZED, 2,
2424                                   build_int_cst (integer_type_node, loop->num),
2425                                   integer_zero_node);
2426   gimple_call_set_lhs (g, cond);
2427
2428   /* Save BB->aux around loop_version as that uses the same field.  */
2429   void **saved_preds = XALLOCAVEC (void *, loop->num_nodes);
2430   for (unsigned i = 0; i < loop->num_nodes; i++)
2431     saved_preds[i] = ifc_bbs[i]->aux;
2432
2433   initialize_original_copy_tables ();
2434   new_loop = loop_version (loop, cond, &cond_bb,
2435                            REG_BR_PROB_BASE, REG_BR_PROB_BASE,
2436                            REG_BR_PROB_BASE, true);
2437   free_original_copy_tables ();
2438
2439   for (unsigned i = 0; i < loop->num_nodes; i++)
2440     ifc_bbs[i]->aux = saved_preds[i];
2441
2442   if (new_loop == NULL)
2443     return false;
2444
2445   new_loop->dont_vectorize = true;
2446   new_loop->force_vectorize = false;
2447   gsi = gsi_last_bb (cond_bb);
2448   gimple_call_set_arg (g, 1, build_int_cst (integer_type_node, new_loop->num));
2449   gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2450   update_ssa (TODO_update_ssa);
2451   return true;
2452 }
2453
2454 /* Performs splitting of critical edges.  Skip splitting and return false
2455    if LOOP will not be converted because:
2456
2457      - LOOP is not well formed.
2458      - LOOP has PHI with more than MAX_PHI_ARG_NUM arguments.
2459
2460    Last restriction is valid only if AGGRESSIVE_IF_CONV is false.  */
2461
2462 static bool
2463 ifcvt_split_critical_edges (struct loop *loop, bool aggressive_if_conv)
2464 {
2465   basic_block *body;
2466   basic_block bb;
2467   unsigned int num = loop->num_nodes;
2468   unsigned int i;
2469   gimple *stmt;
2470   edge e;
2471   edge_iterator ei;
2472   auto_vec<edge> critical_edges;
2473
2474   /* Loop is not well formed.  */
2475   if (num <= 2 || loop->inner || !single_exit (loop))
2476     return false;
2477
2478   body = get_loop_body (loop);
2479   for (i = 0; i < num; i++)
2480     {
2481       bb = body[i];
2482       if (!aggressive_if_conv
2483           && phi_nodes (bb)
2484           && EDGE_COUNT (bb->preds) > MAX_PHI_ARG_NUM)
2485         {
2486           if (dump_file && (dump_flags & TDF_DETAILS))
2487             fprintf (dump_file,
2488                      "BB %d has complicated PHI with more than %u args.\n",
2489                      bb->index, MAX_PHI_ARG_NUM);
2490
2491           free (body);
2492           return false;
2493         }
2494       if (bb == loop->latch || bb_with_exit_edge_p (loop, bb))
2495         continue;
2496
2497       stmt = last_stmt (bb);
2498       /* Skip basic blocks not ending with conditional branch.  */
2499       if (!stmt || gimple_code (stmt) != GIMPLE_COND)
2500         continue;
2501
2502       FOR_EACH_EDGE (e, ei, bb->succs)
2503         if (EDGE_CRITICAL_P (e) && e->dest->loop_father == loop)
2504           critical_edges.safe_push (e);
2505     }
2506   free (body);
2507
2508   while (critical_edges.length () > 0)
2509     {
2510       e = critical_edges.pop ();
2511       /* Don't split if bb can be predicated along non-critical edge.  */
2512       if (EDGE_COUNT (e->dest->preds) > 2 || all_preds_critical_p (e->dest))
2513         split_edge (e);
2514     }
2515
2516   return true;
2517 }
2518
2519 /* Assumes that lhs of DEF_STMT have multiple uses.
2520    Delete one use by (1) creation of copy DEF_STMT with
2521    unique lhs; (2) change original use of lhs in one
2522    use statement with newly created lhs.  */
2523
2524 static void
2525 ifcvt_split_def_stmt (gimple *def_stmt, gimple *use_stmt)
2526 {
2527   tree var;
2528   tree lhs;
2529   gimple *copy_stmt;
2530   gimple_stmt_iterator gsi;
2531   use_operand_p use_p;
2532   imm_use_iterator imm_iter;
2533
2534   var = gimple_assign_lhs (def_stmt);
2535   copy_stmt = gimple_copy (def_stmt);
2536   lhs = make_temp_ssa_name (TREE_TYPE (var), NULL, "_ifc_");
2537   gimple_assign_set_lhs (copy_stmt, lhs);
2538   SSA_NAME_DEF_STMT (lhs) = copy_stmt;
2539   /* Insert copy of DEF_STMT.  */
2540   gsi = gsi_for_stmt (def_stmt);
2541   gsi_insert_after (&gsi, copy_stmt, GSI_SAME_STMT);
2542   /* Change use of var to lhs in use_stmt.  */
2543   if (dump_file && (dump_flags & TDF_DETAILS))
2544     {
2545       fprintf (dump_file, "Change use of var  ");
2546       print_generic_expr (dump_file, var, TDF_SLIM);
2547       fprintf (dump_file, " to ");
2548       print_generic_expr (dump_file, lhs, TDF_SLIM);
2549       fprintf (dump_file, "\n");
2550     }
2551   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, var)
2552     {
2553       if (USE_STMT (use_p) != use_stmt)
2554         continue;
2555       SET_USE (use_p, lhs);
2556       break;
2557     }
2558 }
2559
2560 /* Traverse bool pattern recursively starting from VAR.
2561    Save its def and use statements to defuse_list if VAR does
2562    not have single use.  */
2563
2564 static void
2565 ifcvt_walk_pattern_tree (tree var, vec<gimple *> *defuse_list,
2566                          gimple *use_stmt)
2567 {
2568   tree rhs1, rhs2;
2569   enum tree_code code;
2570   gimple *def_stmt;
2571
2572   if (TREE_CODE (var) != SSA_NAME)
2573     return;
2574
2575   def_stmt = SSA_NAME_DEF_STMT (var);
2576   if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
2577     return;
2578   if (!has_single_use (var))
2579     {
2580       /* Put def and use stmts into defuse_list.  */
2581       defuse_list->safe_push (def_stmt);
2582       defuse_list->safe_push (use_stmt);
2583       if (dump_file && (dump_flags & TDF_DETAILS))
2584         {
2585           fprintf (dump_file, "Multiple lhs uses in stmt\n");
2586           print_gimple_stmt (dump_file, def_stmt, 0, TDF_SLIM);
2587         }
2588     }
2589   rhs1 = gimple_assign_rhs1 (def_stmt);
2590   code = gimple_assign_rhs_code (def_stmt);
2591   switch (code)
2592     {
2593     case SSA_NAME:
2594       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2595       break;
2596     CASE_CONVERT:
2597       if ((TYPE_PRECISION (TREE_TYPE (rhs1)) != 1
2598            || !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
2599           && TREE_CODE (TREE_TYPE (rhs1)) != BOOLEAN_TYPE)
2600         break;
2601       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2602       break;
2603     case BIT_NOT_EXPR:
2604       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2605       break;
2606     case BIT_AND_EXPR:
2607     case BIT_IOR_EXPR:
2608     case BIT_XOR_EXPR:
2609       ifcvt_walk_pattern_tree (rhs1, defuse_list, def_stmt);
2610       rhs2 = gimple_assign_rhs2 (def_stmt);
2611       ifcvt_walk_pattern_tree (rhs2, defuse_list, def_stmt);
2612       break;
2613     default:
2614       break;
2615     }
2616   return;
2617 }
2618
2619 /* Returns true if STMT can be a root of bool pattern applied
2620    by vectorizer.  */
2621
2622 static bool
2623 stmt_is_root_of_bool_pattern (gimple *stmt)
2624 {
2625   enum tree_code code;
2626   tree lhs, rhs;
2627
2628   code = gimple_assign_rhs_code (stmt);
2629   if (CONVERT_EXPR_CODE_P (code))
2630     {
2631       lhs = gimple_assign_lhs (stmt);
2632       rhs = gimple_assign_rhs1 (stmt);
2633       if (TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE)
2634         return false;
2635       if (TREE_CODE (TREE_TYPE (lhs)) == BOOLEAN_TYPE)
2636         return false;
2637       return true;
2638     }
2639   else if (code == COND_EXPR)
2640     {
2641       rhs = gimple_assign_rhs1 (stmt);
2642       if (TREE_CODE (rhs) != SSA_NAME)
2643         return false;
2644       return true;
2645     }
2646   return false;
2647 }
2648
2649 /*  Traverse all statements in BB which correspond to loop header to
2650     find out all statements which can start bool pattern applied by
2651     vectorizer and convert multiple uses in it to conform pattern
2652     restrictions.  Such case can occur if the same predicate is used both
2653     for phi node conversion and load/store mask.  */
2654
2655 static void
2656 ifcvt_repair_bool_pattern (basic_block bb)
2657 {
2658   tree rhs;
2659   gimple *stmt;
2660   gimple_stmt_iterator gsi;
2661   auto_vec<gimple *> defuse_list;
2662   auto_vec<gimple *> pattern_roots;
2663   bool repeat = true;
2664   int niter = 0;
2665   unsigned int ix;
2666
2667   /* Collect all root pattern statements.  */
2668   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2669     {
2670       stmt = gsi_stmt (gsi);
2671       if (gimple_code (stmt) != GIMPLE_ASSIGN)
2672         continue;
2673       if (!stmt_is_root_of_bool_pattern (stmt))
2674         continue;
2675       pattern_roots.safe_push (stmt);
2676     }
2677
2678   if (pattern_roots.is_empty ())
2679     return;
2680
2681   /* Split all statements with multiple uses iteratively since splitting
2682      may create new multiple uses.  */
2683   while (repeat)
2684     {
2685       repeat = false;
2686       niter++;
2687       FOR_EACH_VEC_ELT (pattern_roots, ix, stmt)
2688         {
2689           rhs = gimple_assign_rhs1 (stmt);
2690           ifcvt_walk_pattern_tree (rhs, &defuse_list, stmt);
2691           while (defuse_list.length () > 0)
2692             {
2693               repeat = true;
2694               gimple *def_stmt, *use_stmt;
2695               use_stmt = defuse_list.pop ();
2696               def_stmt = defuse_list.pop ();
2697               ifcvt_split_def_stmt (def_stmt, use_stmt);
2698             }
2699
2700         }
2701     }
2702   if (dump_file && (dump_flags & TDF_DETAILS))
2703     fprintf (dump_file, "Repair bool pattern takes %d iterations. \n",
2704              niter);
2705 }
2706
2707 /* Delete redundant statements produced by predication which prevents
2708    loop vectorization.  */
2709
2710 static void
2711 ifcvt_local_dce (basic_block bb)
2712 {
2713   gimple *stmt;
2714   gimple *stmt1;
2715   gimple *phi;
2716   gimple_stmt_iterator gsi;
2717   auto_vec<gimple *> worklist;
2718   enum gimple_code code;
2719   use_operand_p use_p;
2720   imm_use_iterator imm_iter;
2721
2722   worklist.create (64);
2723   /* Consider all phi as live statements.  */
2724   for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2725     {
2726       phi = gsi_stmt (gsi);
2727       gimple_set_plf (phi, GF_PLF_2, true);
2728       worklist.safe_push (phi);
2729     }
2730   /* Consider load/store statements, CALL and COND as live.  */
2731   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2732     {
2733       stmt = gsi_stmt (gsi);
2734       if (gimple_store_p (stmt)
2735           || gimple_assign_load_p (stmt)
2736           || is_gimple_debug (stmt))
2737         {
2738           gimple_set_plf (stmt, GF_PLF_2, true);
2739           worklist.safe_push (stmt);
2740           continue;
2741         }
2742       code = gimple_code (stmt);
2743       if (code == GIMPLE_COND || code == GIMPLE_CALL)
2744         {
2745           gimple_set_plf (stmt, GF_PLF_2, true);
2746           worklist.safe_push (stmt);
2747           continue;
2748         }
2749       gimple_set_plf (stmt, GF_PLF_2, false);
2750
2751       if (code == GIMPLE_ASSIGN)
2752         {
2753           tree lhs = gimple_assign_lhs (stmt);
2754           FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2755             {
2756               stmt1 = USE_STMT (use_p);
2757               if (gimple_bb (stmt1) != bb)
2758                 {
2759                   gimple_set_plf (stmt, GF_PLF_2, true);
2760                   worklist.safe_push (stmt);
2761                   break;
2762                 }
2763             }
2764         }
2765     }
2766   /* Propagate liveness through arguments of live stmt.  */
2767   while (worklist.length () > 0)
2768     {
2769       ssa_op_iter iter;
2770       use_operand_p use_p;
2771       tree use;
2772
2773       stmt = worklist.pop ();
2774       FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2775         {
2776           use = USE_FROM_PTR (use_p);
2777           if (TREE_CODE (use) != SSA_NAME)
2778             continue;
2779           stmt1 = SSA_NAME_DEF_STMT (use);
2780           if (gimple_bb (stmt1) != bb
2781               || gimple_plf (stmt1, GF_PLF_2))
2782             continue;
2783           gimple_set_plf (stmt1, GF_PLF_2, true);
2784           worklist.safe_push (stmt1);
2785         }
2786     }
2787   /* Delete dead statements.  */
2788   gsi = gsi_start_bb (bb);
2789   while (!gsi_end_p (gsi))
2790     {
2791       stmt = gsi_stmt (gsi);
2792       if (gimple_plf (stmt, GF_PLF_2))
2793         {
2794           gsi_next (&gsi);
2795           continue;
2796         }
2797       if (dump_file && (dump_flags & TDF_DETAILS))
2798         {
2799           fprintf (dump_file, "Delete dead stmt in bb#%d\n", bb->index);
2800           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2801         }
2802       gsi_remove (&gsi, true);
2803       release_defs (stmt);
2804     }
2805 }
2806
2807 /* If-convert LOOP when it is legal.  For the moment this pass has no
2808    profitability analysis.  Returns non-zero todo flags when something
2809    changed.  */
2810
2811 static unsigned int
2812 tree_if_conversion (struct loop *loop)
2813 {
2814   unsigned int todo = 0;
2815   bool aggressive_if_conv;
2816
2817   ifc_bbs = NULL;
2818   any_pred_load_store = false;
2819   any_complicated_phi = false;
2820
2821   /* Apply more aggressive if-conversion when loop or its outer loop were
2822      marked with simd pragma.  When that's the case, we try to if-convert
2823      loop containing PHIs with more than MAX_PHI_ARG_NUM arguments.  */
2824   aggressive_if_conv = loop->force_vectorize;
2825   if (!aggressive_if_conv)
2826     {
2827       struct loop *outer_loop = loop_outer (loop);
2828       if (outer_loop && outer_loop->force_vectorize)
2829         aggressive_if_conv = true;
2830     }
2831
2832   if (!ifcvt_split_critical_edges (loop, aggressive_if_conv))
2833     goto cleanup;
2834
2835   if (!if_convertible_loop_p (loop)
2836       || !dbg_cnt (if_conversion_tree))
2837     goto cleanup;
2838
2839   if ((any_pred_load_store || any_complicated_phi)
2840       && ((!flag_tree_loop_vectorize && !loop->force_vectorize)
2841           || loop->dont_vectorize))
2842     goto cleanup;
2843
2844   if ((any_pred_load_store || any_complicated_phi)
2845       && !version_loop_for_if_conversion (loop))
2846     goto cleanup;
2847
2848   /* Now all statements are if-convertible.  Combine all the basic
2849      blocks into one huge basic block doing the if-conversion
2850      on-the-fly.  */
2851   combine_blocks (loop);
2852
2853   /* Delete dead predicate computations and repair tree correspondent
2854      to bool pattern to delete multiple uses of predicates.  */
2855   ifcvt_local_dce (loop->header);
2856   ifcvt_repair_bool_pattern (loop->header);
2857
2858   todo |= TODO_cleanup_cfg;
2859   mark_virtual_operands_for_renaming (cfun);
2860   todo |= TODO_update_ssa_only_virtuals;
2861
2862  cleanup:
2863   if (ifc_bbs)
2864     {
2865       unsigned int i;
2866
2867       for (i = 0; i < loop->num_nodes; i++)
2868         free_bb_predicate (ifc_bbs[i]);
2869
2870       free (ifc_bbs);
2871       ifc_bbs = NULL;
2872     }
2873   free_dominance_info (CDI_POST_DOMINATORS);
2874
2875   return todo;
2876 }
2877
2878 /* Tree if-conversion pass management.  */
2879
2880 namespace {
2881
2882 const pass_data pass_data_if_conversion =
2883 {
2884   GIMPLE_PASS, /* type */
2885   "ifcvt", /* name */
2886   OPTGROUP_NONE, /* optinfo_flags */
2887   TV_NONE, /* tv_id */
2888   ( PROP_cfg | PROP_ssa ), /* properties_required */
2889   0, /* properties_provided */
2890   0, /* properties_destroyed */
2891   0, /* todo_flags_start */
2892   0, /* todo_flags_finish */
2893 };
2894
2895 class pass_if_conversion : public gimple_opt_pass
2896 {
2897 public:
2898   pass_if_conversion (gcc::context *ctxt)
2899     : gimple_opt_pass (pass_data_if_conversion, ctxt)
2900   {}
2901
2902   /* opt_pass methods: */
2903   virtual bool gate (function *);
2904   virtual unsigned int execute (function *);
2905
2906 }; // class pass_if_conversion
2907
2908 bool
2909 pass_if_conversion::gate (function *fun)
2910 {
2911   return (((flag_tree_loop_vectorize || fun->has_force_vectorize_loops)
2912            && flag_tree_loop_if_convert != 0)
2913           || flag_tree_loop_if_convert == 1
2914           || flag_tree_loop_if_convert_stores == 1);
2915 }
2916
2917 unsigned int
2918 pass_if_conversion::execute (function *fun)
2919 {
2920   struct loop *loop;
2921   unsigned todo = 0;
2922
2923   if (number_of_loops (fun) <= 1)
2924     return 0;
2925
2926   /* If there are infinite loops, during CDI_POST_DOMINATORS computation
2927      we can pick pretty much random bb inside of the infinite loop that
2928      has the fake edge.  If we are unlucky enough, this can confuse the
2929      add_to_predicate_list post-dominator check to optimize as if that
2930      bb or some other one is a join block when it actually is not.
2931      See PR70916.  */
2932   connect_infinite_loops_to_exit ();
2933
2934   FOR_EACH_LOOP (loop, 0)
2935     if (flag_tree_loop_if_convert == 1
2936         || flag_tree_loop_if_convert_stores == 1
2937         || ((flag_tree_loop_vectorize || loop->force_vectorize)
2938             && !loop->dont_vectorize))
2939       todo |= tree_if_conversion (loop);
2940
2941   remove_fake_exit_edges ();
2942
2943   if (flag_checking)
2944     {
2945       basic_block bb;
2946       FOR_EACH_BB_FN (bb, fun)
2947         gcc_assert (!bb->aux);
2948     }
2949
2950   return todo;
2951 }
2952
2953 } // anon namespace
2954
2955 gimple_opt_pass *
2956 make_pass_if_conversion (gcc::context *ctxt)
2957 {
2958   return new pass_if_conversion (ctxt);
2959 }