* testsuite/26_numerics/headers/cmath/hypot.cc: XFAIL on AIX.
[official-gcc.git] / gcc / tree-vect-loop.c
blob4150b0d9ee25cc04d674660c90d9d4c9d318f70a
1 /* Loop Vectorization
2 Copyright (C) 2003-2016 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <dorit@il.ibm.com> and
4 Ira Rosen <irar@il.ibm.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "target.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "cfghooks.h"
31 #include "tree-pass.h"
32 #include "ssa.h"
33 #include "optabs-tree.h"
34 #include "diagnostic-core.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "cfganal.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "tree-ssa-loop-ivopts.h"
42 #include "tree-ssa-loop-manip.h"
43 #include "tree-ssa-loop-niter.h"
44 #include "tree-ssa-loop.h"
45 #include "cfgloop.h"
46 #include "params.h"
47 #include "tree-scalar-evolution.h"
48 #include "tree-vectorizer.h"
49 #include "gimple-fold.h"
50 #include "cgraph.h"
51 #include "tree-cfg.h"
52 #include "tree-if-conv.h"
54 /* Loop Vectorization Pass.
56 This pass tries to vectorize loops.
58 For example, the vectorizer transforms the following simple loop:
60 short a[N]; short b[N]; short c[N]; int i;
62 for (i=0; i<N; i++){
63 a[i] = b[i] + c[i];
66 as if it was manually vectorized by rewriting the source code into:
68 typedef int __attribute__((mode(V8HI))) v8hi;
69 short a[N]; short b[N]; short c[N]; int i;
70 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
71 v8hi va, vb, vc;
73 for (i=0; i<N/8; i++){
74 vb = pb[i];
75 vc = pc[i];
76 va = vb + vc;
77 pa[i] = va;
80 The main entry to this pass is vectorize_loops(), in which
81 the vectorizer applies a set of analyses on a given set of loops,
82 followed by the actual vectorization transformation for the loops that
83 had successfully passed the analysis phase.
84 Throughout this pass we make a distinction between two types of
85 data: scalars (which are represented by SSA_NAMES), and memory references
86 ("data-refs"). These two types of data require different handling both
87 during analysis and transformation. The types of data-refs that the
88 vectorizer currently supports are ARRAY_REFS which base is an array DECL
89 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
90 accesses are required to have a simple (consecutive) access pattern.
92 Analysis phase:
93 ===============
94 The driver for the analysis phase is vect_analyze_loop().
95 It applies a set of analyses, some of which rely on the scalar evolution
96 analyzer (scev) developed by Sebastian Pop.
98 During the analysis phase the vectorizer records some information
99 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
100 loop, as well as general information about the loop as a whole, which is
101 recorded in a "loop_vec_info" struct attached to each loop.
103 Transformation phase:
104 =====================
105 The loop transformation phase scans all the stmts in the loop, and
106 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
107 the loop that needs to be vectorized. It inserts the vector code sequence
108 just before the scalar stmt S, and records a pointer to the vector code
109 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
110 attached to S). This pointer will be used for the vectorization of following
111 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
112 otherwise, we rely on dead code elimination for removing it.
114 For example, say stmt S1 was vectorized into stmt VS1:
116 VS1: vb = px[i];
117 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
118 S2: a = b;
120 To vectorize stmt S2, the vectorizer first finds the stmt that defines
121 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
122 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
123 resulting sequence would be:
125 VS1: vb = px[i];
126 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
127 VS2: va = vb;
128 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
130 Operands that are not SSA_NAMEs, are data-refs that appear in
131 load/store operations (like 'x[i]' in S1), and are handled differently.
133 Target modeling:
134 =================
135 Currently the only target specific information that is used is the
136 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
137 Targets that can support different sizes of vectors, for now will need
138 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
139 flexibility will be added in the future.
141 Since we only vectorize operations which vector form can be
142 expressed using existing tree codes, to verify that an operation is
143 supported, the vectorizer checks the relevant optab at the relevant
144 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
145 the value found is CODE_FOR_nothing, then there's no target support, and
146 we can't vectorize the stmt.
148 For additional information on this project see:
149 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
152 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *);
154 /* Function vect_determine_vectorization_factor
156 Determine the vectorization factor (VF). VF is the number of data elements
157 that are operated upon in parallel in a single iteration of the vectorized
158 loop. For example, when vectorizing a loop that operates on 4byte elements,
159 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
160 elements can fit in a single vector register.
162 We currently support vectorization of loops in which all types operated upon
163 are of the same size. Therefore this function currently sets VF according to
164 the size of the types operated upon, and fails if there are multiple sizes
165 in the loop.
167 VF is also the factor by which the loop iterations are strip-mined, e.g.:
168 original loop:
169 for (i=0; i<N; i++){
170 a[i] = b[i] + c[i];
173 vectorized loop:
174 for (i=0; i<N; i+=VF){
175 a[i:VF] = b[i:VF] + c[i:VF];
179 static bool
180 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
182 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
183 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
184 unsigned nbbs = loop->num_nodes;
185 unsigned int vectorization_factor = 0;
186 tree scalar_type;
187 gphi *phi;
188 tree vectype;
189 unsigned int nunits;
190 stmt_vec_info stmt_info;
191 unsigned i;
192 HOST_WIDE_INT dummy;
193 gimple *stmt, *pattern_stmt = NULL;
194 gimple_seq pattern_def_seq = NULL;
195 gimple_stmt_iterator pattern_def_si = gsi_none ();
196 bool analyze_pattern_stmt = false;
197 bool bool_result;
198 auto_vec<stmt_vec_info> mask_producers;
200 if (dump_enabled_p ())
201 dump_printf_loc (MSG_NOTE, vect_location,
202 "=== vect_determine_vectorization_factor ===\n");
204 for (i = 0; i < nbbs; i++)
206 basic_block bb = bbs[i];
208 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
209 gsi_next (&si))
211 phi = si.phi ();
212 stmt_info = vinfo_for_stmt (phi);
213 if (dump_enabled_p ())
215 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: ");
216 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
219 gcc_assert (stmt_info);
221 if (STMT_VINFO_RELEVANT_P (stmt_info)
222 || STMT_VINFO_LIVE_P (stmt_info))
224 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
225 scalar_type = TREE_TYPE (PHI_RESULT (phi));
227 if (dump_enabled_p ())
229 dump_printf_loc (MSG_NOTE, vect_location,
230 "get vectype for scalar type: ");
231 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
232 dump_printf (MSG_NOTE, "\n");
235 vectype = get_vectype_for_scalar_type (scalar_type);
236 if (!vectype)
238 if (dump_enabled_p ())
240 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
241 "not vectorized: unsupported "
242 "data-type ");
243 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
244 scalar_type);
245 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
247 return false;
249 STMT_VINFO_VECTYPE (stmt_info) = vectype;
251 if (dump_enabled_p ())
253 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
254 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
255 dump_printf (MSG_NOTE, "\n");
258 nunits = TYPE_VECTOR_SUBPARTS (vectype);
259 if (dump_enabled_p ())
260 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n",
261 nunits);
263 if (!vectorization_factor
264 || (nunits > vectorization_factor))
265 vectorization_factor = nunits;
269 for (gimple_stmt_iterator si = gsi_start_bb (bb);
270 !gsi_end_p (si) || analyze_pattern_stmt;)
272 tree vf_vectype;
274 if (analyze_pattern_stmt)
275 stmt = pattern_stmt;
276 else
277 stmt = gsi_stmt (si);
279 stmt_info = vinfo_for_stmt (stmt);
281 if (dump_enabled_p ())
283 dump_printf_loc (MSG_NOTE, vect_location,
284 "==> examining statement: ");
285 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
288 gcc_assert (stmt_info);
290 /* Skip stmts which do not need to be vectorized. */
291 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
292 && !STMT_VINFO_LIVE_P (stmt_info))
293 || gimple_clobber_p (stmt))
295 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
296 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
297 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
298 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
300 stmt = pattern_stmt;
301 stmt_info = vinfo_for_stmt (pattern_stmt);
302 if (dump_enabled_p ())
304 dump_printf_loc (MSG_NOTE, vect_location,
305 "==> examining pattern statement: ");
306 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
309 else
311 if (dump_enabled_p ())
312 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
313 gsi_next (&si);
314 continue;
317 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
318 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
319 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
320 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
321 analyze_pattern_stmt = true;
323 /* If a pattern statement has def stmts, analyze them too. */
324 if (is_pattern_stmt_p (stmt_info))
326 if (pattern_def_seq == NULL)
328 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
329 pattern_def_si = gsi_start (pattern_def_seq);
331 else if (!gsi_end_p (pattern_def_si))
332 gsi_next (&pattern_def_si);
333 if (pattern_def_seq != NULL)
335 gimple *pattern_def_stmt = NULL;
336 stmt_vec_info pattern_def_stmt_info = NULL;
338 while (!gsi_end_p (pattern_def_si))
340 pattern_def_stmt = gsi_stmt (pattern_def_si);
341 pattern_def_stmt_info
342 = vinfo_for_stmt (pattern_def_stmt);
343 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
344 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
345 break;
346 gsi_next (&pattern_def_si);
349 if (!gsi_end_p (pattern_def_si))
351 if (dump_enabled_p ())
353 dump_printf_loc (MSG_NOTE, vect_location,
354 "==> examining pattern def stmt: ");
355 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
356 pattern_def_stmt, 0);
359 stmt = pattern_def_stmt;
360 stmt_info = pattern_def_stmt_info;
362 else
364 pattern_def_si = gsi_none ();
365 analyze_pattern_stmt = false;
368 else
369 analyze_pattern_stmt = false;
372 if (gimple_get_lhs (stmt) == NULL_TREE
373 /* MASK_STORE has no lhs, but is ok. */
374 && (!is_gimple_call (stmt)
375 || !gimple_call_internal_p (stmt)
376 || gimple_call_internal_fn (stmt) != IFN_MASK_STORE))
378 if (is_gimple_call (stmt))
380 /* Ignore calls with no lhs. These must be calls to
381 #pragma omp simd functions, and what vectorization factor
382 it really needs can't be determined until
383 vectorizable_simd_clone_call. */
384 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
386 pattern_def_seq = NULL;
387 gsi_next (&si);
389 continue;
391 if (dump_enabled_p ())
393 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
394 "not vectorized: irregular stmt.");
395 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
398 return false;
401 if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
403 if (dump_enabled_p ())
405 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
406 "not vectorized: vector stmt in loop:");
407 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
409 return false;
412 bool_result = false;
414 if (STMT_VINFO_VECTYPE (stmt_info))
416 /* The only case when a vectype had been already set is for stmts
417 that contain a dataref, or for "pattern-stmts" (stmts
418 generated by the vectorizer to represent/replace a certain
419 idiom). */
420 gcc_assert (STMT_VINFO_DATA_REF (stmt_info)
421 || is_pattern_stmt_p (stmt_info)
422 || !gsi_end_p (pattern_def_si));
423 vectype = STMT_VINFO_VECTYPE (stmt_info);
425 else
427 gcc_assert (!STMT_VINFO_DATA_REF (stmt_info));
428 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
429 scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
430 else
431 scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
433 /* Bool ops don't participate in vectorization factor
434 computation. For comparison use compared types to
435 compute a factor. */
436 if (TREE_CODE (scalar_type) == BOOLEAN_TYPE
437 && is_gimple_assign (stmt)
438 && gimple_assign_rhs_code (stmt) != COND_EXPR)
440 if (STMT_VINFO_RELEVANT_P (stmt_info)
441 || STMT_VINFO_LIVE_P (stmt_info))
442 mask_producers.safe_push (stmt_info);
443 bool_result = true;
445 if (gimple_code (stmt) == GIMPLE_ASSIGN
446 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
447 == tcc_comparison
448 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt)))
449 != BOOLEAN_TYPE)
450 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
451 else
453 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
455 pattern_def_seq = NULL;
456 gsi_next (&si);
458 continue;
462 if (dump_enabled_p ())
464 dump_printf_loc (MSG_NOTE, vect_location,
465 "get vectype for scalar type: ");
466 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
467 dump_printf (MSG_NOTE, "\n");
469 vectype = get_vectype_for_scalar_type (scalar_type);
470 if (!vectype)
472 if (dump_enabled_p ())
474 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
475 "not vectorized: unsupported "
476 "data-type ");
477 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
478 scalar_type);
479 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
481 return false;
484 if (!bool_result)
485 STMT_VINFO_VECTYPE (stmt_info) = vectype;
487 if (dump_enabled_p ())
489 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
490 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
491 dump_printf (MSG_NOTE, "\n");
495 /* Don't try to compute VF out scalar types if we stmt
496 produces boolean vector. Use result vectype instead. */
497 if (VECTOR_BOOLEAN_TYPE_P (vectype))
498 vf_vectype = vectype;
499 else
501 /* The vectorization factor is according to the smallest
502 scalar type (or the largest vector size, but we only
503 support one vector size per loop). */
504 if (!bool_result)
505 scalar_type = vect_get_smallest_scalar_type (stmt, &dummy,
506 &dummy);
507 if (dump_enabled_p ())
509 dump_printf_loc (MSG_NOTE, vect_location,
510 "get vectype for scalar type: ");
511 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
512 dump_printf (MSG_NOTE, "\n");
514 vf_vectype = get_vectype_for_scalar_type (scalar_type);
516 if (!vf_vectype)
518 if (dump_enabled_p ())
520 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
521 "not vectorized: unsupported data-type ");
522 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
523 scalar_type);
524 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
526 return false;
529 if ((GET_MODE_SIZE (TYPE_MODE (vectype))
530 != GET_MODE_SIZE (TYPE_MODE (vf_vectype))))
532 if (dump_enabled_p ())
534 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
535 "not vectorized: different sized vector "
536 "types in statement, ");
537 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
538 vectype);
539 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
540 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
541 vf_vectype);
542 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
544 return false;
547 if (dump_enabled_p ())
549 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
550 dump_generic_expr (MSG_NOTE, TDF_SLIM, vf_vectype);
551 dump_printf (MSG_NOTE, "\n");
554 nunits = TYPE_VECTOR_SUBPARTS (vf_vectype);
555 if (dump_enabled_p ())
556 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n", nunits);
557 if (!vectorization_factor
558 || (nunits > vectorization_factor))
559 vectorization_factor = nunits;
561 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
563 pattern_def_seq = NULL;
564 gsi_next (&si);
569 /* TODO: Analyze cost. Decide if worth while to vectorize. */
570 if (dump_enabled_p ())
571 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = %d\n",
572 vectorization_factor);
573 if (vectorization_factor <= 1)
575 if (dump_enabled_p ())
576 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
577 "not vectorized: unsupported data-type\n");
578 return false;
580 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
582 for (i = 0; i < mask_producers.length (); i++)
584 tree mask_type = NULL;
586 stmt = STMT_VINFO_STMT (mask_producers[i]);
588 if (gimple_code (stmt) == GIMPLE_ASSIGN
589 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison
590 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt))) != BOOLEAN_TYPE)
592 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
593 mask_type = get_mask_type_for_scalar_type (scalar_type);
595 if (!mask_type)
597 if (dump_enabled_p ())
598 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
599 "not vectorized: unsupported mask\n");
600 return false;
603 else
605 tree rhs;
606 ssa_op_iter iter;
607 gimple *def_stmt;
608 enum vect_def_type dt;
610 FOR_EACH_SSA_TREE_OPERAND (rhs, stmt, iter, SSA_OP_USE)
612 if (!vect_is_simple_use (rhs, mask_producers[i]->vinfo,
613 &def_stmt, &dt, &vectype))
615 if (dump_enabled_p ())
617 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
618 "not vectorized: can't compute mask type "
619 "for statement, ");
620 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
623 return false;
626 /* No vectype probably means external definition.
627 Allow it in case there is another operand which
628 allows to determine mask type. */
629 if (!vectype)
630 continue;
632 if (!mask_type)
633 mask_type = vectype;
634 else if (TYPE_VECTOR_SUBPARTS (mask_type)
635 != TYPE_VECTOR_SUBPARTS (vectype))
637 if (dump_enabled_p ())
639 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
640 "not vectorized: different sized masks "
641 "types in statement, ");
642 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
643 mask_type);
644 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
645 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
646 vectype);
647 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
649 return false;
651 else if (VECTOR_BOOLEAN_TYPE_P (mask_type)
652 != VECTOR_BOOLEAN_TYPE_P (vectype))
654 if (dump_enabled_p ())
656 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
657 "not vectorized: mixed mask and "
658 "nonmask vector types in statement, ");
659 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
660 mask_type);
661 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
662 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
663 vectype);
664 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
666 return false;
670 /* We may compare boolean value loaded as vector of integers.
671 Fix mask_type in such case. */
672 if (mask_type
673 && !VECTOR_BOOLEAN_TYPE_P (mask_type)
674 && gimple_code (stmt) == GIMPLE_ASSIGN
675 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
676 mask_type = build_same_sized_truth_vector_type (mask_type);
679 /* No mask_type should mean loop invariant predicate.
680 This is probably a subject for optimization in
681 if-conversion. */
682 if (!mask_type)
684 if (dump_enabled_p ())
686 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
687 "not vectorized: can't compute mask type "
688 "for statement, ");
689 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
692 return false;
695 STMT_VINFO_VECTYPE (mask_producers[i]) = mask_type;
698 return true;
702 /* Function vect_is_simple_iv_evolution.
704 FORNOW: A simple evolution of an induction variables in the loop is
705 considered a polynomial evolution. */
707 static bool
708 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
709 tree * step)
711 tree init_expr;
712 tree step_expr;
713 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
714 basic_block bb;
716 /* When there is no evolution in this loop, the evolution function
717 is not "simple". */
718 if (evolution_part == NULL_TREE)
719 return false;
721 /* When the evolution is a polynomial of degree >= 2
722 the evolution function is not "simple". */
723 if (tree_is_chrec (evolution_part))
724 return false;
726 step_expr = evolution_part;
727 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
729 if (dump_enabled_p ())
731 dump_printf_loc (MSG_NOTE, vect_location, "step: ");
732 dump_generic_expr (MSG_NOTE, TDF_SLIM, step_expr);
733 dump_printf (MSG_NOTE, ", init: ");
734 dump_generic_expr (MSG_NOTE, TDF_SLIM, init_expr);
735 dump_printf (MSG_NOTE, "\n");
738 *init = init_expr;
739 *step = step_expr;
741 if (TREE_CODE (step_expr) != INTEGER_CST
742 && (TREE_CODE (step_expr) != SSA_NAME
743 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
744 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
745 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
746 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
747 || !flag_associative_math)))
748 && (TREE_CODE (step_expr) != REAL_CST
749 || !flag_associative_math))
751 if (dump_enabled_p ())
752 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
753 "step unknown.\n");
754 return false;
757 return true;
760 /* Function vect_analyze_scalar_cycles_1.
762 Examine the cross iteration def-use cycles of scalar variables
763 in LOOP. LOOP_VINFO represents the loop that is now being
764 considered for vectorization (can be LOOP, or an outer-loop
765 enclosing LOOP). */
767 static void
768 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, struct loop *loop)
770 basic_block bb = loop->header;
771 tree init, step;
772 auto_vec<gimple *, 64> worklist;
773 gphi_iterator gsi;
774 bool double_reduc;
776 if (dump_enabled_p ())
777 dump_printf_loc (MSG_NOTE, vect_location,
778 "=== vect_analyze_scalar_cycles ===\n");
780 /* First - identify all inductions. Reduction detection assumes that all the
781 inductions have been identified, therefore, this order must not be
782 changed. */
783 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
785 gphi *phi = gsi.phi ();
786 tree access_fn = NULL;
787 tree def = PHI_RESULT (phi);
788 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
790 if (dump_enabled_p ())
792 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
793 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
796 /* Skip virtual phi's. The data dependences that are associated with
797 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
798 if (virtual_operand_p (def))
799 continue;
801 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
803 /* Analyze the evolution function. */
804 access_fn = analyze_scalar_evolution (loop, def);
805 if (access_fn)
807 STRIP_NOPS (access_fn);
808 if (dump_enabled_p ())
810 dump_printf_loc (MSG_NOTE, vect_location,
811 "Access function of PHI: ");
812 dump_generic_expr (MSG_NOTE, TDF_SLIM, access_fn);
813 dump_printf (MSG_NOTE, "\n");
815 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
816 = initial_condition_in_loop_num (access_fn, loop->num);
817 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
818 = evolution_part_in_loop_num (access_fn, loop->num);
821 if (!access_fn
822 || !vect_is_simple_iv_evolution (loop->num, access_fn, &init, &step)
823 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
824 && TREE_CODE (step) != INTEGER_CST))
826 worklist.safe_push (phi);
827 continue;
830 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
831 != NULL_TREE);
832 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
834 if (dump_enabled_p ())
835 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
836 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
840 /* Second - identify all reductions and nested cycles. */
841 while (worklist.length () > 0)
843 gimple *phi = worklist.pop ();
844 tree def = PHI_RESULT (phi);
845 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
846 gimple *reduc_stmt;
847 bool nested_cycle;
849 if (dump_enabled_p ())
851 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
852 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
855 gcc_assert (!virtual_operand_p (def)
856 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
858 nested_cycle = (loop != LOOP_VINFO_LOOP (loop_vinfo));
859 reduc_stmt = vect_force_simple_reduction (loop_vinfo, phi, !nested_cycle,
860 &double_reduc, false);
861 if (reduc_stmt)
863 if (double_reduc)
865 if (dump_enabled_p ())
866 dump_printf_loc (MSG_NOTE, vect_location,
867 "Detected double reduction.\n");
869 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
870 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
871 vect_double_reduction_def;
873 else
875 if (nested_cycle)
877 if (dump_enabled_p ())
878 dump_printf_loc (MSG_NOTE, vect_location,
879 "Detected vectorizable nested cycle.\n");
881 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
882 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
883 vect_nested_cycle;
885 else
887 if (dump_enabled_p ())
888 dump_printf_loc (MSG_NOTE, vect_location,
889 "Detected reduction.\n");
891 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
892 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
893 vect_reduction_def;
894 /* Store the reduction cycles for possible vectorization in
895 loop-aware SLP. */
896 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt);
900 else
901 if (dump_enabled_p ())
902 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
903 "Unknown def-use cycle pattern.\n");
908 /* Function vect_analyze_scalar_cycles.
910 Examine the cross iteration def-use cycles of scalar variables, by
911 analyzing the loop-header PHIs of scalar variables. Classify each
912 cycle as one of the following: invariant, induction, reduction, unknown.
913 We do that for the loop represented by LOOP_VINFO, and also to its
914 inner-loop, if exists.
915 Examples for scalar cycles:
917 Example1: reduction:
919 loop1:
920 for (i=0; i<N; i++)
921 sum += a[i];
923 Example2: induction:
925 loop2:
926 for (i=0; i<N; i++)
927 a[i] = i; */
929 static void
930 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
932 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
934 vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
936 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
937 Reductions in such inner-loop therefore have different properties than
938 the reductions in the nest that gets vectorized:
939 1. When vectorized, they are executed in the same order as in the original
940 scalar loop, so we can't change the order of computation when
941 vectorizing them.
942 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
943 current checks are too strict. */
945 if (loop->inner)
946 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
949 /* Transfer group and reduction information from STMT to its pattern stmt. */
951 static void
952 vect_fixup_reduc_chain (gimple *stmt)
954 gimple *firstp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
955 gimple *stmtp;
956 gcc_assert (!GROUP_FIRST_ELEMENT (vinfo_for_stmt (firstp))
957 && GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
958 GROUP_SIZE (vinfo_for_stmt (firstp)) = GROUP_SIZE (vinfo_for_stmt (stmt));
961 stmtp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
962 GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmtp)) = firstp;
963 stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmt));
964 if (stmt)
965 GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmtp))
966 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
968 while (stmt);
969 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmtp)) = vect_reduction_def;
972 /* Fixup scalar cycles that now have their stmts detected as patterns. */
974 static void
975 vect_fixup_scalar_cycles_with_patterns (loop_vec_info loop_vinfo)
977 gimple *first;
978 unsigned i;
980 FOR_EACH_VEC_ELT (LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo), i, first)
981 if (STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (first)))
983 gimple *next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (first));
984 while (next)
986 if (! STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (next)))
987 break;
988 next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
990 /* If not all stmt in the chain are patterns try to handle
991 the chain without patterns. */
992 if (! next)
994 vect_fixup_reduc_chain (first);
995 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo)[i]
996 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (first));
1001 /* Function vect_get_loop_niters.
1003 Determine how many iterations the loop is executed and place it
1004 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
1005 in NUMBER_OF_ITERATIONSM1. Place the condition under which the
1006 niter information holds in ASSUMPTIONS.
1008 Return the loop exit condition. */
1011 static gcond *
1012 vect_get_loop_niters (struct loop *loop, tree *assumptions,
1013 tree *number_of_iterations, tree *number_of_iterationsm1)
1015 edge exit = single_exit (loop);
1016 struct tree_niter_desc niter_desc;
1017 tree niter_assumptions, niter, may_be_zero;
1018 gcond *cond = get_loop_exit_condition (loop);
1020 *assumptions = boolean_true_node;
1021 *number_of_iterationsm1 = chrec_dont_know;
1022 *number_of_iterations = chrec_dont_know;
1023 if (dump_enabled_p ())
1024 dump_printf_loc (MSG_NOTE, vect_location,
1025 "=== get_loop_niters ===\n");
1027 if (!exit)
1028 return cond;
1030 niter = chrec_dont_know;
1031 may_be_zero = NULL_TREE;
1032 niter_assumptions = boolean_true_node;
1033 if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
1034 || chrec_contains_undetermined (niter_desc.niter))
1035 return cond;
1037 niter_assumptions = niter_desc.assumptions;
1038 may_be_zero = niter_desc.may_be_zero;
1039 niter = niter_desc.niter;
1041 if (may_be_zero && integer_zerop (may_be_zero))
1042 may_be_zero = NULL_TREE;
1044 if (may_be_zero)
1046 if (COMPARISON_CLASS_P (may_be_zero))
1048 /* Try to combine may_be_zero with assumptions, this can simplify
1049 computation of niter expression. */
1050 if (niter_assumptions && !integer_nonzerop (niter_assumptions))
1051 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1052 niter_assumptions,
1053 fold_build1 (TRUTH_NOT_EXPR,
1054 boolean_type_node,
1055 may_be_zero));
1056 else
1057 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
1058 build_int_cst (TREE_TYPE (niter), 0), niter);
1060 may_be_zero = NULL_TREE;
1062 else if (integer_nonzerop (may_be_zero))
1064 *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
1065 *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
1066 return cond;
1068 else
1069 return cond;
1072 *assumptions = niter_assumptions;
1073 *number_of_iterationsm1 = niter;
1075 /* We want the number of loop header executions which is the number
1076 of latch executions plus one.
1077 ??? For UINT_MAX latch executions this number overflows to zero
1078 for loops like do { n++; } while (n != 0); */
1079 if (niter && !chrec_contains_undetermined (niter))
1080 niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), unshare_expr (niter),
1081 build_int_cst (TREE_TYPE (niter), 1));
1082 *number_of_iterations = niter;
1084 return cond;
1087 /* Function bb_in_loop_p
1089 Used as predicate for dfs order traversal of the loop bbs. */
1091 static bool
1092 bb_in_loop_p (const_basic_block bb, const void *data)
1094 const struct loop *const loop = (const struct loop *)data;
1095 if (flow_bb_inside_loop_p (loop, bb))
1096 return true;
1097 return false;
1101 /* Function new_loop_vec_info.
1103 Create and initialize a new loop_vec_info struct for LOOP, as well as
1104 stmt_vec_info structs for all the stmts in LOOP. */
1106 static loop_vec_info
1107 new_loop_vec_info (struct loop *loop)
1109 loop_vec_info res;
1110 basic_block *bbs;
1111 gimple_stmt_iterator si;
1112 unsigned int i, nbbs;
1114 res = (loop_vec_info) xcalloc (1, sizeof (struct _loop_vec_info));
1115 res->kind = vec_info::loop;
1116 LOOP_VINFO_LOOP (res) = loop;
1118 bbs = get_loop_body (loop);
1120 /* Create/Update stmt_info for all stmts in the loop. */
1121 for (i = 0; i < loop->num_nodes; i++)
1123 basic_block bb = bbs[i];
1125 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1127 gimple *phi = gsi_stmt (si);
1128 gimple_set_uid (phi, 0);
1129 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, res));
1132 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1134 gimple *stmt = gsi_stmt (si);
1135 gimple_set_uid (stmt, 0);
1136 set_vinfo_for_stmt (stmt, new_stmt_vec_info (stmt, res));
1140 /* CHECKME: We want to visit all BBs before their successors (except for
1141 latch blocks, for which this assertion wouldn't hold). In the simple
1142 case of the loop forms we allow, a dfs order of the BBs would the same
1143 as reversed postorder traversal, so we are safe. */
1145 free (bbs);
1146 bbs = XCNEWVEC (basic_block, loop->num_nodes);
1147 nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p,
1148 bbs, loop->num_nodes, loop);
1149 gcc_assert (nbbs == loop->num_nodes);
1151 LOOP_VINFO_BBS (res) = bbs;
1152 LOOP_VINFO_NITERSM1 (res) = NULL;
1153 LOOP_VINFO_NITERS (res) = NULL;
1154 LOOP_VINFO_NITERS_UNCHANGED (res) = NULL;
1155 LOOP_VINFO_NITERS_ASSUMPTIONS (res) = NULL;
1156 LOOP_VINFO_COST_MODEL_THRESHOLD (res) = 0;
1157 LOOP_VINFO_VECTORIZABLE_P (res) = 0;
1158 LOOP_VINFO_PEELING_FOR_ALIGNMENT (res) = 0;
1159 LOOP_VINFO_VECT_FACTOR (res) = 0;
1160 LOOP_VINFO_LOOP_NEST (res) = vNULL;
1161 LOOP_VINFO_DATAREFS (res) = vNULL;
1162 LOOP_VINFO_DDRS (res) = vNULL;
1163 LOOP_VINFO_UNALIGNED_DR (res) = NULL;
1164 LOOP_VINFO_MAY_MISALIGN_STMTS (res) = vNULL;
1165 LOOP_VINFO_MAY_ALIAS_DDRS (res) = vNULL;
1166 LOOP_VINFO_GROUPED_STORES (res) = vNULL;
1167 LOOP_VINFO_REDUCTIONS (res) = vNULL;
1168 LOOP_VINFO_REDUCTION_CHAINS (res) = vNULL;
1169 LOOP_VINFO_SLP_INSTANCES (res) = vNULL;
1170 LOOP_VINFO_SLP_UNROLLING_FACTOR (res) = 1;
1171 LOOP_VINFO_TARGET_COST_DATA (res) = init_cost (loop);
1172 LOOP_VINFO_PEELING_FOR_GAPS (res) = false;
1173 LOOP_VINFO_PEELING_FOR_NITER (res) = false;
1174 LOOP_VINFO_OPERANDS_SWAPPED (res) = false;
1175 LOOP_VINFO_ORIG_LOOP_INFO (res) = NULL;
1177 return res;
1181 /* Function destroy_loop_vec_info.
1183 Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the
1184 stmts in the loop. */
1186 void
1187 destroy_loop_vec_info (loop_vec_info loop_vinfo, bool clean_stmts)
1189 struct loop *loop;
1190 basic_block *bbs;
1191 int nbbs;
1192 gimple_stmt_iterator si;
1193 int j;
1194 vec<slp_instance> slp_instances;
1195 slp_instance instance;
1196 bool swapped;
1198 if (!loop_vinfo)
1199 return;
1201 loop = LOOP_VINFO_LOOP (loop_vinfo);
1203 bbs = LOOP_VINFO_BBS (loop_vinfo);
1204 nbbs = clean_stmts ? loop->num_nodes : 0;
1205 swapped = LOOP_VINFO_OPERANDS_SWAPPED (loop_vinfo);
1207 for (j = 0; j < nbbs; j++)
1209 basic_block bb = bbs[j];
1210 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1211 free_stmt_vec_info (gsi_stmt (si));
1213 for (si = gsi_start_bb (bb); !gsi_end_p (si); )
1215 gimple *stmt = gsi_stmt (si);
1217 /* We may have broken canonical form by moving a constant
1218 into RHS1 of a commutative op. Fix such occurrences. */
1219 if (swapped && is_gimple_assign (stmt))
1221 enum tree_code code = gimple_assign_rhs_code (stmt);
1223 if ((code == PLUS_EXPR
1224 || code == POINTER_PLUS_EXPR
1225 || code == MULT_EXPR)
1226 && CONSTANT_CLASS_P (gimple_assign_rhs1 (stmt)))
1227 swap_ssa_operands (stmt,
1228 gimple_assign_rhs1_ptr (stmt),
1229 gimple_assign_rhs2_ptr (stmt));
1230 else if (code == COND_EXPR
1231 && CONSTANT_CLASS_P (gimple_assign_rhs2 (stmt)))
1233 tree cond_expr = gimple_assign_rhs1 (stmt);
1234 enum tree_code cond_code = TREE_CODE (cond_expr);
1236 if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
1238 bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr,
1239 0));
1240 cond_code = invert_tree_comparison (cond_code,
1241 honor_nans);
1242 if (cond_code != ERROR_MARK)
1244 TREE_SET_CODE (cond_expr, cond_code);
1245 swap_ssa_operands (stmt,
1246 gimple_assign_rhs2_ptr (stmt),
1247 gimple_assign_rhs3_ptr (stmt));
1253 /* Free stmt_vec_info. */
1254 free_stmt_vec_info (stmt);
1255 gsi_next (&si);
1259 free (LOOP_VINFO_BBS (loop_vinfo));
1260 vect_destroy_datarefs (loop_vinfo);
1261 free_dependence_relations (LOOP_VINFO_DDRS (loop_vinfo));
1262 LOOP_VINFO_LOOP_NEST (loop_vinfo).release ();
1263 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).release ();
1264 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
1265 LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).release ();
1266 slp_instances = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
1267 FOR_EACH_VEC_ELT (slp_instances, j, instance)
1268 vect_free_slp_instance (instance);
1270 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
1271 LOOP_VINFO_GROUPED_STORES (loop_vinfo).release ();
1272 LOOP_VINFO_REDUCTIONS (loop_vinfo).release ();
1273 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).release ();
1275 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
1276 loop_vinfo->scalar_cost_vec.release ();
1278 free (loop_vinfo);
1279 loop->aux = NULL;
1283 /* Calculate the cost of one scalar iteration of the loop. */
1284 static void
1285 vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
1287 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1288 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1289 int nbbs = loop->num_nodes, factor, scalar_single_iter_cost = 0;
1290 int innerloop_iters, i;
1292 /* Count statements in scalar loop. Using this as scalar cost for a single
1293 iteration for now.
1295 TODO: Add outer loop support.
1297 TODO: Consider assigning different costs to different scalar
1298 statements. */
1300 /* FORNOW. */
1301 innerloop_iters = 1;
1302 if (loop->inner)
1303 innerloop_iters = 50; /* FIXME */
1305 for (i = 0; i < nbbs; i++)
1307 gimple_stmt_iterator si;
1308 basic_block bb = bbs[i];
1310 if (bb->loop_father == loop->inner)
1311 factor = innerloop_iters;
1312 else
1313 factor = 1;
1315 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1317 gimple *stmt = gsi_stmt (si);
1318 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1320 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1321 continue;
1323 /* Skip stmts that are not vectorized inside the loop. */
1324 if (stmt_info
1325 && !STMT_VINFO_RELEVANT_P (stmt_info)
1326 && (!STMT_VINFO_LIVE_P (stmt_info)
1327 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1328 && !STMT_VINFO_IN_PATTERN_P (stmt_info))
1329 continue;
1331 vect_cost_for_stmt kind;
1332 if (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt)))
1334 if (DR_IS_READ (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt))))
1335 kind = scalar_load;
1336 else
1337 kind = scalar_store;
1339 else
1340 kind = scalar_stmt;
1342 scalar_single_iter_cost
1343 += record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1344 factor, kind, NULL, 0, vect_prologue);
1347 LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo)
1348 = scalar_single_iter_cost;
1352 /* Function vect_analyze_loop_form_1.
1354 Verify that certain CFG restrictions hold, including:
1355 - the loop has a pre-header
1356 - the loop has a single entry and exit
1357 - the loop exit condition is simple enough
1358 - the number of iterations can be analyzed, i.e, a countable loop. The
1359 niter could be analyzed under some assumptions. */
1361 bool
1362 vect_analyze_loop_form_1 (struct loop *loop, gcond **loop_cond,
1363 tree *assumptions, tree *number_of_iterationsm1,
1364 tree *number_of_iterations, gcond **inner_loop_cond)
1366 if (dump_enabled_p ())
1367 dump_printf_loc (MSG_NOTE, vect_location,
1368 "=== vect_analyze_loop_form ===\n");
1370 /* Different restrictions apply when we are considering an inner-most loop,
1371 vs. an outer (nested) loop.
1372 (FORNOW. May want to relax some of these restrictions in the future). */
1374 if (!loop->inner)
1376 /* Inner-most loop. We currently require that the number of BBs is
1377 exactly 2 (the header and latch). Vectorizable inner-most loops
1378 look like this:
1380 (pre-header)
1382 header <--------+
1383 | | |
1384 | +--> latch --+
1386 (exit-bb) */
1388 if (loop->num_nodes != 2)
1390 if (dump_enabled_p ())
1391 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1392 "not vectorized: control flow in loop.\n");
1393 return false;
1396 if (empty_block_p (loop->header))
1398 if (dump_enabled_p ())
1399 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1400 "not vectorized: empty loop.\n");
1401 return false;
1404 else
1406 struct loop *innerloop = loop->inner;
1407 edge entryedge;
1409 /* Nested loop. We currently require that the loop is doubly-nested,
1410 contains a single inner loop, and the number of BBs is exactly 5.
1411 Vectorizable outer-loops look like this:
1413 (pre-header)
1415 header <---+
1417 inner-loop |
1419 tail ------+
1421 (exit-bb)
1423 The inner-loop has the properties expected of inner-most loops
1424 as described above. */
1426 if ((loop->inner)->inner || (loop->inner)->next)
1428 if (dump_enabled_p ())
1429 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1430 "not vectorized: multiple nested loops.\n");
1431 return false;
1434 if (loop->num_nodes != 5)
1436 if (dump_enabled_p ())
1437 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1438 "not vectorized: control flow in loop.\n");
1439 return false;
1442 entryedge = loop_preheader_edge (innerloop);
1443 if (entryedge->src != loop->header
1444 || !single_exit (innerloop)
1445 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1447 if (dump_enabled_p ())
1448 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1449 "not vectorized: unsupported outerloop form.\n");
1450 return false;
1453 /* Analyze the inner-loop. */
1454 tree inner_niterm1, inner_niter, inner_assumptions;
1455 if (! vect_analyze_loop_form_1 (loop->inner, inner_loop_cond,
1456 &inner_assumptions, &inner_niterm1,
1457 &inner_niter, NULL)
1458 /* Don't support analyzing niter under assumptions for inner
1459 loop. */
1460 || !integer_onep (inner_assumptions))
1462 if (dump_enabled_p ())
1463 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1464 "not vectorized: Bad inner loop.\n");
1465 return false;
1468 if (!expr_invariant_in_loop_p (loop, inner_niter))
1470 if (dump_enabled_p ())
1471 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1472 "not vectorized: inner-loop count not"
1473 " invariant.\n");
1474 return false;
1477 if (dump_enabled_p ())
1478 dump_printf_loc (MSG_NOTE, vect_location,
1479 "Considering outer-loop vectorization.\n");
1482 if (!single_exit (loop)
1483 || EDGE_COUNT (loop->header->preds) != 2)
1485 if (dump_enabled_p ())
1487 if (!single_exit (loop))
1488 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1489 "not vectorized: multiple exits.\n");
1490 else if (EDGE_COUNT (loop->header->preds) != 2)
1491 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1492 "not vectorized: too many incoming edges.\n");
1494 return false;
1497 /* We assume that the loop exit condition is at the end of the loop. i.e,
1498 that the loop is represented as a do-while (with a proper if-guard
1499 before the loop if needed), where the loop header contains all the
1500 executable statements, and the latch is empty. */
1501 if (!empty_block_p (loop->latch)
1502 || !gimple_seq_empty_p (phi_nodes (loop->latch)))
1504 if (dump_enabled_p ())
1505 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1506 "not vectorized: latch block not empty.\n");
1507 return false;
1510 /* Make sure the exit is not abnormal. */
1511 edge e = single_exit (loop);
1512 if (e->flags & EDGE_ABNORMAL)
1514 if (dump_enabled_p ())
1515 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1516 "not vectorized: abnormal loop exit edge.\n");
1517 return false;
1520 *loop_cond = vect_get_loop_niters (loop, assumptions, number_of_iterations,
1521 number_of_iterationsm1);
1522 if (!*loop_cond)
1524 if (dump_enabled_p ())
1525 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1526 "not vectorized: complicated exit condition.\n");
1527 return false;
1530 if (integer_zerop (*assumptions)
1531 || !*number_of_iterations
1532 || chrec_contains_undetermined (*number_of_iterations))
1534 if (dump_enabled_p ())
1535 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1536 "not vectorized: number of iterations cannot be "
1537 "computed.\n");
1538 return false;
1541 if (integer_zerop (*number_of_iterations))
1543 if (dump_enabled_p ())
1544 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1545 "not vectorized: number of iterations = 0.\n");
1546 return false;
1549 return true;
1552 /* Analyze LOOP form and return a loop_vec_info if it is of suitable form. */
1554 loop_vec_info
1555 vect_analyze_loop_form (struct loop *loop)
1557 tree assumptions, number_of_iterations, number_of_iterationsm1;
1558 gcond *loop_cond, *inner_loop_cond = NULL;
1560 if (! vect_analyze_loop_form_1 (loop, &loop_cond,
1561 &assumptions, &number_of_iterationsm1,
1562 &number_of_iterations, &inner_loop_cond))
1563 return NULL;
1565 loop_vec_info loop_vinfo = new_loop_vec_info (loop);
1566 LOOP_VINFO_NITERSM1 (loop_vinfo) = number_of_iterationsm1;
1567 LOOP_VINFO_NITERS (loop_vinfo) = number_of_iterations;
1568 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = number_of_iterations;
1569 if (!integer_onep (assumptions))
1571 /* We consider to vectorize this loop by versioning it under
1572 some assumptions. In order to do this, we need to clear
1573 existing information computed by scev and niter analyzer. */
1574 scev_reset_htab ();
1575 free_numbers_of_iterations_estimates_loop (loop);
1576 /* Also set flag for this loop so that following scev and niter
1577 analysis are done under the assumptions. */
1578 loop_constraint_set (loop, LOOP_C_FINITE);
1579 /* Also record the assumptions for versioning. */
1580 LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = assumptions;
1583 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
1585 if (dump_enabled_p ())
1587 dump_printf_loc (MSG_NOTE, vect_location,
1588 "Symbolic number of iterations is ");
1589 dump_generic_expr (MSG_NOTE, TDF_DETAILS, number_of_iterations);
1590 dump_printf (MSG_NOTE, "\n");
1594 STMT_VINFO_TYPE (vinfo_for_stmt (loop_cond)) = loop_exit_ctrl_vec_info_type;
1595 if (inner_loop_cond)
1596 STMT_VINFO_TYPE (vinfo_for_stmt (inner_loop_cond))
1597 = loop_exit_ctrl_vec_info_type;
1599 gcc_assert (!loop->aux);
1600 loop->aux = loop_vinfo;
1601 return loop_vinfo;
1606 /* Scan the loop stmts and dependent on whether there are any (non-)SLP
1607 statements update the vectorization factor. */
1609 static void
1610 vect_update_vf_for_slp (loop_vec_info loop_vinfo)
1612 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1613 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1614 int nbbs = loop->num_nodes;
1615 unsigned int vectorization_factor;
1616 int i;
1618 if (dump_enabled_p ())
1619 dump_printf_loc (MSG_NOTE, vect_location,
1620 "=== vect_update_vf_for_slp ===\n");
1622 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1623 gcc_assert (vectorization_factor != 0);
1625 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
1626 vectorization factor of the loop is the unrolling factor required by
1627 the SLP instances. If that unrolling factor is 1, we say, that we
1628 perform pure SLP on loop - cross iteration parallelism is not
1629 exploited. */
1630 bool only_slp_in_loop = true;
1631 for (i = 0; i < nbbs; i++)
1633 basic_block bb = bbs[i];
1634 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1635 gsi_next (&si))
1637 gimple *stmt = gsi_stmt (si);
1638 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1639 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
1640 && STMT_VINFO_RELATED_STMT (stmt_info))
1642 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
1643 stmt_info = vinfo_for_stmt (stmt);
1645 if ((STMT_VINFO_RELEVANT_P (stmt_info)
1646 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1647 && !PURE_SLP_STMT (stmt_info))
1648 /* STMT needs both SLP and loop-based vectorization. */
1649 only_slp_in_loop = false;
1653 if (only_slp_in_loop)
1654 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
1655 else
1656 vectorization_factor
1657 = least_common_multiple (vectorization_factor,
1658 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
1660 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
1661 if (dump_enabled_p ())
1662 dump_printf_loc (MSG_NOTE, vect_location,
1663 "Updating vectorization factor to %d\n",
1664 vectorization_factor);
1667 /* Function vect_analyze_loop_operations.
1669 Scan the loop stmts and make sure they are all vectorizable. */
1671 static bool
1672 vect_analyze_loop_operations (loop_vec_info loop_vinfo)
1674 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1675 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1676 int nbbs = loop->num_nodes;
1677 int i;
1678 stmt_vec_info stmt_info;
1679 bool need_to_vectorize = false;
1680 bool ok;
1682 if (dump_enabled_p ())
1683 dump_printf_loc (MSG_NOTE, vect_location,
1684 "=== vect_analyze_loop_operations ===\n");
1686 for (i = 0; i < nbbs; i++)
1688 basic_block bb = bbs[i];
1690 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
1691 gsi_next (&si))
1693 gphi *phi = si.phi ();
1694 ok = true;
1696 stmt_info = vinfo_for_stmt (phi);
1697 if (dump_enabled_p ())
1699 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: ");
1700 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
1702 if (virtual_operand_p (gimple_phi_result (phi)))
1703 continue;
1705 /* Inner-loop loop-closed exit phi in outer-loop vectorization
1706 (i.e., a phi in the tail of the outer-loop). */
1707 if (! is_loop_header_bb_p (bb))
1709 /* FORNOW: we currently don't support the case that these phis
1710 are not used in the outerloop (unless it is double reduction,
1711 i.e., this phi is vect_reduction_def), cause this case
1712 requires to actually do something here. */
1713 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
1714 || STMT_VINFO_LIVE_P (stmt_info))
1715 && STMT_VINFO_DEF_TYPE (stmt_info)
1716 != vect_double_reduction_def)
1718 if (dump_enabled_p ())
1719 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1720 "Unsupported loop-closed phi in "
1721 "outer-loop.\n");
1722 return false;
1725 /* If PHI is used in the outer loop, we check that its operand
1726 is defined in the inner loop. */
1727 if (STMT_VINFO_RELEVANT_P (stmt_info))
1729 tree phi_op;
1730 gimple *op_def_stmt;
1732 if (gimple_phi_num_args (phi) != 1)
1733 return false;
1735 phi_op = PHI_ARG_DEF (phi, 0);
1736 if (TREE_CODE (phi_op) != SSA_NAME)
1737 return false;
1739 op_def_stmt = SSA_NAME_DEF_STMT (phi_op);
1740 if (gimple_nop_p (op_def_stmt)
1741 || !flow_bb_inside_loop_p (loop, gimple_bb (op_def_stmt))
1742 || !vinfo_for_stmt (op_def_stmt))
1743 return false;
1745 if (STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1746 != vect_used_in_outer
1747 && STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1748 != vect_used_in_outer_by_reduction)
1749 return false;
1752 continue;
1755 gcc_assert (stmt_info);
1757 if ((STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
1758 || STMT_VINFO_LIVE_P (stmt_info))
1759 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
1761 /* A scalar-dependence cycle that we don't support. */
1762 if (dump_enabled_p ())
1763 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1764 "not vectorized: scalar dependence cycle.\n");
1765 return false;
1768 if (STMT_VINFO_RELEVANT_P (stmt_info))
1770 need_to_vectorize = true;
1771 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
1772 ok = vectorizable_induction (phi, NULL, NULL);
1775 if (ok && STMT_VINFO_LIVE_P (stmt_info))
1776 ok = vectorizable_live_operation (phi, NULL, NULL, -1, NULL);
1778 if (!ok)
1780 if (dump_enabled_p ())
1782 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1783 "not vectorized: relevant phi not "
1784 "supported: ");
1785 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, phi, 0);
1787 return false;
1791 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1792 gsi_next (&si))
1794 gimple *stmt = gsi_stmt (si);
1795 if (!gimple_clobber_p (stmt)
1796 && !vect_analyze_stmt (stmt, &need_to_vectorize, NULL))
1797 return false;
1799 } /* bbs */
1801 /* All operations in the loop are either irrelevant (deal with loop
1802 control, or dead), or only used outside the loop and can be moved
1803 out of the loop (e.g. invariants, inductions). The loop can be
1804 optimized away by scalar optimizations. We're better off not
1805 touching this loop. */
1806 if (!need_to_vectorize)
1808 if (dump_enabled_p ())
1809 dump_printf_loc (MSG_NOTE, vect_location,
1810 "All the computation can be taken out of the loop.\n");
1811 if (dump_enabled_p ())
1812 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1813 "not vectorized: redundant loop. no profit to "
1814 "vectorize.\n");
1815 return false;
1818 return true;
1822 /* Function vect_analyze_loop_2.
1824 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1825 for it. The different analyses will record information in the
1826 loop_vec_info struct. */
1827 static bool
1828 vect_analyze_loop_2 (loop_vec_info loop_vinfo, bool &fatal)
1830 bool ok;
1831 int max_vf = MAX_VECTORIZATION_FACTOR;
1832 int min_vf = 2;
1833 unsigned int n_stmts = 0;
1835 /* The first group of checks is independent of the vector size. */
1836 fatal = true;
1838 /* Find all data references in the loop (which correspond to vdefs/vuses)
1839 and analyze their evolution in the loop. */
1841 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1843 loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
1844 if (!find_loop_nest (loop, &LOOP_VINFO_LOOP_NEST (loop_vinfo)))
1846 if (dump_enabled_p ())
1847 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1848 "not vectorized: loop nest containing two "
1849 "or more consecutive inner loops cannot be "
1850 "vectorized\n");
1851 return false;
1854 for (unsigned i = 0; i < loop->num_nodes; i++)
1855 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
1856 !gsi_end_p (gsi); gsi_next (&gsi))
1858 gimple *stmt = gsi_stmt (gsi);
1859 if (is_gimple_debug (stmt))
1860 continue;
1861 ++n_stmts;
1862 if (!find_data_references_in_stmt (loop, stmt,
1863 &LOOP_VINFO_DATAREFS (loop_vinfo)))
1865 if (is_gimple_call (stmt) && loop->safelen)
1867 tree fndecl = gimple_call_fndecl (stmt), op;
1868 if (fndecl != NULL_TREE)
1870 cgraph_node *node = cgraph_node::get (fndecl);
1871 if (node != NULL && node->simd_clones != NULL)
1873 unsigned int j, n = gimple_call_num_args (stmt);
1874 for (j = 0; j < n; j++)
1876 op = gimple_call_arg (stmt, j);
1877 if (DECL_P (op)
1878 || (REFERENCE_CLASS_P (op)
1879 && get_base_address (op)))
1880 break;
1882 op = gimple_call_lhs (stmt);
1883 /* Ignore #pragma omp declare simd functions
1884 if they don't have data references in the
1885 call stmt itself. */
1886 if (j == n
1887 && !(op
1888 && (DECL_P (op)
1889 || (REFERENCE_CLASS_P (op)
1890 && get_base_address (op)))))
1891 continue;
1895 if (dump_enabled_p ())
1896 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1897 "not vectorized: loop contains function "
1898 "calls or data references that cannot "
1899 "be analyzed\n");
1900 return false;
1904 /* Analyze the data references and also adjust the minimal
1905 vectorization factor according to the loads and stores. */
1907 ok = vect_analyze_data_refs (loop_vinfo, &min_vf);
1908 if (!ok)
1910 if (dump_enabled_p ())
1911 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1912 "bad data references.\n");
1913 return false;
1916 /* Classify all cross-iteration scalar data-flow cycles.
1917 Cross-iteration cycles caused by virtual phis are analyzed separately. */
1918 vect_analyze_scalar_cycles (loop_vinfo);
1920 vect_pattern_recog (loop_vinfo);
1922 vect_fixup_scalar_cycles_with_patterns (loop_vinfo);
1924 /* Analyze the access patterns of the data-refs in the loop (consecutive,
1925 complex, etc.). FORNOW: Only handle consecutive access pattern. */
1927 ok = vect_analyze_data_ref_accesses (loop_vinfo);
1928 if (!ok)
1930 if (dump_enabled_p ())
1931 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1932 "bad data access.\n");
1933 return false;
1936 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
1938 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo);
1939 if (!ok)
1941 if (dump_enabled_p ())
1942 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1943 "unexpected pattern.\n");
1944 return false;
1947 /* While the rest of the analysis below depends on it in some way. */
1948 fatal = false;
1950 /* Analyze data dependences between the data-refs in the loop
1951 and adjust the maximum vectorization factor according to
1952 the dependences.
1953 FORNOW: fail at the first data dependence that we encounter. */
1955 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
1956 if (!ok
1957 || max_vf < min_vf)
1959 if (dump_enabled_p ())
1960 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1961 "bad data dependence.\n");
1962 return false;
1965 ok = vect_determine_vectorization_factor (loop_vinfo);
1966 if (!ok)
1968 if (dump_enabled_p ())
1969 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1970 "can't determine vectorization factor.\n");
1971 return false;
1973 if (max_vf < LOOP_VINFO_VECT_FACTOR (loop_vinfo))
1975 if (dump_enabled_p ())
1976 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1977 "bad data dependence.\n");
1978 return false;
1981 /* Compute the scalar iteration cost. */
1982 vect_compute_single_scalar_iteration_cost (loop_vinfo);
1984 int saved_vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1985 HOST_WIDE_INT estimated_niter;
1986 unsigned th;
1987 int min_scalar_loop_bound;
1989 /* Check the SLP opportunities in the loop, analyze and build SLP trees. */
1990 ok = vect_analyze_slp (loop_vinfo, n_stmts);
1991 if (!ok)
1992 return false;
1994 /* If there are any SLP instances mark them as pure_slp. */
1995 bool slp = vect_make_slp_decision (loop_vinfo);
1996 if (slp)
1998 /* Find stmts that need to be both vectorized and SLPed. */
1999 vect_detect_hybrid_slp (loop_vinfo);
2001 /* Update the vectorization factor based on the SLP decision. */
2002 vect_update_vf_for_slp (loop_vinfo);
2005 /* This is the point where we can re-start analysis with SLP forced off. */
2006 start_over:
2008 /* Now the vectorization factor is final. */
2009 unsigned vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2010 gcc_assert (vectorization_factor != 0);
2012 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
2013 dump_printf_loc (MSG_NOTE, vect_location,
2014 "vectorization_factor = %d, niters = "
2015 HOST_WIDE_INT_PRINT_DEC "\n", vectorization_factor,
2016 LOOP_VINFO_INT_NITERS (loop_vinfo));
2018 HOST_WIDE_INT max_niter
2019 = likely_max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2020 if ((LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2021 && (LOOP_VINFO_INT_NITERS (loop_vinfo) < vectorization_factor))
2022 || (max_niter != -1
2023 && (unsigned HOST_WIDE_INT) max_niter < vectorization_factor))
2025 if (dump_enabled_p ())
2026 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2027 "not vectorized: iteration count smaller than "
2028 "vectorization factor.\n");
2029 return false;
2032 /* Analyze the alignment of the data-refs in the loop.
2033 Fail if a data reference is found that cannot be vectorized. */
2035 ok = vect_analyze_data_refs_alignment (loop_vinfo);
2036 if (!ok)
2038 if (dump_enabled_p ())
2039 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2040 "bad data alignment.\n");
2041 return false;
2044 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
2045 It is important to call pruning after vect_analyze_data_ref_accesses,
2046 since we use grouping information gathered by interleaving analysis. */
2047 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
2048 if (!ok)
2049 return false;
2051 /* Do not invoke vect_enhance_data_refs_alignment for eplilogue
2052 vectorization. */
2053 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2055 /* This pass will decide on using loop versioning and/or loop peeling in
2056 order to enhance the alignment of data references in the loop. */
2057 ok = vect_enhance_data_refs_alignment (loop_vinfo);
2058 if (!ok)
2060 if (dump_enabled_p ())
2061 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2062 "bad data alignment.\n");
2063 return false;
2067 if (slp)
2069 /* Analyze operations in the SLP instances. Note this may
2070 remove unsupported SLP instances which makes the above
2071 SLP kind detection invalid. */
2072 unsigned old_size = LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length ();
2073 vect_slp_analyze_operations (LOOP_VINFO_SLP_INSTANCES (loop_vinfo),
2074 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2075 if (LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length () != old_size)
2076 goto again;
2079 /* Scan all the remaining operations in the loop that are not subject
2080 to SLP and make sure they are vectorizable. */
2081 ok = vect_analyze_loop_operations (loop_vinfo);
2082 if (!ok)
2084 if (dump_enabled_p ())
2085 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2086 "bad operation or unsupported loop bound.\n");
2087 return false;
2090 /* If epilog loop is required because of data accesses with gaps,
2091 one additional iteration needs to be peeled. Check if there is
2092 enough iterations for vectorization. */
2093 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2094 && LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2096 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2097 tree scalar_niters = LOOP_VINFO_NITERSM1 (loop_vinfo);
2099 if (wi::to_widest (scalar_niters) < vf)
2101 if (dump_enabled_p ())
2102 dump_printf_loc (MSG_NOTE, vect_location,
2103 "loop has no enough iterations to support"
2104 " peeling for gaps.\n");
2105 return false;
2109 /* Analyze cost. Decide if worth while to vectorize. */
2110 int min_profitable_estimate, min_profitable_iters;
2111 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
2112 &min_profitable_estimate);
2114 if (min_profitable_iters < 0)
2116 if (dump_enabled_p ())
2117 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2118 "not vectorized: vectorization not profitable.\n");
2119 if (dump_enabled_p ())
2120 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2121 "not vectorized: vector version will never be "
2122 "profitable.\n");
2123 goto again;
2126 min_scalar_loop_bound = ((PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
2127 * vectorization_factor) - 1);
2129 /* Use the cost model only if it is more conservative than user specified
2130 threshold. */
2131 th = (unsigned) min_scalar_loop_bound;
2132 if (min_profitable_iters
2133 && (!min_scalar_loop_bound
2134 || min_profitable_iters > min_scalar_loop_bound))
2135 th = (unsigned) min_profitable_iters;
2137 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
2139 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2140 && LOOP_VINFO_INT_NITERS (loop_vinfo) <= th)
2142 if (dump_enabled_p ())
2143 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2144 "not vectorized: vectorization not profitable.\n");
2145 if (dump_enabled_p ())
2146 dump_printf_loc (MSG_NOTE, vect_location,
2147 "not vectorized: iteration count smaller than user "
2148 "specified loop bound parameter or minimum profitable "
2149 "iterations (whichever is more conservative).\n");
2150 goto again;
2153 estimated_niter
2154 = estimated_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2155 if (estimated_niter == -1)
2156 estimated_niter = max_niter;
2157 if (estimated_niter != -1
2158 && ((unsigned HOST_WIDE_INT) estimated_niter
2159 <= MAX (th, (unsigned)min_profitable_estimate)))
2161 if (dump_enabled_p ())
2162 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2163 "not vectorized: estimated iteration count too "
2164 "small.\n");
2165 if (dump_enabled_p ())
2166 dump_printf_loc (MSG_NOTE, vect_location,
2167 "not vectorized: estimated iteration count smaller "
2168 "than specified loop bound parameter or minimum "
2169 "profitable iterations (whichever is more "
2170 "conservative).\n");
2171 goto again;
2174 /* Decide whether we need to create an epilogue loop to handle
2175 remaining scalar iterations. */
2176 th = ((LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) + 1)
2177 / LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2178 * LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2180 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2181 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
2183 if (ctz_hwi (LOOP_VINFO_INT_NITERS (loop_vinfo)
2184 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
2185 < exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
2186 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2188 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2189 || (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
2190 < (unsigned)exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2191 /* In case of versioning, check if the maximum number of
2192 iterations is greater than th. If they are identical,
2193 the epilogue is unnecessary. */
2194 && (!LOOP_REQUIRES_VERSIONING (loop_vinfo)
2195 || (unsigned HOST_WIDE_INT) max_niter > th)))
2196 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2198 /* If an epilogue loop is required make sure we can create one. */
2199 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2200 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
2202 if (dump_enabled_p ())
2203 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
2204 if (!vect_can_advance_ivs_p (loop_vinfo)
2205 || !slpeel_can_duplicate_loop_p (LOOP_VINFO_LOOP (loop_vinfo),
2206 single_exit (LOOP_VINFO_LOOP
2207 (loop_vinfo))))
2209 if (dump_enabled_p ())
2210 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2211 "not vectorized: can't create required "
2212 "epilog loop\n");
2213 goto again;
2217 gcc_assert (vectorization_factor
2218 == (unsigned)LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2220 /* Ok to vectorize! */
2221 return true;
2223 again:
2224 /* Try again with SLP forced off but if we didn't do any SLP there is
2225 no point in re-trying. */
2226 if (!slp)
2227 return false;
2229 /* If there are reduction chains re-trying will fail anyway. */
2230 if (! LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).is_empty ())
2231 return false;
2233 /* Likewise if the grouped loads or stores in the SLP cannot be handled
2234 via interleaving or lane instructions. */
2235 slp_instance instance;
2236 slp_tree node;
2237 unsigned i, j;
2238 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
2240 stmt_vec_info vinfo;
2241 vinfo = vinfo_for_stmt
2242 (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0]);
2243 if (! STMT_VINFO_GROUPED_ACCESS (vinfo))
2244 continue;
2245 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2246 unsigned int size = STMT_VINFO_GROUP_SIZE (vinfo);
2247 tree vectype = STMT_VINFO_VECTYPE (vinfo);
2248 if (! vect_store_lanes_supported (vectype, size)
2249 && ! vect_grouped_store_supported (vectype, size))
2250 return false;
2251 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
2253 vinfo = vinfo_for_stmt (SLP_TREE_SCALAR_STMTS (node)[0]);
2254 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2255 bool single_element_p = !STMT_VINFO_GROUP_NEXT_ELEMENT (vinfo);
2256 size = STMT_VINFO_GROUP_SIZE (vinfo);
2257 vectype = STMT_VINFO_VECTYPE (vinfo);
2258 if (! vect_load_lanes_supported (vectype, size)
2259 && ! vect_grouped_load_supported (vectype, single_element_p,
2260 size))
2261 return false;
2265 if (dump_enabled_p ())
2266 dump_printf_loc (MSG_NOTE, vect_location,
2267 "re-trying with SLP disabled\n");
2269 /* Roll back state appropriately. No SLP this time. */
2270 slp = false;
2271 /* Restore vectorization factor as it were without SLP. */
2272 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = saved_vectorization_factor;
2273 /* Free the SLP instances. */
2274 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
2275 vect_free_slp_instance (instance);
2276 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
2277 /* Reset SLP type to loop_vect on all stmts. */
2278 for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
2280 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
2281 for (gimple_stmt_iterator si = gsi_start_bb (bb);
2282 !gsi_end_p (si); gsi_next (&si))
2284 stmt_vec_info stmt_info = vinfo_for_stmt (gsi_stmt (si));
2285 STMT_SLP_TYPE (stmt_info) = loop_vect;
2286 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
2288 stmt_info = vinfo_for_stmt (STMT_VINFO_RELATED_STMT (stmt_info));
2289 STMT_SLP_TYPE (stmt_info) = loop_vect;
2290 for (gimple_stmt_iterator pi
2291 = gsi_start (STMT_VINFO_PATTERN_DEF_SEQ (stmt_info));
2292 !gsi_end_p (pi); gsi_next (&pi))
2294 gimple *pstmt = gsi_stmt (pi);
2295 STMT_SLP_TYPE (vinfo_for_stmt (pstmt)) = loop_vect;
2300 /* Free optimized alias test DDRS. */
2301 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
2302 /* Reset target cost data. */
2303 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2304 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo)
2305 = init_cost (LOOP_VINFO_LOOP (loop_vinfo));
2306 /* Reset assorted flags. */
2307 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
2308 LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
2309 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
2311 goto start_over;
2314 /* Function vect_analyze_loop.
2316 Apply a set of analyses on LOOP, and create a loop_vec_info struct
2317 for it. The different analyses will record information in the
2318 loop_vec_info struct. If ORIG_LOOP_VINFO is not NULL epilogue must
2319 be vectorized. */
2320 loop_vec_info
2321 vect_analyze_loop (struct loop *loop, loop_vec_info orig_loop_vinfo)
2323 loop_vec_info loop_vinfo;
2324 unsigned int vector_sizes;
2326 /* Autodetect first vector size we try. */
2327 current_vector_size = 0;
2328 vector_sizes = targetm.vectorize.autovectorize_vector_sizes ();
2330 if (dump_enabled_p ())
2331 dump_printf_loc (MSG_NOTE, vect_location,
2332 "===== analyze_loop_nest =====\n");
2334 if (loop_outer (loop)
2335 && loop_vec_info_for_loop (loop_outer (loop))
2336 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
2338 if (dump_enabled_p ())
2339 dump_printf_loc (MSG_NOTE, vect_location,
2340 "outer-loop already vectorized.\n");
2341 return NULL;
2344 while (1)
2346 /* Check the CFG characteristics of the loop (nesting, entry/exit). */
2347 loop_vinfo = vect_analyze_loop_form (loop);
2348 if (!loop_vinfo)
2350 if (dump_enabled_p ())
2351 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2352 "bad loop form.\n");
2353 return NULL;
2356 bool fatal = false;
2358 if (orig_loop_vinfo)
2359 LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo) = orig_loop_vinfo;
2361 if (vect_analyze_loop_2 (loop_vinfo, fatal))
2363 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
2365 return loop_vinfo;
2368 destroy_loop_vec_info (loop_vinfo, true);
2370 vector_sizes &= ~current_vector_size;
2371 if (fatal
2372 || vector_sizes == 0
2373 || current_vector_size == 0)
2374 return NULL;
2376 /* Try the next biggest vector size. */
2377 current_vector_size = 1 << floor_log2 (vector_sizes);
2378 if (dump_enabled_p ())
2379 dump_printf_loc (MSG_NOTE, vect_location,
2380 "***** Re-trying analysis with "
2381 "vector size %d\n", current_vector_size);
2386 /* Function reduction_code_for_scalar_code
2388 Input:
2389 CODE - tree_code of a reduction operations.
2391 Output:
2392 REDUC_CODE - the corresponding tree-code to be used to reduce the
2393 vector of partial results into a single scalar result, or ERROR_MARK
2394 if the operation is a supported reduction operation, but does not have
2395 such a tree-code.
2397 Return FALSE if CODE currently cannot be vectorized as reduction. */
2399 static bool
2400 reduction_code_for_scalar_code (enum tree_code code,
2401 enum tree_code *reduc_code)
2403 switch (code)
2405 case MAX_EXPR:
2406 *reduc_code = REDUC_MAX_EXPR;
2407 return true;
2409 case MIN_EXPR:
2410 *reduc_code = REDUC_MIN_EXPR;
2411 return true;
2413 case PLUS_EXPR:
2414 *reduc_code = REDUC_PLUS_EXPR;
2415 return true;
2417 case MULT_EXPR:
2418 case MINUS_EXPR:
2419 case BIT_IOR_EXPR:
2420 case BIT_XOR_EXPR:
2421 case BIT_AND_EXPR:
2422 *reduc_code = ERROR_MARK;
2423 return true;
2425 default:
2426 return false;
2431 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
2432 STMT is printed with a message MSG. */
2434 static void
2435 report_vect_op (int msg_type, gimple *stmt, const char *msg)
2437 dump_printf_loc (msg_type, vect_location, "%s", msg);
2438 dump_gimple_stmt (msg_type, TDF_SLIM, stmt, 0);
2442 /* Detect SLP reduction of the form:
2444 #a1 = phi <a5, a0>
2445 a2 = operation (a1)
2446 a3 = operation (a2)
2447 a4 = operation (a3)
2448 a5 = operation (a4)
2450 #a = phi <a5>
2452 PHI is the reduction phi node (#a1 = phi <a5, a0> above)
2453 FIRST_STMT is the first reduction stmt in the chain
2454 (a2 = operation (a1)).
2456 Return TRUE if a reduction chain was detected. */
2458 static bool
2459 vect_is_slp_reduction (loop_vec_info loop_info, gimple *phi,
2460 gimple *first_stmt)
2462 struct loop *loop = (gimple_bb (phi))->loop_father;
2463 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2464 enum tree_code code;
2465 gimple *current_stmt = NULL, *loop_use_stmt = NULL, *first, *next_stmt;
2466 stmt_vec_info use_stmt_info, current_stmt_info;
2467 tree lhs;
2468 imm_use_iterator imm_iter;
2469 use_operand_p use_p;
2470 int nloop_uses, size = 0, n_out_of_loop_uses;
2471 bool found = false;
2473 if (loop != vect_loop)
2474 return false;
2476 lhs = PHI_RESULT (phi);
2477 code = gimple_assign_rhs_code (first_stmt);
2478 while (1)
2480 nloop_uses = 0;
2481 n_out_of_loop_uses = 0;
2482 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2484 gimple *use_stmt = USE_STMT (use_p);
2485 if (is_gimple_debug (use_stmt))
2486 continue;
2488 /* Check if we got back to the reduction phi. */
2489 if (use_stmt == phi)
2491 loop_use_stmt = use_stmt;
2492 found = true;
2493 break;
2496 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2498 loop_use_stmt = use_stmt;
2499 nloop_uses++;
2501 else
2502 n_out_of_loop_uses++;
2504 /* There are can be either a single use in the loop or two uses in
2505 phi nodes. */
2506 if (nloop_uses > 1 || (n_out_of_loop_uses && nloop_uses))
2507 return false;
2510 if (found)
2511 break;
2513 /* We reached a statement with no loop uses. */
2514 if (nloop_uses == 0)
2515 return false;
2517 /* This is a loop exit phi, and we haven't reached the reduction phi. */
2518 if (gimple_code (loop_use_stmt) == GIMPLE_PHI)
2519 return false;
2521 if (!is_gimple_assign (loop_use_stmt)
2522 || code != gimple_assign_rhs_code (loop_use_stmt)
2523 || !flow_bb_inside_loop_p (loop, gimple_bb (loop_use_stmt)))
2524 return false;
2526 /* Insert USE_STMT into reduction chain. */
2527 use_stmt_info = vinfo_for_stmt (loop_use_stmt);
2528 if (current_stmt)
2530 current_stmt_info = vinfo_for_stmt (current_stmt);
2531 GROUP_NEXT_ELEMENT (current_stmt_info) = loop_use_stmt;
2532 GROUP_FIRST_ELEMENT (use_stmt_info)
2533 = GROUP_FIRST_ELEMENT (current_stmt_info);
2535 else
2536 GROUP_FIRST_ELEMENT (use_stmt_info) = loop_use_stmt;
2538 lhs = gimple_assign_lhs (loop_use_stmt);
2539 current_stmt = loop_use_stmt;
2540 size++;
2543 if (!found || loop_use_stmt != phi || size < 2)
2544 return false;
2546 /* Swap the operands, if needed, to make the reduction operand be the second
2547 operand. */
2548 lhs = PHI_RESULT (phi);
2549 next_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2550 while (next_stmt)
2552 if (gimple_assign_rhs2 (next_stmt) == lhs)
2554 tree op = gimple_assign_rhs1 (next_stmt);
2555 gimple *def_stmt = NULL;
2557 if (TREE_CODE (op) == SSA_NAME)
2558 def_stmt = SSA_NAME_DEF_STMT (op);
2560 /* Check that the other def is either defined in the loop
2561 ("vect_internal_def"), or it's an induction (defined by a
2562 loop-header phi-node). */
2563 if (def_stmt
2564 && gimple_bb (def_stmt)
2565 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2566 && (is_gimple_assign (def_stmt)
2567 || is_gimple_call (def_stmt)
2568 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2569 == vect_induction_def
2570 || (gimple_code (def_stmt) == GIMPLE_PHI
2571 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2572 == vect_internal_def
2573 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2575 lhs = gimple_assign_lhs (next_stmt);
2576 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2577 continue;
2580 return false;
2582 else
2584 tree op = gimple_assign_rhs2 (next_stmt);
2585 gimple *def_stmt = NULL;
2587 if (TREE_CODE (op) == SSA_NAME)
2588 def_stmt = SSA_NAME_DEF_STMT (op);
2590 /* Check that the other def is either defined in the loop
2591 ("vect_internal_def"), or it's an induction (defined by a
2592 loop-header phi-node). */
2593 if (def_stmt
2594 && gimple_bb (def_stmt)
2595 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2596 && (is_gimple_assign (def_stmt)
2597 || is_gimple_call (def_stmt)
2598 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2599 == vect_induction_def
2600 || (gimple_code (def_stmt) == GIMPLE_PHI
2601 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2602 == vect_internal_def
2603 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2605 if (dump_enabled_p ())
2607 dump_printf_loc (MSG_NOTE, vect_location, "swapping oprnds: ");
2608 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, next_stmt, 0);
2611 swap_ssa_operands (next_stmt,
2612 gimple_assign_rhs1_ptr (next_stmt),
2613 gimple_assign_rhs2_ptr (next_stmt));
2614 update_stmt (next_stmt);
2616 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (next_stmt)))
2617 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2619 else
2620 return false;
2623 lhs = gimple_assign_lhs (next_stmt);
2624 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2627 /* Save the chain for further analysis in SLP detection. */
2628 first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2629 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (first);
2630 GROUP_SIZE (vinfo_for_stmt (first)) = size;
2632 return true;
2636 /* Function vect_is_simple_reduction_1
2638 (1) Detect a cross-iteration def-use cycle that represents a simple
2639 reduction computation. We look for the following pattern:
2641 loop_header:
2642 a1 = phi < a0, a2 >
2643 a3 = ...
2644 a2 = operation (a3, a1)
2648 a3 = ...
2649 loop_header:
2650 a1 = phi < a0, a2 >
2651 a2 = operation (a3, a1)
2653 such that:
2654 1. operation is commutative and associative and it is safe to
2655 change the order of the computation (if CHECK_REDUCTION is true)
2656 2. no uses for a2 in the loop (a2 is used out of the loop)
2657 3. no uses of a1 in the loop besides the reduction operation
2658 4. no uses of a1 outside the loop.
2660 Conditions 1,4 are tested here.
2661 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
2663 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
2664 nested cycles, if CHECK_REDUCTION is false.
2666 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
2667 reductions:
2669 a1 = phi < a0, a2 >
2670 inner loop (def of a3)
2671 a2 = phi < a3 >
2673 (4) Detect condition expressions, ie:
2674 for (int i = 0; i < N; i++)
2675 if (a[i] < val)
2676 ret_val = a[i];
2680 static gimple *
2681 vect_is_simple_reduction (loop_vec_info loop_info, gimple *phi,
2682 bool check_reduction, bool *double_reduc,
2683 bool need_wrapping_integral_overflow,
2684 enum vect_reduction_type *v_reduc_type)
2686 struct loop *loop = (gimple_bb (phi))->loop_father;
2687 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2688 edge latch_e = loop_latch_edge (loop);
2689 tree loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
2690 gimple *def_stmt, *def1 = NULL, *def2 = NULL, *phi_use_stmt = NULL;
2691 enum tree_code orig_code, code;
2692 tree op1, op2, op3 = NULL_TREE, op4 = NULL_TREE;
2693 tree type;
2694 int nloop_uses;
2695 tree name;
2696 imm_use_iterator imm_iter;
2697 use_operand_p use_p;
2698 bool phi_def;
2700 *double_reduc = false;
2701 *v_reduc_type = TREE_CODE_REDUCTION;
2703 /* If CHECK_REDUCTION is true, we assume inner-most loop vectorization,
2704 otherwise, we assume outer loop vectorization. */
2705 gcc_assert ((check_reduction && loop == vect_loop)
2706 || (!check_reduction && flow_loop_nested_p (vect_loop, loop)));
2708 name = PHI_RESULT (phi);
2709 /* ??? If there are no uses of the PHI result the inner loop reduction
2710 won't be detected as possibly double-reduction by vectorizable_reduction
2711 because that tries to walk the PHI arg from the preheader edge which
2712 can be constant. See PR60382. */
2713 if (has_zero_uses (name))
2714 return NULL;
2715 nloop_uses = 0;
2716 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2718 gimple *use_stmt = USE_STMT (use_p);
2719 if (is_gimple_debug (use_stmt))
2720 continue;
2722 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2724 if (dump_enabled_p ())
2725 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2726 "intermediate value used outside loop.\n");
2728 return NULL;
2731 nloop_uses++;
2732 if (nloop_uses > 1)
2734 if (dump_enabled_p ())
2735 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2736 "reduction used in loop.\n");
2737 return NULL;
2740 phi_use_stmt = use_stmt;
2743 if (TREE_CODE (loop_arg) != SSA_NAME)
2745 if (dump_enabled_p ())
2747 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2748 "reduction: not ssa_name: ");
2749 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, loop_arg);
2750 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
2752 return NULL;
2755 def_stmt = SSA_NAME_DEF_STMT (loop_arg);
2756 if (!def_stmt)
2758 if (dump_enabled_p ())
2759 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2760 "reduction: no def_stmt.\n");
2761 return NULL;
2764 if (!is_gimple_assign (def_stmt) && gimple_code (def_stmt) != GIMPLE_PHI)
2766 if (dump_enabled_p ())
2767 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, def_stmt, 0);
2768 return NULL;
2771 if (is_gimple_assign (def_stmt))
2773 name = gimple_assign_lhs (def_stmt);
2774 phi_def = false;
2776 else
2778 name = PHI_RESULT (def_stmt);
2779 phi_def = true;
2782 nloop_uses = 0;
2783 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2785 gimple *use_stmt = USE_STMT (use_p);
2786 if (is_gimple_debug (use_stmt))
2787 continue;
2788 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2789 nloop_uses++;
2790 if (nloop_uses > 1)
2792 if (dump_enabled_p ())
2793 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2794 "reduction used in loop.\n");
2795 return NULL;
2799 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
2800 defined in the inner loop. */
2801 if (phi_def)
2803 op1 = PHI_ARG_DEF (def_stmt, 0);
2805 if (gimple_phi_num_args (def_stmt) != 1
2806 || TREE_CODE (op1) != SSA_NAME)
2808 if (dump_enabled_p ())
2809 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2810 "unsupported phi node definition.\n");
2812 return NULL;
2815 def1 = SSA_NAME_DEF_STMT (op1);
2816 if (gimple_bb (def1)
2817 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2818 && loop->inner
2819 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
2820 && is_gimple_assign (def1)
2821 && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt)))
2823 if (dump_enabled_p ())
2824 report_vect_op (MSG_NOTE, def_stmt,
2825 "detected double reduction: ");
2827 *double_reduc = true;
2828 return def_stmt;
2831 return NULL;
2834 code = orig_code = gimple_assign_rhs_code (def_stmt);
2836 /* We can handle "res -= x[i]", which is non-associative by
2837 simply rewriting this into "res += -x[i]". Avoid changing
2838 gimple instruction for the first simple tests and only do this
2839 if we're allowed to change code at all. */
2840 if (code == MINUS_EXPR
2841 && (op1 = gimple_assign_rhs1 (def_stmt))
2842 && TREE_CODE (op1) == SSA_NAME
2843 && SSA_NAME_DEF_STMT (op1) == phi)
2844 code = PLUS_EXPR;
2846 if (code == COND_EXPR)
2848 if (check_reduction)
2849 *v_reduc_type = COND_REDUCTION;
2851 else if (!commutative_tree_code (code) || !associative_tree_code (code))
2853 if (dump_enabled_p ())
2854 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2855 "reduction: not commutative/associative: ");
2856 return NULL;
2859 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
2861 if (code != COND_EXPR)
2863 if (dump_enabled_p ())
2864 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2865 "reduction: not binary operation: ");
2867 return NULL;
2870 op3 = gimple_assign_rhs1 (def_stmt);
2871 if (COMPARISON_CLASS_P (op3))
2873 op4 = TREE_OPERAND (op3, 1);
2874 op3 = TREE_OPERAND (op3, 0);
2877 op1 = gimple_assign_rhs2 (def_stmt);
2878 op2 = gimple_assign_rhs3 (def_stmt);
2880 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2882 if (dump_enabled_p ())
2883 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2884 "reduction: uses not ssa_names: ");
2886 return NULL;
2889 else
2891 op1 = gimple_assign_rhs1 (def_stmt);
2892 op2 = gimple_assign_rhs2 (def_stmt);
2894 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2896 if (dump_enabled_p ())
2897 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2898 "reduction: uses not ssa_names: ");
2900 return NULL;
2904 type = TREE_TYPE (gimple_assign_lhs (def_stmt));
2905 if ((TREE_CODE (op1) == SSA_NAME
2906 && !types_compatible_p (type,TREE_TYPE (op1)))
2907 || (TREE_CODE (op2) == SSA_NAME
2908 && !types_compatible_p (type, TREE_TYPE (op2)))
2909 || (op3 && TREE_CODE (op3) == SSA_NAME
2910 && !types_compatible_p (type, TREE_TYPE (op3)))
2911 || (op4 && TREE_CODE (op4) == SSA_NAME
2912 && !types_compatible_p (type, TREE_TYPE (op4))))
2914 if (dump_enabled_p ())
2916 dump_printf_loc (MSG_NOTE, vect_location,
2917 "reduction: multiple types: operation type: ");
2918 dump_generic_expr (MSG_NOTE, TDF_SLIM, type);
2919 dump_printf (MSG_NOTE, ", operands types: ");
2920 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2921 TREE_TYPE (op1));
2922 dump_printf (MSG_NOTE, ",");
2923 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2924 TREE_TYPE (op2));
2925 if (op3)
2927 dump_printf (MSG_NOTE, ",");
2928 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2929 TREE_TYPE (op3));
2932 if (op4)
2934 dump_printf (MSG_NOTE, ",");
2935 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2936 TREE_TYPE (op4));
2938 dump_printf (MSG_NOTE, "\n");
2941 return NULL;
2944 /* Check that it's ok to change the order of the computation.
2945 Generally, when vectorizing a reduction we change the order of the
2946 computation. This may change the behavior of the program in some
2947 cases, so we need to check that this is ok. One exception is when
2948 vectorizing an outer-loop: the inner-loop is executed sequentially,
2949 and therefore vectorizing reductions in the inner-loop during
2950 outer-loop vectorization is safe. */
2952 if (*v_reduc_type != COND_REDUCTION
2953 && check_reduction)
2955 /* CHECKME: check for !flag_finite_math_only too? */
2956 if (SCALAR_FLOAT_TYPE_P (type) && !flag_associative_math)
2958 /* Changing the order of operations changes the semantics. */
2959 if (dump_enabled_p ())
2960 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2961 "reduction: unsafe fp math optimization: ");
2962 return NULL;
2964 else if (INTEGRAL_TYPE_P (type))
2966 if (!operation_no_trapping_overflow (type, code))
2968 /* Changing the order of operations changes the semantics. */
2969 if (dump_enabled_p ())
2970 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2971 "reduction: unsafe int math optimization"
2972 " (overflow traps): ");
2973 return NULL;
2975 if (need_wrapping_integral_overflow
2976 && !TYPE_OVERFLOW_WRAPS (type)
2977 && operation_can_overflow (code))
2979 /* Changing the order of operations changes the semantics. */
2980 if (dump_enabled_p ())
2981 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2982 "reduction: unsafe int math optimization"
2983 " (overflow doesn't wrap): ");
2984 return NULL;
2987 else if (SAT_FIXED_POINT_TYPE_P (type))
2989 /* Changing the order of operations changes the semantics. */
2990 if (dump_enabled_p ())
2991 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2992 "reduction: unsafe fixed-point math optimization: ");
2993 return NULL;
2997 /* Reduction is safe. We're dealing with one of the following:
2998 1) integer arithmetic and no trapv
2999 2) floating point arithmetic, and special flags permit this optimization
3000 3) nested cycle (i.e., outer loop vectorization). */
3001 if (TREE_CODE (op1) == SSA_NAME)
3002 def1 = SSA_NAME_DEF_STMT (op1);
3004 if (TREE_CODE (op2) == SSA_NAME)
3005 def2 = SSA_NAME_DEF_STMT (op2);
3007 if (code != COND_EXPR
3008 && ((!def1 || gimple_nop_p (def1)) && (!def2 || gimple_nop_p (def2))))
3010 if (dump_enabled_p ())
3011 report_vect_op (MSG_NOTE, def_stmt, "reduction: no defs for operands: ");
3012 return NULL;
3015 /* Check that one def is the reduction def, defined by PHI,
3016 the other def is either defined in the loop ("vect_internal_def"),
3017 or it's an induction (defined by a loop-header phi-node). */
3019 if (def2 && def2 == phi
3020 && (code == COND_EXPR
3021 || !def1 || gimple_nop_p (def1)
3022 || !flow_bb_inside_loop_p (loop, gimple_bb (def1))
3023 || (def1 && flow_bb_inside_loop_p (loop, gimple_bb (def1))
3024 && (is_gimple_assign (def1)
3025 || is_gimple_call (def1)
3026 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
3027 == vect_induction_def
3028 || (gimple_code (def1) == GIMPLE_PHI
3029 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
3030 == vect_internal_def
3031 && !is_loop_header_bb_p (gimple_bb (def1)))))))
3033 if (dump_enabled_p ())
3034 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3035 return def_stmt;
3038 if (def1 && def1 == phi
3039 && (code == COND_EXPR
3040 || !def2 || gimple_nop_p (def2)
3041 || !flow_bb_inside_loop_p (loop, gimple_bb (def2))
3042 || (def2 && flow_bb_inside_loop_p (loop, gimple_bb (def2))
3043 && (is_gimple_assign (def2)
3044 || is_gimple_call (def2)
3045 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3046 == vect_induction_def
3047 || (gimple_code (def2) == GIMPLE_PHI
3048 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3049 == vect_internal_def
3050 && !is_loop_header_bb_p (gimple_bb (def2)))))))
3052 if (check_reduction && orig_code != MINUS_EXPR)
3054 /* Check if we can swap operands (just for simplicity - so that
3055 the rest of the code can assume that the reduction variable
3056 is always the last (second) argument). */
3057 if (code == COND_EXPR)
3059 /* Swap cond_expr by inverting the condition. */
3060 tree cond_expr = gimple_assign_rhs1 (def_stmt);
3061 enum tree_code invert_code = ERROR_MARK;
3062 enum tree_code cond_code = TREE_CODE (cond_expr);
3064 if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
3066 bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr, 0));
3067 invert_code = invert_tree_comparison (cond_code, honor_nans);
3069 if (invert_code != ERROR_MARK)
3071 TREE_SET_CODE (cond_expr, invert_code);
3072 swap_ssa_operands (def_stmt,
3073 gimple_assign_rhs2_ptr (def_stmt),
3074 gimple_assign_rhs3_ptr (def_stmt));
3076 else
3078 if (dump_enabled_p ())
3079 report_vect_op (MSG_NOTE, def_stmt,
3080 "detected reduction: cannot swap operands "
3081 "for cond_expr");
3082 return NULL;
3085 else
3086 swap_ssa_operands (def_stmt, gimple_assign_rhs1_ptr (def_stmt),
3087 gimple_assign_rhs2_ptr (def_stmt));
3089 if (dump_enabled_p ())
3090 report_vect_op (MSG_NOTE, def_stmt,
3091 "detected reduction: need to swap operands: ");
3093 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (def_stmt)))
3094 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
3096 else
3098 if (dump_enabled_p ())
3099 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3102 return def_stmt;
3105 /* Try to find SLP reduction chain. */
3106 if (check_reduction && code != COND_EXPR
3107 && vect_is_slp_reduction (loop_info, phi, def_stmt))
3109 if (dump_enabled_p ())
3110 report_vect_op (MSG_NOTE, def_stmt,
3111 "reduction: detected reduction chain: ");
3113 return def_stmt;
3116 if (dump_enabled_p ())
3117 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3118 "reduction: unknown pattern: ");
3120 return NULL;
3123 /* Wrapper around vect_is_simple_reduction_1, which will modify code
3124 in-place if it enables detection of more reductions. Arguments
3125 as there. */
3127 gimple *
3128 vect_force_simple_reduction (loop_vec_info loop_info, gimple *phi,
3129 bool check_reduction, bool *double_reduc,
3130 bool need_wrapping_integral_overflow)
3132 enum vect_reduction_type v_reduc_type;
3133 return vect_is_simple_reduction (loop_info, phi, check_reduction,
3134 double_reduc,
3135 need_wrapping_integral_overflow,
3136 &v_reduc_type);
3139 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
3141 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
3142 int *peel_iters_epilogue,
3143 stmt_vector_for_cost *scalar_cost_vec,
3144 stmt_vector_for_cost *prologue_cost_vec,
3145 stmt_vector_for_cost *epilogue_cost_vec)
3147 int retval = 0;
3148 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3150 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
3152 *peel_iters_epilogue = vf/2;
3153 if (dump_enabled_p ())
3154 dump_printf_loc (MSG_NOTE, vect_location,
3155 "cost model: epilogue peel iters set to vf/2 "
3156 "because loop iterations are unknown .\n");
3158 /* If peeled iterations are known but number of scalar loop
3159 iterations are unknown, count a taken branch per peeled loop. */
3160 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3161 NULL, 0, vect_prologue);
3162 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3163 NULL, 0, vect_epilogue);
3165 else
3167 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
3168 peel_iters_prologue = niters < peel_iters_prologue ?
3169 niters : peel_iters_prologue;
3170 *peel_iters_epilogue = (niters - peel_iters_prologue) % vf;
3171 /* If we need to peel for gaps, but no peeling is required, we have to
3172 peel VF iterations. */
3173 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !*peel_iters_epilogue)
3174 *peel_iters_epilogue = vf;
3177 stmt_info_for_cost *si;
3178 int j;
3179 if (peel_iters_prologue)
3180 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3181 retval += record_stmt_cost (prologue_cost_vec,
3182 si->count * peel_iters_prologue,
3183 si->kind, NULL, si->misalign,
3184 vect_prologue);
3185 if (*peel_iters_epilogue)
3186 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3187 retval += record_stmt_cost (epilogue_cost_vec,
3188 si->count * *peel_iters_epilogue,
3189 si->kind, NULL, si->misalign,
3190 vect_epilogue);
3192 return retval;
3195 /* Function vect_estimate_min_profitable_iters
3197 Return the number of iterations required for the vector version of the
3198 loop to be profitable relative to the cost of the scalar version of the
3199 loop.
3201 *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
3202 of iterations for vectorization. -1 value means loop vectorization
3203 is not profitable. This returned value may be used for dynamic
3204 profitability check.
3206 *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
3207 for static check against estimated number of iterations. */
3209 static void
3210 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
3211 int *ret_min_profitable_niters,
3212 int *ret_min_profitable_estimate)
3214 int min_profitable_iters;
3215 int min_profitable_estimate;
3216 int peel_iters_prologue;
3217 int peel_iters_epilogue;
3218 unsigned vec_inside_cost = 0;
3219 int vec_outside_cost = 0;
3220 unsigned vec_prologue_cost = 0;
3221 unsigned vec_epilogue_cost = 0;
3222 int scalar_single_iter_cost = 0;
3223 int scalar_outside_cost = 0;
3224 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3225 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
3226 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3228 /* Cost model disabled. */
3229 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
3231 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
3232 *ret_min_profitable_niters = 0;
3233 *ret_min_profitable_estimate = 0;
3234 return;
3237 /* Requires loop versioning tests to handle misalignment. */
3238 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
3240 /* FIXME: Make cost depend on complexity of individual check. */
3241 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
3242 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3243 vect_prologue);
3244 dump_printf (MSG_NOTE,
3245 "cost model: Adding cost of checks for loop "
3246 "versioning to treat misalignment.\n");
3249 /* Requires loop versioning with alias checks. */
3250 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
3252 /* FIXME: Make cost depend on complexity of individual check. */
3253 unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
3254 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3255 vect_prologue);
3256 dump_printf (MSG_NOTE,
3257 "cost model: Adding cost of checks for loop "
3258 "versioning aliasing.\n");
3261 /* Requires loop versioning with niter checks. */
3262 if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
3264 /* FIXME: Make cost depend on complexity of individual check. */
3265 (void) add_stmt_cost (target_cost_data, 1, vector_stmt, NULL, 0,
3266 vect_prologue);
3267 dump_printf (MSG_NOTE,
3268 "cost model: Adding cost of checks for loop "
3269 "versioning niters.\n");
3272 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3273 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken, NULL, 0,
3274 vect_prologue);
3276 /* Count statements in scalar loop. Using this as scalar cost for a single
3277 iteration for now.
3279 TODO: Add outer loop support.
3281 TODO: Consider assigning different costs to different scalar
3282 statements. */
3284 scalar_single_iter_cost
3285 = LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo);
3287 /* Add additional cost for the peeled instructions in prologue and epilogue
3288 loop.
3290 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
3291 at compile-time - we assume it's vf/2 (the worst would be vf-1).
3293 TODO: Build an expression that represents peel_iters for prologue and
3294 epilogue to be used in a run-time test. */
3296 if (npeel < 0)
3298 peel_iters_prologue = vf/2;
3299 dump_printf (MSG_NOTE, "cost model: "
3300 "prologue peel iters set to vf/2.\n");
3302 /* If peeling for alignment is unknown, loop bound of main loop becomes
3303 unknown. */
3304 peel_iters_epilogue = vf/2;
3305 dump_printf (MSG_NOTE, "cost model: "
3306 "epilogue peel iters set to vf/2 because "
3307 "peeling for alignment is unknown.\n");
3309 /* If peeled iterations are unknown, count a taken branch and a not taken
3310 branch per peeled loop. Even if scalar loop iterations are known,
3311 vector iterations are not known since peeled prologue iterations are
3312 not known. Hence guards remain the same. */
3313 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3314 NULL, 0, vect_prologue);
3315 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3316 NULL, 0, vect_prologue);
3317 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3318 NULL, 0, vect_epilogue);
3319 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3320 NULL, 0, vect_epilogue);
3321 stmt_info_for_cost *si;
3322 int j;
3323 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
3325 struct _stmt_vec_info *stmt_info
3326 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3327 (void) add_stmt_cost (target_cost_data,
3328 si->count * peel_iters_prologue,
3329 si->kind, stmt_info, si->misalign,
3330 vect_prologue);
3331 (void) add_stmt_cost (target_cost_data,
3332 si->count * peel_iters_epilogue,
3333 si->kind, stmt_info, si->misalign,
3334 vect_epilogue);
3337 else
3339 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
3340 stmt_info_for_cost *si;
3341 int j;
3342 void *data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3344 prologue_cost_vec.create (2);
3345 epilogue_cost_vec.create (2);
3346 peel_iters_prologue = npeel;
3348 (void) vect_get_known_peeling_cost (loop_vinfo, peel_iters_prologue,
3349 &peel_iters_epilogue,
3350 &LOOP_VINFO_SCALAR_ITERATION_COST
3351 (loop_vinfo),
3352 &prologue_cost_vec,
3353 &epilogue_cost_vec);
3355 FOR_EACH_VEC_ELT (prologue_cost_vec, j, si)
3357 struct _stmt_vec_info *stmt_info
3358 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3359 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3360 si->misalign, vect_prologue);
3363 FOR_EACH_VEC_ELT (epilogue_cost_vec, j, si)
3365 struct _stmt_vec_info *stmt_info
3366 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3367 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3368 si->misalign, vect_epilogue);
3371 prologue_cost_vec.release ();
3372 epilogue_cost_vec.release ();
3375 /* FORNOW: The scalar outside cost is incremented in one of the
3376 following ways:
3378 1. The vectorizer checks for alignment and aliasing and generates
3379 a condition that allows dynamic vectorization. A cost model
3380 check is ANDED with the versioning condition. Hence scalar code
3381 path now has the added cost of the versioning check.
3383 if (cost > th & versioning_check)
3384 jmp to vector code
3386 Hence run-time scalar is incremented by not-taken branch cost.
3388 2. The vectorizer then checks if a prologue is required. If the
3389 cost model check was not done before during versioning, it has to
3390 be done before the prologue check.
3392 if (cost <= th)
3393 prologue = scalar_iters
3394 if (prologue == 0)
3395 jmp to vector code
3396 else
3397 execute prologue
3398 if (prologue == num_iters)
3399 go to exit
3401 Hence the run-time scalar cost is incremented by a taken branch,
3402 plus a not-taken branch, plus a taken branch cost.
3404 3. The vectorizer then checks if an epilogue is required. If the
3405 cost model check was not done before during prologue check, it
3406 has to be done with the epilogue check.
3408 if (prologue == 0)
3409 jmp to vector code
3410 else
3411 execute prologue
3412 if (prologue == num_iters)
3413 go to exit
3414 vector code:
3415 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
3416 jmp to epilogue
3418 Hence the run-time scalar cost should be incremented by 2 taken
3419 branches.
3421 TODO: The back end may reorder the BBS's differently and reverse
3422 conditions/branch directions. Change the estimates below to
3423 something more reasonable. */
3425 /* If the number of iterations is known and we do not do versioning, we can
3426 decide whether to vectorize at compile time. Hence the scalar version
3427 do not carry cost model guard costs. */
3428 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3429 || LOOP_REQUIRES_VERSIONING (loop_vinfo))
3431 /* Cost model check occurs at versioning. */
3432 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3433 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
3434 else
3436 /* Cost model check occurs at prologue generation. */
3437 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
3438 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
3439 + vect_get_stmt_cost (cond_branch_not_taken);
3440 /* Cost model check occurs at epilogue generation. */
3441 else
3442 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
3446 /* Complete the target-specific cost calculations. */
3447 finish_cost (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo), &vec_prologue_cost,
3448 &vec_inside_cost, &vec_epilogue_cost);
3450 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
3452 if (dump_enabled_p ())
3454 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
3455 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
3456 vec_inside_cost);
3457 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
3458 vec_prologue_cost);
3459 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
3460 vec_epilogue_cost);
3461 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
3462 scalar_single_iter_cost);
3463 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
3464 scalar_outside_cost);
3465 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
3466 vec_outside_cost);
3467 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
3468 peel_iters_prologue);
3469 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
3470 peel_iters_epilogue);
3473 /* Calculate number of iterations required to make the vector version
3474 profitable, relative to the loop bodies only. The following condition
3475 must hold true:
3476 SIC * niters + SOC > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC
3477 where
3478 SIC = scalar iteration cost, VIC = vector iteration cost,
3479 VOC = vector outside cost, VF = vectorization factor,
3480 PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations
3481 SOC = scalar outside cost for run time cost model check. */
3483 if ((scalar_single_iter_cost * vf) > (int) vec_inside_cost)
3485 if (vec_outside_cost <= 0)
3486 min_profitable_iters = 1;
3487 else
3489 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost) * vf
3490 - vec_inside_cost * peel_iters_prologue
3491 - vec_inside_cost * peel_iters_epilogue)
3492 / ((scalar_single_iter_cost * vf)
3493 - vec_inside_cost);
3495 if ((scalar_single_iter_cost * vf * min_profitable_iters)
3496 <= (((int) vec_inside_cost * min_profitable_iters)
3497 + (((int) vec_outside_cost - scalar_outside_cost) * vf)))
3498 min_profitable_iters++;
3501 /* vector version will never be profitable. */
3502 else
3504 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
3505 warning_at (vect_location, OPT_Wopenmp_simd, "vectorization "
3506 "did not happen for a simd loop");
3508 if (dump_enabled_p ())
3509 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3510 "cost model: the vector iteration cost = %d "
3511 "divided by the scalar iteration cost = %d "
3512 "is greater or equal to the vectorization factor = %d"
3513 ".\n",
3514 vec_inside_cost, scalar_single_iter_cost, vf);
3515 *ret_min_profitable_niters = -1;
3516 *ret_min_profitable_estimate = -1;
3517 return;
3520 dump_printf (MSG_NOTE,
3521 " Calculated minimum iters for profitability: %d\n",
3522 min_profitable_iters);
3524 min_profitable_iters =
3525 min_profitable_iters < vf ? vf : min_profitable_iters;
3527 /* Because the condition we create is:
3528 if (niters <= min_profitable_iters)
3529 then skip the vectorized loop. */
3530 min_profitable_iters--;
3532 if (dump_enabled_p ())
3533 dump_printf_loc (MSG_NOTE, vect_location,
3534 " Runtime profitability threshold = %d\n",
3535 min_profitable_iters);
3537 *ret_min_profitable_niters = min_profitable_iters;
3539 /* Calculate number of iterations required to make the vector version
3540 profitable, relative to the loop bodies only.
3542 Non-vectorized variant is SIC * niters and it must win over vector
3543 variant on the expected loop trip count. The following condition must hold true:
3544 SIC * niters > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC + SOC */
3546 if (vec_outside_cost <= 0)
3547 min_profitable_estimate = 1;
3548 else
3550 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost) * vf
3551 - vec_inside_cost * peel_iters_prologue
3552 - vec_inside_cost * peel_iters_epilogue)
3553 / ((scalar_single_iter_cost * vf)
3554 - vec_inside_cost);
3556 min_profitable_estimate --;
3557 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
3558 if (dump_enabled_p ())
3559 dump_printf_loc (MSG_NOTE, vect_location,
3560 " Static estimate profitability threshold = %d\n",
3561 min_profitable_estimate);
3563 *ret_min_profitable_estimate = min_profitable_estimate;
3566 /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
3567 vector elements (not bits) for a vector of mode MODE. */
3568 static void
3569 calc_vec_perm_mask_for_shift (enum machine_mode mode, unsigned int offset,
3570 unsigned char *sel)
3572 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3574 for (i = 0; i < nelt; i++)
3575 sel[i] = (i + offset) & (2*nelt - 1);
3578 /* Checks whether the target supports whole-vector shifts for vectors of mode
3579 MODE. This is the case if _either_ the platform handles vec_shr_optab, _or_
3580 it supports vec_perm_const with masks for all necessary shift amounts. */
3581 static bool
3582 have_whole_vector_shift (enum machine_mode mode)
3584 if (optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
3585 return true;
3587 if (direct_optab_handler (vec_perm_const_optab, mode) == CODE_FOR_nothing)
3588 return false;
3590 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3591 unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
3593 for (i = nelt/2; i >= 1; i/=2)
3595 calc_vec_perm_mask_for_shift (mode, i, sel);
3596 if (!can_vec_perm_p (mode, false, sel))
3597 return false;
3599 return true;
3602 /* Return the reduction operand (with index REDUC_INDEX) of STMT. */
3604 static tree
3605 get_reduction_op (gimple *stmt, int reduc_index)
3607 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
3609 case GIMPLE_SINGLE_RHS:
3610 gcc_assert (TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt))
3611 == ternary_op);
3612 return TREE_OPERAND (gimple_assign_rhs1 (stmt), reduc_index);
3613 case GIMPLE_UNARY_RHS:
3614 return gimple_assign_rhs1 (stmt);
3615 case GIMPLE_BINARY_RHS:
3616 return (reduc_index
3617 ? gimple_assign_rhs2 (stmt) : gimple_assign_rhs1 (stmt));
3618 case GIMPLE_TERNARY_RHS:
3619 return gimple_op (stmt, reduc_index + 1);
3620 default:
3621 gcc_unreachable ();
3625 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
3626 functions. Design better to avoid maintenance issues. */
3628 /* Function vect_model_reduction_cost.
3630 Models cost for a reduction operation, including the vector ops
3631 generated within the strip-mine loop, the initial definition before
3632 the loop, and the epilogue code that must be generated. */
3634 static bool
3635 vect_model_reduction_cost (stmt_vec_info stmt_info, enum tree_code reduc_code,
3636 int ncopies, int reduc_index)
3638 int prologue_cost = 0, epilogue_cost = 0;
3639 enum tree_code code;
3640 optab optab;
3641 tree vectype;
3642 gimple *stmt, *orig_stmt;
3643 tree reduction_op;
3644 machine_mode mode;
3645 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3646 struct loop *loop = NULL;
3647 void *target_cost_data;
3649 if (loop_vinfo)
3651 loop = LOOP_VINFO_LOOP (loop_vinfo);
3652 target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3654 else
3655 target_cost_data = BB_VINFO_TARGET_COST_DATA (STMT_VINFO_BB_VINFO (stmt_info));
3657 /* Condition reductions generate two reductions in the loop. */
3658 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3659 ncopies *= 2;
3661 /* Cost of reduction op inside loop. */
3662 unsigned inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3663 stmt_info, 0, vect_body);
3664 stmt = STMT_VINFO_STMT (stmt_info);
3666 reduction_op = get_reduction_op (stmt, reduc_index);
3668 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
3669 if (!vectype)
3671 if (dump_enabled_p ())
3673 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3674 "unsupported data-type ");
3675 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
3676 TREE_TYPE (reduction_op));
3677 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
3679 return false;
3682 mode = TYPE_MODE (vectype);
3683 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
3685 if (!orig_stmt)
3686 orig_stmt = STMT_VINFO_STMT (stmt_info);
3688 code = gimple_assign_rhs_code (orig_stmt);
3690 /* Add in cost for initial definition.
3691 For cond reduction we have four vectors: initial index, step, initial
3692 result of the data reduction, initial value of the index reduction. */
3693 int prologue_stmts = STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
3694 == COND_REDUCTION ? 4 : 1;
3695 prologue_cost += add_stmt_cost (target_cost_data, prologue_stmts,
3696 scalar_to_vec, stmt_info, 0,
3697 vect_prologue);
3699 /* Determine cost of epilogue code.
3701 We have a reduction operator that will reduce the vector in one statement.
3702 Also requires scalar extract. */
3704 if (!loop || !nested_in_vect_loop_p (loop, orig_stmt))
3706 if (reduc_code != ERROR_MARK)
3708 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3710 /* An EQ stmt and an COND_EXPR stmt. */
3711 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3712 vector_stmt, stmt_info, 0,
3713 vect_epilogue);
3714 /* Reduction of the max index and a reduction of the found
3715 values. */
3716 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3717 vec_to_scalar, stmt_info, 0,
3718 vect_epilogue);
3719 /* A broadcast of the max value. */
3720 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3721 scalar_to_vec, stmt_info, 0,
3722 vect_epilogue);
3724 else
3726 epilogue_cost += add_stmt_cost (target_cost_data, 1, vector_stmt,
3727 stmt_info, 0, vect_epilogue);
3728 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3729 vec_to_scalar, stmt_info, 0,
3730 vect_epilogue);
3733 else
3735 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
3736 tree bitsize =
3737 TYPE_SIZE (TREE_TYPE (gimple_assign_lhs (orig_stmt)));
3738 int element_bitsize = tree_to_uhwi (bitsize);
3739 int nelements = vec_size_in_bits / element_bitsize;
3741 optab = optab_for_tree_code (code, vectype, optab_default);
3743 /* We have a whole vector shift available. */
3744 if (VECTOR_MODE_P (mode)
3745 && optab_handler (optab, mode) != CODE_FOR_nothing
3746 && have_whole_vector_shift (mode))
3748 /* Final reduction via vector shifts and the reduction operator.
3749 Also requires scalar extract. */
3750 epilogue_cost += add_stmt_cost (target_cost_data,
3751 exact_log2 (nelements) * 2,
3752 vector_stmt, stmt_info, 0,
3753 vect_epilogue);
3754 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3755 vec_to_scalar, stmt_info, 0,
3756 vect_epilogue);
3758 else
3759 /* Use extracts and reduction op for final reduction. For N
3760 elements, we have N extracts and N-1 reduction ops. */
3761 epilogue_cost += add_stmt_cost (target_cost_data,
3762 nelements + nelements - 1,
3763 vector_stmt, stmt_info, 0,
3764 vect_epilogue);
3768 if (dump_enabled_p ())
3769 dump_printf (MSG_NOTE,
3770 "vect_model_reduction_cost: inside_cost = %d, "
3771 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
3772 prologue_cost, epilogue_cost);
3774 return true;
3778 /* Function vect_model_induction_cost.
3780 Models cost for induction operations. */
3782 static void
3783 vect_model_induction_cost (stmt_vec_info stmt_info, int ncopies)
3785 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3786 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3787 unsigned inside_cost, prologue_cost;
3789 /* loop cost for vec_loop. */
3790 inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3791 stmt_info, 0, vect_body);
3793 /* prologue cost for vec_init and vec_step. */
3794 prologue_cost = add_stmt_cost (target_cost_data, 2, scalar_to_vec,
3795 stmt_info, 0, vect_prologue);
3797 if (dump_enabled_p ())
3798 dump_printf_loc (MSG_NOTE, vect_location,
3799 "vect_model_induction_cost: inside_cost = %d, "
3800 "prologue_cost = %d .\n", inside_cost, prologue_cost);
3804 /* Function get_initial_def_for_induction
3806 Input:
3807 STMT - a stmt that performs an induction operation in the loop.
3808 IV_PHI - the initial value of the induction variable
3810 Output:
3811 Return a vector variable, initialized with the first VF values of
3812 the induction variable. E.g., for an iv with IV_PHI='X' and
3813 evolution S, for a vector of 4 units, we want to return:
3814 [X, X + S, X + 2*S, X + 3*S]. */
3816 static tree
3817 get_initial_def_for_induction (gimple *iv_phi)
3819 stmt_vec_info stmt_vinfo = vinfo_for_stmt (iv_phi);
3820 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3821 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3822 tree vectype;
3823 int nunits;
3824 edge pe = loop_preheader_edge (loop);
3825 struct loop *iv_loop;
3826 basic_block new_bb;
3827 tree new_vec, vec_init, vec_step, t;
3828 tree new_name;
3829 gimple *new_stmt;
3830 gphi *induction_phi;
3831 tree induc_def, vec_def, vec_dest;
3832 tree init_expr, step_expr;
3833 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3834 int i;
3835 int ncopies;
3836 tree expr;
3837 stmt_vec_info phi_info = vinfo_for_stmt (iv_phi);
3838 bool nested_in_vect_loop = false;
3839 gimple_seq stmts;
3840 imm_use_iterator imm_iter;
3841 use_operand_p use_p;
3842 gimple *exit_phi;
3843 edge latch_e;
3844 tree loop_arg;
3845 gimple_stmt_iterator si;
3846 basic_block bb = gimple_bb (iv_phi);
3847 tree stepvectype;
3848 tree resvectype;
3850 /* Is phi in an inner-loop, while vectorizing an enclosing outer-loop? */
3851 if (nested_in_vect_loop_p (loop, iv_phi))
3853 nested_in_vect_loop = true;
3854 iv_loop = loop->inner;
3856 else
3857 iv_loop = loop;
3858 gcc_assert (iv_loop == (gimple_bb (iv_phi))->loop_father);
3860 latch_e = loop_latch_edge (iv_loop);
3861 loop_arg = PHI_ARG_DEF_FROM_EDGE (iv_phi, latch_e);
3863 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
3864 gcc_assert (step_expr != NULL_TREE);
3866 pe = loop_preheader_edge (iv_loop);
3867 init_expr = PHI_ARG_DEF_FROM_EDGE (iv_phi,
3868 loop_preheader_edge (iv_loop));
3870 vectype = get_vectype_for_scalar_type (TREE_TYPE (init_expr));
3871 resvectype = get_vectype_for_scalar_type (TREE_TYPE (PHI_RESULT (iv_phi)));
3872 gcc_assert (vectype);
3873 nunits = TYPE_VECTOR_SUBPARTS (vectype);
3874 ncopies = vf / nunits;
3876 gcc_assert (phi_info);
3877 gcc_assert (ncopies >= 1);
3879 /* Convert the step to the desired type. */
3880 stmts = NULL;
3881 step_expr = gimple_convert (&stmts, TREE_TYPE (vectype), step_expr);
3882 if (stmts)
3884 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3885 gcc_assert (!new_bb);
3888 /* Find the first insertion point in the BB. */
3889 si = gsi_after_labels (bb);
3891 /* Create the vector that holds the initial_value of the induction. */
3892 if (nested_in_vect_loop)
3894 /* iv_loop is nested in the loop to be vectorized. init_expr had already
3895 been created during vectorization of previous stmts. We obtain it
3896 from the STMT_VINFO_VEC_STMT of the defining stmt. */
3897 vec_init = vect_get_vec_def_for_operand (init_expr, iv_phi);
3898 /* If the initial value is not of proper type, convert it. */
3899 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
3901 new_stmt
3902 = gimple_build_assign (vect_get_new_ssa_name (vectype,
3903 vect_simple_var,
3904 "vec_iv_"),
3905 VIEW_CONVERT_EXPR,
3906 build1 (VIEW_CONVERT_EXPR, vectype,
3907 vec_init));
3908 vec_init = gimple_assign_lhs (new_stmt);
3909 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
3910 new_stmt);
3911 gcc_assert (!new_bb);
3912 set_vinfo_for_stmt (new_stmt,
3913 new_stmt_vec_info (new_stmt, loop_vinfo));
3916 else
3918 vec<constructor_elt, va_gc> *v;
3920 /* iv_loop is the loop to be vectorized. Create:
3921 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
3922 stmts = NULL;
3923 new_name = gimple_convert (&stmts, TREE_TYPE (vectype), init_expr);
3925 vec_alloc (v, nunits);
3926 bool constant_p = is_gimple_min_invariant (new_name);
3927 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3928 for (i = 1; i < nunits; i++)
3930 /* Create: new_name_i = new_name + step_expr */
3931 new_name = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (new_name),
3932 new_name, step_expr);
3933 if (!is_gimple_min_invariant (new_name))
3934 constant_p = false;
3935 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3937 if (stmts)
3939 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3940 gcc_assert (!new_bb);
3943 /* Create a vector from [new_name_0, new_name_1, ..., new_name_nunits-1] */
3944 if (constant_p)
3945 new_vec = build_vector_from_ctor (vectype, v);
3946 else
3947 new_vec = build_constructor (vectype, v);
3948 vec_init = vect_init_vector (iv_phi, new_vec, vectype, NULL);
3952 /* Create the vector that holds the step of the induction. */
3953 if (nested_in_vect_loop)
3954 /* iv_loop is nested in the loop to be vectorized. Generate:
3955 vec_step = [S, S, S, S] */
3956 new_name = step_expr;
3957 else
3959 /* iv_loop is the loop to be vectorized. Generate:
3960 vec_step = [VF*S, VF*S, VF*S, VF*S] */
3961 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3963 expr = build_int_cst (integer_type_node, vf);
3964 expr = fold_convert (TREE_TYPE (step_expr), expr);
3966 else
3967 expr = build_int_cst (TREE_TYPE (step_expr), vf);
3968 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3969 expr, step_expr);
3970 if (TREE_CODE (step_expr) == SSA_NAME)
3971 new_name = vect_init_vector (iv_phi, new_name,
3972 TREE_TYPE (step_expr), NULL);
3975 t = unshare_expr (new_name);
3976 gcc_assert (CONSTANT_CLASS_P (new_name)
3977 || TREE_CODE (new_name) == SSA_NAME);
3978 stepvectype = get_vectype_for_scalar_type (TREE_TYPE (new_name));
3979 gcc_assert (stepvectype);
3980 new_vec = build_vector_from_val (stepvectype, t);
3981 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3984 /* Create the following def-use cycle:
3985 loop prolog:
3986 vec_init = ...
3987 vec_step = ...
3988 loop:
3989 vec_iv = PHI <vec_init, vec_loop>
3991 STMT
3993 vec_loop = vec_iv + vec_step; */
3995 /* Create the induction-phi that defines the induction-operand. */
3996 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
3997 induction_phi = create_phi_node (vec_dest, iv_loop->header);
3998 set_vinfo_for_stmt (induction_phi,
3999 new_stmt_vec_info (induction_phi, loop_vinfo));
4000 induc_def = PHI_RESULT (induction_phi);
4002 /* Create the iv update inside the loop */
4003 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR, induc_def, vec_step);
4004 vec_def = make_ssa_name (vec_dest, new_stmt);
4005 gimple_assign_set_lhs (new_stmt, vec_def);
4006 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4007 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo));
4009 /* Set the arguments of the phi node: */
4010 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
4011 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
4012 UNKNOWN_LOCATION);
4015 /* In case that vectorization factor (VF) is bigger than the number
4016 of elements that we can fit in a vectype (nunits), we have to generate
4017 more than one vector stmt - i.e - we need to "unroll" the
4018 vector stmt by a factor VF/nunits. For more details see documentation
4019 in vectorizable_operation. */
4021 if (ncopies > 1)
4023 stmt_vec_info prev_stmt_vinfo;
4024 /* FORNOW. This restriction should be relaxed. */
4025 gcc_assert (!nested_in_vect_loop);
4027 /* Create the vector that holds the step of the induction. */
4028 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
4030 expr = build_int_cst (integer_type_node, nunits);
4031 expr = fold_convert (TREE_TYPE (step_expr), expr);
4033 else
4034 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
4035 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
4036 expr, step_expr);
4037 if (TREE_CODE (step_expr) == SSA_NAME)
4038 new_name = vect_init_vector (iv_phi, new_name,
4039 TREE_TYPE (step_expr), NULL);
4040 t = unshare_expr (new_name);
4041 gcc_assert (CONSTANT_CLASS_P (new_name)
4042 || TREE_CODE (new_name) == SSA_NAME);
4043 new_vec = build_vector_from_val (stepvectype, t);
4044 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
4046 vec_def = induc_def;
4047 prev_stmt_vinfo = vinfo_for_stmt (induction_phi);
4048 for (i = 1; i < ncopies; i++)
4050 /* vec_i = vec_prev + vec_step */
4051 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR,
4052 vec_def, vec_step);
4053 vec_def = make_ssa_name (vec_dest, new_stmt);
4054 gimple_assign_set_lhs (new_stmt, vec_def);
4056 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4057 if (!useless_type_conversion_p (resvectype, vectype))
4059 new_stmt
4060 = gimple_build_assign
4061 (vect_get_new_vect_var (resvectype, vect_simple_var,
4062 "vec_iv_"),
4063 VIEW_CONVERT_EXPR,
4064 build1 (VIEW_CONVERT_EXPR, resvectype,
4065 gimple_assign_lhs (new_stmt)));
4066 gimple_assign_set_lhs (new_stmt,
4067 make_ssa_name
4068 (gimple_assign_lhs (new_stmt), new_stmt));
4069 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4071 set_vinfo_for_stmt (new_stmt,
4072 new_stmt_vec_info (new_stmt, loop_vinfo));
4073 STMT_VINFO_RELATED_STMT (prev_stmt_vinfo) = new_stmt;
4074 prev_stmt_vinfo = vinfo_for_stmt (new_stmt);
4078 if (nested_in_vect_loop)
4080 /* Find the loop-closed exit-phi of the induction, and record
4081 the final vector of induction results: */
4082 exit_phi = NULL;
4083 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
4085 gimple *use_stmt = USE_STMT (use_p);
4086 if (is_gimple_debug (use_stmt))
4087 continue;
4089 if (!flow_bb_inside_loop_p (iv_loop, gimple_bb (use_stmt)))
4091 exit_phi = use_stmt;
4092 break;
4095 if (exit_phi)
4097 stmt_vec_info stmt_vinfo = vinfo_for_stmt (exit_phi);
4098 /* FORNOW. Currently not supporting the case that an inner-loop induction
4099 is not used in the outer-loop (i.e. only outside the outer-loop). */
4100 gcc_assert (STMT_VINFO_RELEVANT_P (stmt_vinfo)
4101 && !STMT_VINFO_LIVE_P (stmt_vinfo));
4103 STMT_VINFO_VEC_STMT (stmt_vinfo) = new_stmt;
4104 if (dump_enabled_p ())
4106 dump_printf_loc (MSG_NOTE, vect_location,
4107 "vector of inductions after inner-loop:");
4108 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, new_stmt, 0);
4114 if (dump_enabled_p ())
4116 dump_printf_loc (MSG_NOTE, vect_location,
4117 "transform induction: created def-use cycle: ");
4118 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, induction_phi, 0);
4119 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
4120 SSA_NAME_DEF_STMT (vec_def), 0);
4123 STMT_VINFO_VEC_STMT (phi_info) = induction_phi;
4124 if (!useless_type_conversion_p (resvectype, vectype))
4126 new_stmt = gimple_build_assign (vect_get_new_vect_var (resvectype,
4127 vect_simple_var,
4128 "vec_iv_"),
4129 VIEW_CONVERT_EXPR,
4130 build1 (VIEW_CONVERT_EXPR, resvectype,
4131 induc_def));
4132 induc_def = make_ssa_name (gimple_assign_lhs (new_stmt), new_stmt);
4133 gimple_assign_set_lhs (new_stmt, induc_def);
4134 si = gsi_after_labels (bb);
4135 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4136 set_vinfo_for_stmt (new_stmt,
4137 new_stmt_vec_info (new_stmt, loop_vinfo));
4138 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_stmt))
4139 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (induction_phi));
4142 return induc_def;
4146 /* Function get_initial_def_for_reduction
4148 Input:
4149 STMT - a stmt that performs a reduction operation in the loop.
4150 INIT_VAL - the initial value of the reduction variable
4152 Output:
4153 ADJUSTMENT_DEF - a tree that holds a value to be added to the final result
4154 of the reduction (used for adjusting the epilog - see below).
4155 Return a vector variable, initialized according to the operation that STMT
4156 performs. This vector will be used as the initial value of the
4157 vector of partial results.
4159 Option1 (adjust in epilog): Initialize the vector as follows:
4160 add/bit or/xor: [0,0,...,0,0]
4161 mult/bit and: [1,1,...,1,1]
4162 min/max/cond_expr: [init_val,init_val,..,init_val,init_val]
4163 and when necessary (e.g. add/mult case) let the caller know
4164 that it needs to adjust the result by init_val.
4166 Option2: Initialize the vector as follows:
4167 add/bit or/xor: [init_val,0,0,...,0]
4168 mult/bit and: [init_val,1,1,...,1]
4169 min/max/cond_expr: [init_val,init_val,...,init_val]
4170 and no adjustments are needed.
4172 For example, for the following code:
4174 s = init_val;
4175 for (i=0;i<n;i++)
4176 s = s + a[i];
4178 STMT is 's = s + a[i]', and the reduction variable is 's'.
4179 For a vector of 4 units, we want to return either [0,0,0,init_val],
4180 or [0,0,0,0] and let the caller know that it needs to adjust
4181 the result at the end by 'init_val'.
4183 FORNOW, we are using the 'adjust in epilog' scheme, because this way the
4184 initialization vector is simpler (same element in all entries), if
4185 ADJUSTMENT_DEF is not NULL, and Option2 otherwise.
4187 A cost model should help decide between these two schemes. */
4189 tree
4190 get_initial_def_for_reduction (gimple *stmt, tree init_val,
4191 tree *adjustment_def)
4193 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
4194 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
4195 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
4196 tree scalar_type = TREE_TYPE (init_val);
4197 tree vectype = get_vectype_for_scalar_type (scalar_type);
4198 int nunits;
4199 enum tree_code code = gimple_assign_rhs_code (stmt);
4200 tree def_for_init;
4201 tree init_def;
4202 tree *elts;
4203 int i;
4204 bool nested_in_vect_loop = false;
4205 REAL_VALUE_TYPE real_init_val = dconst0;
4206 int int_init_val = 0;
4207 gimple *def_stmt = NULL;
4208 gimple_seq stmts = NULL;
4210 gcc_assert (vectype);
4211 nunits = TYPE_VECTOR_SUBPARTS (vectype);
4213 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
4214 || SCALAR_FLOAT_TYPE_P (scalar_type));
4216 if (nested_in_vect_loop_p (loop, stmt))
4217 nested_in_vect_loop = true;
4218 else
4219 gcc_assert (loop == (gimple_bb (stmt))->loop_father);
4221 /* In case of double reduction we only create a vector variable to be put
4222 in the reduction phi node. The actual statement creation is done in
4223 vect_create_epilog_for_reduction. */
4224 if (adjustment_def && nested_in_vect_loop
4225 && TREE_CODE (init_val) == SSA_NAME
4226 && (def_stmt = SSA_NAME_DEF_STMT (init_val))
4227 && gimple_code (def_stmt) == GIMPLE_PHI
4228 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
4229 && vinfo_for_stmt (def_stmt)
4230 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
4231 == vect_double_reduction_def)
4233 *adjustment_def = NULL;
4234 return vect_create_destination_var (init_val, vectype);
4237 /* In case of a nested reduction do not use an adjustment def as
4238 that case is not supported by the epilogue generation correctly
4239 if ncopies is not one. */
4240 if (adjustment_def && nested_in_vect_loop)
4242 *adjustment_def = NULL;
4243 return vect_get_vec_def_for_operand (init_val, stmt);
4246 switch (code)
4248 case WIDEN_SUM_EXPR:
4249 case DOT_PROD_EXPR:
4250 case SAD_EXPR:
4251 case PLUS_EXPR:
4252 case MINUS_EXPR:
4253 case BIT_IOR_EXPR:
4254 case BIT_XOR_EXPR:
4255 case MULT_EXPR:
4256 case BIT_AND_EXPR:
4257 /* ADJUSMENT_DEF is NULL when called from
4258 vect_create_epilog_for_reduction to vectorize double reduction. */
4259 if (adjustment_def)
4260 *adjustment_def = init_val;
4262 if (code == MULT_EXPR)
4264 real_init_val = dconst1;
4265 int_init_val = 1;
4268 if (code == BIT_AND_EXPR)
4269 int_init_val = -1;
4271 if (SCALAR_FLOAT_TYPE_P (scalar_type))
4272 def_for_init = build_real (scalar_type, real_init_val);
4273 else
4274 def_for_init = build_int_cst (scalar_type, int_init_val);
4276 /* Create a vector of '0' or '1' except the first element. */
4277 elts = XALLOCAVEC (tree, nunits);
4278 for (i = nunits - 2; i >= 0; --i)
4279 elts[i + 1] = def_for_init;
4281 /* Option1: the first element is '0' or '1' as well. */
4282 if (adjustment_def)
4284 elts[0] = def_for_init;
4285 init_def = build_vector (vectype, elts);
4286 break;
4289 /* Option2: the first element is INIT_VAL. */
4290 elts[0] = init_val;
4291 if (TREE_CONSTANT (init_val))
4292 init_def = build_vector (vectype, elts);
4293 else
4295 vec<constructor_elt, va_gc> *v;
4296 vec_alloc (v, nunits);
4297 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init_val);
4298 for (i = 1; i < nunits; ++i)
4299 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[i]);
4300 init_def = build_constructor (vectype, v);
4303 break;
4305 case MIN_EXPR:
4306 case MAX_EXPR:
4307 case COND_EXPR:
4308 if (adjustment_def)
4310 *adjustment_def = NULL_TREE;
4311 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_vinfo) != COND_REDUCTION)
4313 init_def = vect_get_vec_def_for_operand (init_val, stmt);
4314 break;
4317 init_val = gimple_convert (&stmts, TREE_TYPE (vectype), init_val);
4318 if (! gimple_seq_empty_p (stmts))
4319 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4320 init_def = build_vector_from_val (vectype, init_val);
4321 break;
4323 default:
4324 gcc_unreachable ();
4327 return init_def;
4330 /* Function vect_create_epilog_for_reduction
4332 Create code at the loop-epilog to finalize the result of a reduction
4333 computation.
4335 VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector
4336 reduction statements.
4337 STMT is the scalar reduction stmt that is being vectorized.
4338 NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the
4339 number of elements that we can fit in a vectype (nunits). In this case
4340 we have to generate more than one vector stmt - i.e - we need to "unroll"
4341 the vector stmt by a factor VF/nunits. For more details see documentation
4342 in vectorizable_operation.
4343 REDUC_CODE is the tree-code for the epilog reduction.
4344 REDUCTION_PHIS is a list of the phi-nodes that carry the reduction
4345 computation.
4346 REDUC_INDEX is the index of the operand in the right hand side of the
4347 statement that is defined by REDUCTION_PHI.
4348 DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled.
4349 SLP_NODE is an SLP node containing a group of reduction statements. The
4350 first one in this group is STMT.
4351 INDUCTION_INDEX is the index of the loop for condition reductions.
4352 Otherwise it is undefined.
4354 This function:
4355 1. Creates the reduction def-use cycles: sets the arguments for
4356 REDUCTION_PHIS:
4357 The loop-entry argument is the vectorized initial-value of the reduction.
4358 The loop-latch argument is taken from VECT_DEFS - the vector of partial
4359 sums.
4360 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
4361 by applying the operation specified by REDUC_CODE if available, or by
4362 other means (whole-vector shifts or a scalar loop).
4363 The function also creates a new phi node at the loop exit to preserve
4364 loop-closed form, as illustrated below.
4366 The flow at the entry to this function:
4368 loop:
4369 vec_def = phi <null, null> # REDUCTION_PHI
4370 VECT_DEF = vector_stmt # vectorized form of STMT
4371 s_loop = scalar_stmt # (scalar) STMT
4372 loop_exit:
4373 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4374 use <s_out0>
4375 use <s_out0>
4377 The above is transformed by this function into:
4379 loop:
4380 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4381 VECT_DEF = vector_stmt # vectorized form of STMT
4382 s_loop = scalar_stmt # (scalar) STMT
4383 loop_exit:
4384 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4385 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4386 v_out2 = reduce <v_out1>
4387 s_out3 = extract_field <v_out2, 0>
4388 s_out4 = adjust_result <s_out3>
4389 use <s_out4>
4390 use <s_out4>
4393 static void
4394 vect_create_epilog_for_reduction (vec<tree> vect_defs, gimple *stmt,
4395 int ncopies, enum tree_code reduc_code,
4396 vec<gimple *> reduction_phis,
4397 int reduc_index, bool double_reduc,
4398 slp_tree slp_node, tree induction_index)
4400 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
4401 stmt_vec_info prev_phi_info;
4402 tree vectype;
4403 machine_mode mode;
4404 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
4405 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
4406 basic_block exit_bb;
4407 tree scalar_dest;
4408 tree scalar_type;
4409 gimple *new_phi = NULL, *phi;
4410 gimple_stmt_iterator exit_gsi;
4411 tree vec_dest;
4412 tree new_temp = NULL_TREE, new_dest, new_name, new_scalar_dest;
4413 gimple *epilog_stmt = NULL;
4414 enum tree_code code = gimple_assign_rhs_code (stmt);
4415 gimple *exit_phi;
4416 tree bitsize;
4417 tree adjustment_def = NULL;
4418 tree vec_initial_def = NULL;
4419 tree reduction_op, expr, def, initial_def = NULL;
4420 tree orig_name, scalar_result;
4421 imm_use_iterator imm_iter, phi_imm_iter;
4422 use_operand_p use_p, phi_use_p;
4423 gimple *use_stmt, *orig_stmt, *reduction_phi = NULL;
4424 bool nested_in_vect_loop = false;
4425 auto_vec<gimple *> new_phis;
4426 auto_vec<gimple *> inner_phis;
4427 enum vect_def_type dt = vect_unknown_def_type;
4428 int j, i;
4429 auto_vec<tree> scalar_results;
4430 unsigned int group_size = 1, k, ratio;
4431 auto_vec<tree> vec_initial_defs;
4432 auto_vec<gimple *> phis;
4433 bool slp_reduc = false;
4434 tree new_phi_result;
4435 gimple *inner_phi = NULL;
4437 if (slp_node)
4438 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
4440 if (nested_in_vect_loop_p (loop, stmt))
4442 outer_loop = loop;
4443 loop = loop->inner;
4444 nested_in_vect_loop = true;
4445 gcc_assert (!slp_node);
4448 reduction_op = get_reduction_op (stmt, reduc_index);
4450 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
4451 gcc_assert (vectype);
4452 mode = TYPE_MODE (vectype);
4454 /* 1. Create the reduction def-use cycle:
4455 Set the arguments of REDUCTION_PHIS, i.e., transform
4457 loop:
4458 vec_def = phi <null, null> # REDUCTION_PHI
4459 VECT_DEF = vector_stmt # vectorized form of STMT
4462 into:
4464 loop:
4465 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4466 VECT_DEF = vector_stmt # vectorized form of STMT
4469 (in case of SLP, do it for all the phis). */
4471 /* Get the loop-entry arguments. */
4472 enum vect_def_type initial_def_dt = vect_unknown_def_type;
4473 if (slp_node)
4474 vect_get_vec_defs (reduction_op, NULL_TREE, stmt, &vec_initial_defs,
4475 NULL, slp_node, reduc_index);
4476 else
4478 /* Get at the scalar def before the loop, that defines the initial value
4479 of the reduction variable. */
4480 gimple *def_stmt = SSA_NAME_DEF_STMT (reduction_op);
4481 initial_def = PHI_ARG_DEF_FROM_EDGE (def_stmt,
4482 loop_preheader_edge (loop));
4483 vect_is_simple_use (initial_def, loop_vinfo, &def_stmt, &initial_def_dt);
4484 vec_initial_def = get_initial_def_for_reduction (stmt, initial_def,
4485 &adjustment_def);
4486 vec_initial_defs.create (1);
4487 vec_initial_defs.quick_push (vec_initial_def);
4490 /* Set phi nodes arguments. */
4491 FOR_EACH_VEC_ELT (reduction_phis, i, phi)
4493 tree vec_init_def, def;
4494 gimple_seq stmts;
4495 vec_init_def = force_gimple_operand (vec_initial_defs[i], &stmts,
4496 true, NULL_TREE);
4497 if (stmts)
4498 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4500 def = vect_defs[i];
4501 for (j = 0; j < ncopies; j++)
4503 if (j != 0)
4505 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4506 if (nested_in_vect_loop)
4507 vec_init_def
4508 = vect_get_vec_def_for_stmt_copy (initial_def_dt,
4509 vec_init_def);
4512 /* Set the loop-entry arg of the reduction-phi. */
4514 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4515 == INTEGER_INDUC_COND_REDUCTION)
4517 /* Initialise the reduction phi to zero. This prevents initial
4518 values of non-zero interferring with the reduction op. */
4519 gcc_assert (ncopies == 1);
4520 gcc_assert (i == 0);
4522 tree vec_init_def_type = TREE_TYPE (vec_init_def);
4523 tree zero_vec = build_zero_cst (vec_init_def_type);
4525 add_phi_arg (as_a <gphi *> (phi), zero_vec,
4526 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4528 else
4529 add_phi_arg (as_a <gphi *> (phi), vec_init_def,
4530 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4532 /* Set the loop-latch arg for the reduction-phi. */
4533 if (j > 0)
4534 def = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type, def);
4536 add_phi_arg (as_a <gphi *> (phi), def, loop_latch_edge (loop),
4537 UNKNOWN_LOCATION);
4539 if (dump_enabled_p ())
4541 dump_printf_loc (MSG_NOTE, vect_location,
4542 "transform reduction: created def-use cycle: ");
4543 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
4544 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (def), 0);
4549 /* 2. Create epilog code.
4550 The reduction epilog code operates across the elements of the vector
4551 of partial results computed by the vectorized loop.
4552 The reduction epilog code consists of:
4554 step 1: compute the scalar result in a vector (v_out2)
4555 step 2: extract the scalar result (s_out3) from the vector (v_out2)
4556 step 3: adjust the scalar result (s_out3) if needed.
4558 Step 1 can be accomplished using one the following three schemes:
4559 (scheme 1) using reduc_code, if available.
4560 (scheme 2) using whole-vector shifts, if available.
4561 (scheme 3) using a scalar loop. In this case steps 1+2 above are
4562 combined.
4564 The overall epilog code looks like this:
4566 s_out0 = phi <s_loop> # original EXIT_PHI
4567 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4568 v_out2 = reduce <v_out1> # step 1
4569 s_out3 = extract_field <v_out2, 0> # step 2
4570 s_out4 = adjust_result <s_out3> # step 3
4572 (step 3 is optional, and steps 1 and 2 may be combined).
4573 Lastly, the uses of s_out0 are replaced by s_out4. */
4576 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
4577 v_out1 = phi <VECT_DEF>
4578 Store them in NEW_PHIS. */
4580 exit_bb = single_exit (loop)->dest;
4581 prev_phi_info = NULL;
4582 new_phis.create (vect_defs.length ());
4583 FOR_EACH_VEC_ELT (vect_defs, i, def)
4585 for (j = 0; j < ncopies; j++)
4587 tree new_def = copy_ssa_name (def);
4588 phi = create_phi_node (new_def, exit_bb);
4589 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, loop_vinfo));
4590 if (j == 0)
4591 new_phis.quick_push (phi);
4592 else
4594 def = vect_get_vec_def_for_stmt_copy (dt, def);
4595 STMT_VINFO_RELATED_STMT (prev_phi_info) = phi;
4598 SET_PHI_ARG_DEF (phi, single_exit (loop)->dest_idx, def);
4599 prev_phi_info = vinfo_for_stmt (phi);
4603 /* The epilogue is created for the outer-loop, i.e., for the loop being
4604 vectorized. Create exit phis for the outer loop. */
4605 if (double_reduc)
4607 loop = outer_loop;
4608 exit_bb = single_exit (loop)->dest;
4609 inner_phis.create (vect_defs.length ());
4610 FOR_EACH_VEC_ELT (new_phis, i, phi)
4612 tree new_result = copy_ssa_name (PHI_RESULT (phi));
4613 gphi *outer_phi = create_phi_node (new_result, exit_bb);
4614 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4615 PHI_RESULT (phi));
4616 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4617 loop_vinfo));
4618 inner_phis.quick_push (phi);
4619 new_phis[i] = outer_phi;
4620 prev_phi_info = vinfo_for_stmt (outer_phi);
4621 while (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi)))
4623 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4624 new_result = copy_ssa_name (PHI_RESULT (phi));
4625 outer_phi = create_phi_node (new_result, exit_bb);
4626 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4627 PHI_RESULT (phi));
4628 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4629 loop_vinfo));
4630 STMT_VINFO_RELATED_STMT (prev_phi_info) = outer_phi;
4631 prev_phi_info = vinfo_for_stmt (outer_phi);
4636 exit_gsi = gsi_after_labels (exit_bb);
4638 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
4639 (i.e. when reduc_code is not available) and in the final adjustment
4640 code (if needed). Also get the original scalar reduction variable as
4641 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
4642 represents a reduction pattern), the tree-code and scalar-def are
4643 taken from the original stmt that the pattern-stmt (STMT) replaces.
4644 Otherwise (it is a regular reduction) - the tree-code and scalar-def
4645 are taken from STMT. */
4647 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4648 if (!orig_stmt)
4650 /* Regular reduction */
4651 orig_stmt = stmt;
4653 else
4655 /* Reduction pattern */
4656 stmt_vec_info stmt_vinfo = vinfo_for_stmt (orig_stmt);
4657 gcc_assert (STMT_VINFO_IN_PATTERN_P (stmt_vinfo));
4658 gcc_assert (STMT_VINFO_RELATED_STMT (stmt_vinfo) == stmt);
4661 code = gimple_assign_rhs_code (orig_stmt);
4662 /* For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore,
4663 partial results are added and not subtracted. */
4664 if (code == MINUS_EXPR)
4665 code = PLUS_EXPR;
4667 scalar_dest = gimple_assign_lhs (orig_stmt);
4668 scalar_type = TREE_TYPE (scalar_dest);
4669 scalar_results.create (group_size);
4670 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
4671 bitsize = TYPE_SIZE (scalar_type);
4673 /* In case this is a reduction in an inner-loop while vectorizing an outer
4674 loop - we don't need to extract a single scalar result at the end of the
4675 inner-loop (unless it is double reduction, i.e., the use of reduction is
4676 outside the outer-loop). The final vector of partial results will be used
4677 in the vectorized outer-loop, or reduced to a scalar result at the end of
4678 the outer-loop. */
4679 if (nested_in_vect_loop && !double_reduc)
4680 goto vect_finalize_reduction;
4682 /* SLP reduction without reduction chain, e.g.,
4683 # a1 = phi <a2, a0>
4684 # b1 = phi <b2, b0>
4685 a2 = operation (a1)
4686 b2 = operation (b1) */
4687 slp_reduc = (slp_node && !GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
4689 /* In case of reduction chain, e.g.,
4690 # a1 = phi <a3, a0>
4691 a2 = operation (a1)
4692 a3 = operation (a2),
4694 we may end up with more than one vector result. Here we reduce them to
4695 one vector. */
4696 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4698 tree first_vect = PHI_RESULT (new_phis[0]);
4699 tree tmp;
4700 gassign *new_vec_stmt = NULL;
4702 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4703 for (k = 1; k < new_phis.length (); k++)
4705 gimple *next_phi = new_phis[k];
4706 tree second_vect = PHI_RESULT (next_phi);
4708 tmp = build2 (code, vectype, first_vect, second_vect);
4709 new_vec_stmt = gimple_build_assign (vec_dest, tmp);
4710 first_vect = make_ssa_name (vec_dest, new_vec_stmt);
4711 gimple_assign_set_lhs (new_vec_stmt, first_vect);
4712 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4715 new_phi_result = first_vect;
4716 if (new_vec_stmt)
4718 new_phis.truncate (0);
4719 new_phis.safe_push (new_vec_stmt);
4722 else
4723 new_phi_result = PHI_RESULT (new_phis[0]);
4725 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
4727 /* For condition reductions, we have a vector (NEW_PHI_RESULT) containing
4728 various data values where the condition matched and another vector
4729 (INDUCTION_INDEX) containing all the indexes of those matches. We
4730 need to extract the last matching index (which will be the index with
4731 highest value) and use this to index into the data vector.
4732 For the case where there were no matches, the data vector will contain
4733 all default values and the index vector will be all zeros. */
4735 /* Get various versions of the type of the vector of indexes. */
4736 tree index_vec_type = TREE_TYPE (induction_index);
4737 gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
4738 tree index_scalar_type = TREE_TYPE (index_vec_type);
4739 tree index_vec_cmp_type = build_same_sized_truth_vector_type
4740 (index_vec_type);
4742 /* Get an unsigned integer version of the type of the data vector. */
4743 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
4744 tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
4745 tree vectype_unsigned = build_vector_type
4746 (scalar_type_unsigned, TYPE_VECTOR_SUBPARTS (vectype));
4748 /* First we need to create a vector (ZERO_VEC) of zeros and another
4749 vector (MAX_INDEX_VEC) filled with the last matching index, which we
4750 can create using a MAX reduction and then expanding.
4751 In the case where the loop never made any matches, the max index will
4752 be zero. */
4754 /* Vector of {0, 0, 0,...}. */
4755 tree zero_vec = make_ssa_name (vectype);
4756 tree zero_vec_rhs = build_zero_cst (vectype);
4757 gimple *zero_vec_stmt = gimple_build_assign (zero_vec, zero_vec_rhs);
4758 gsi_insert_before (&exit_gsi, zero_vec_stmt, GSI_SAME_STMT);
4760 /* Find maximum value from the vector of found indexes. */
4761 tree max_index = make_ssa_name (index_scalar_type);
4762 gimple *max_index_stmt = gimple_build_assign (max_index, REDUC_MAX_EXPR,
4763 induction_index);
4764 gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
4766 /* Vector of {max_index, max_index, max_index,...}. */
4767 tree max_index_vec = make_ssa_name (index_vec_type);
4768 tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
4769 max_index);
4770 gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
4771 max_index_vec_rhs);
4772 gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
4774 /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
4775 with the vector (INDUCTION_INDEX) of found indexes, choosing values
4776 from the data vector (NEW_PHI_RESULT) for matches, 0 (ZERO_VEC)
4777 otherwise. Only one value should match, resulting in a vector
4778 (VEC_COND) with one data value and the rest zeros.
4779 In the case where the loop never made any matches, every index will
4780 match, resulting in a vector with all data values (which will all be
4781 the default value). */
4783 /* Compare the max index vector to the vector of found indexes to find
4784 the position of the max value. */
4785 tree vec_compare = make_ssa_name (index_vec_cmp_type);
4786 gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
4787 induction_index,
4788 max_index_vec);
4789 gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
4791 /* Use the compare to choose either values from the data vector or
4792 zero. */
4793 tree vec_cond = make_ssa_name (vectype);
4794 gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
4795 vec_compare, new_phi_result,
4796 zero_vec);
4797 gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
4799 /* Finally we need to extract the data value from the vector (VEC_COND)
4800 into a scalar (MATCHED_DATA_REDUC). Logically we want to do a OR
4801 reduction, but because this doesn't exist, we can use a MAX reduction
4802 instead. The data value might be signed or a float so we need to cast
4803 it first.
4804 In the case where the loop never made any matches, the data values are
4805 all identical, and so will reduce down correctly. */
4807 /* Make the matched data values unsigned. */
4808 tree vec_cond_cast = make_ssa_name (vectype_unsigned);
4809 tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
4810 vec_cond);
4811 gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
4812 VIEW_CONVERT_EXPR,
4813 vec_cond_cast_rhs);
4814 gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
4816 /* Reduce down to a scalar value. */
4817 tree data_reduc = make_ssa_name (scalar_type_unsigned);
4818 optab ot = optab_for_tree_code (REDUC_MAX_EXPR, vectype_unsigned,
4819 optab_default);
4820 gcc_assert (optab_handler (ot, TYPE_MODE (vectype_unsigned))
4821 != CODE_FOR_nothing);
4822 gimple *data_reduc_stmt = gimple_build_assign (data_reduc,
4823 REDUC_MAX_EXPR,
4824 vec_cond_cast);
4825 gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
4827 /* Convert the reduced value back to the result type and set as the
4828 result. */
4829 tree data_reduc_cast = build1 (VIEW_CONVERT_EXPR, scalar_type,
4830 data_reduc);
4831 epilog_stmt = gimple_build_assign (new_scalar_dest, data_reduc_cast);
4832 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4833 gimple_assign_set_lhs (epilog_stmt, new_temp);
4834 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4835 scalar_results.safe_push (new_temp);
4838 /* 2.3 Create the reduction code, using one of the three schemes described
4839 above. In SLP we simply need to extract all the elements from the
4840 vector (without reducing them), so we use scalar shifts. */
4841 else if (reduc_code != ERROR_MARK && !slp_reduc)
4843 tree tmp;
4844 tree vec_elem_type;
4846 /*** Case 1: Create:
4847 v_out2 = reduc_expr <v_out1> */
4849 if (dump_enabled_p ())
4850 dump_printf_loc (MSG_NOTE, vect_location,
4851 "Reduce using direct vector reduction.\n");
4853 vec_elem_type = TREE_TYPE (TREE_TYPE (new_phi_result));
4854 if (!useless_type_conversion_p (scalar_type, vec_elem_type))
4856 tree tmp_dest =
4857 vect_create_destination_var (scalar_dest, vec_elem_type);
4858 tmp = build1 (reduc_code, vec_elem_type, new_phi_result);
4859 epilog_stmt = gimple_build_assign (tmp_dest, tmp);
4860 new_temp = make_ssa_name (tmp_dest, epilog_stmt);
4861 gimple_assign_set_lhs (epilog_stmt, new_temp);
4862 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4864 tmp = build1 (NOP_EXPR, scalar_type, new_temp);
4866 else
4867 tmp = build1 (reduc_code, scalar_type, new_phi_result);
4869 epilog_stmt = gimple_build_assign (new_scalar_dest, tmp);
4870 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4871 gimple_assign_set_lhs (epilog_stmt, new_temp);
4872 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4874 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4875 == INTEGER_INDUC_COND_REDUCTION)
4877 /* Earlier we set the initial value to be zero. Check the result
4878 and if it is zero then replace with the original initial
4879 value. */
4880 tree zero = build_zero_cst (scalar_type);
4881 tree zcompare = build2 (EQ_EXPR, boolean_type_node, new_temp, zero);
4883 tmp = make_ssa_name (new_scalar_dest);
4884 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
4885 initial_def, new_temp);
4886 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4887 new_temp = tmp;
4890 scalar_results.safe_push (new_temp);
4892 else
4894 bool reduce_with_shift = have_whole_vector_shift (mode);
4895 int element_bitsize = tree_to_uhwi (bitsize);
4896 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4897 tree vec_temp;
4899 /* Regardless of whether we have a whole vector shift, if we're
4900 emulating the operation via tree-vect-generic, we don't want
4901 to use it. Only the first round of the reduction is likely
4902 to still be profitable via emulation. */
4903 /* ??? It might be better to emit a reduction tree code here, so that
4904 tree-vect-generic can expand the first round via bit tricks. */
4905 if (!VECTOR_MODE_P (mode))
4906 reduce_with_shift = false;
4907 else
4909 optab optab = optab_for_tree_code (code, vectype, optab_default);
4910 if (optab_handler (optab, mode) == CODE_FOR_nothing)
4911 reduce_with_shift = false;
4914 if (reduce_with_shift && !slp_reduc)
4916 int nelements = vec_size_in_bits / element_bitsize;
4917 unsigned char *sel = XALLOCAVEC (unsigned char, nelements);
4919 int elt_offset;
4921 tree zero_vec = build_zero_cst (vectype);
4922 /*** Case 2: Create:
4923 for (offset = nelements/2; offset >= 1; offset/=2)
4925 Create: va' = vec_shift <va, offset>
4926 Create: va = vop <va, va'>
4927 } */
4929 tree rhs;
4931 if (dump_enabled_p ())
4932 dump_printf_loc (MSG_NOTE, vect_location,
4933 "Reduce using vector shifts\n");
4935 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4936 new_temp = new_phi_result;
4937 for (elt_offset = nelements / 2;
4938 elt_offset >= 1;
4939 elt_offset /= 2)
4941 calc_vec_perm_mask_for_shift (mode, elt_offset, sel);
4942 tree mask = vect_gen_perm_mask_any (vectype, sel);
4943 epilog_stmt = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
4944 new_temp, zero_vec, mask);
4945 new_name = make_ssa_name (vec_dest, epilog_stmt);
4946 gimple_assign_set_lhs (epilog_stmt, new_name);
4947 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4949 epilog_stmt = gimple_build_assign (vec_dest, code, new_name,
4950 new_temp);
4951 new_temp = make_ssa_name (vec_dest, epilog_stmt);
4952 gimple_assign_set_lhs (epilog_stmt, new_temp);
4953 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4956 /* 2.4 Extract the final scalar result. Create:
4957 s_out3 = extract_field <v_out2, bitpos> */
4959 if (dump_enabled_p ())
4960 dump_printf_loc (MSG_NOTE, vect_location,
4961 "extract scalar result\n");
4963 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp,
4964 bitsize, bitsize_zero_node);
4965 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4966 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4967 gimple_assign_set_lhs (epilog_stmt, new_temp);
4968 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4969 scalar_results.safe_push (new_temp);
4971 else
4973 /*** Case 3: Create:
4974 s = extract_field <v_out2, 0>
4975 for (offset = element_size;
4976 offset < vector_size;
4977 offset += element_size;)
4979 Create: s' = extract_field <v_out2, offset>
4980 Create: s = op <s, s'> // For non SLP cases
4981 } */
4983 if (dump_enabled_p ())
4984 dump_printf_loc (MSG_NOTE, vect_location,
4985 "Reduce using scalar code.\n");
4987 vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4988 FOR_EACH_VEC_ELT (new_phis, i, new_phi)
4990 int bit_offset;
4991 if (gimple_code (new_phi) == GIMPLE_PHI)
4992 vec_temp = PHI_RESULT (new_phi);
4993 else
4994 vec_temp = gimple_assign_lhs (new_phi);
4995 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp, bitsize,
4996 bitsize_zero_node);
4997 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4998 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4999 gimple_assign_set_lhs (epilog_stmt, new_temp);
5000 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5002 /* In SLP we don't need to apply reduction operation, so we just
5003 collect s' values in SCALAR_RESULTS. */
5004 if (slp_reduc)
5005 scalar_results.safe_push (new_temp);
5007 for (bit_offset = element_bitsize;
5008 bit_offset < vec_size_in_bits;
5009 bit_offset += element_bitsize)
5011 tree bitpos = bitsize_int (bit_offset);
5012 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp,
5013 bitsize, bitpos);
5015 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
5016 new_name = make_ssa_name (new_scalar_dest, epilog_stmt);
5017 gimple_assign_set_lhs (epilog_stmt, new_name);
5018 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5020 if (slp_reduc)
5022 /* In SLP we don't need to apply reduction operation, so
5023 we just collect s' values in SCALAR_RESULTS. */
5024 new_temp = new_name;
5025 scalar_results.safe_push (new_name);
5027 else
5029 epilog_stmt = gimple_build_assign (new_scalar_dest, code,
5030 new_name, new_temp);
5031 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
5032 gimple_assign_set_lhs (epilog_stmt, new_temp);
5033 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5038 /* The only case where we need to reduce scalar results in SLP, is
5039 unrolling. If the size of SCALAR_RESULTS is greater than
5040 GROUP_SIZE, we reduce them combining elements modulo
5041 GROUP_SIZE. */
5042 if (slp_reduc)
5044 tree res, first_res, new_res;
5045 gimple *new_stmt;
5047 /* Reduce multiple scalar results in case of SLP unrolling. */
5048 for (j = group_size; scalar_results.iterate (j, &res);
5049 j++)
5051 first_res = scalar_results[j % group_size];
5052 new_stmt = gimple_build_assign (new_scalar_dest, code,
5053 first_res, res);
5054 new_res = make_ssa_name (new_scalar_dest, new_stmt);
5055 gimple_assign_set_lhs (new_stmt, new_res);
5056 gsi_insert_before (&exit_gsi, new_stmt, GSI_SAME_STMT);
5057 scalar_results[j % group_size] = new_res;
5060 else
5061 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
5062 scalar_results.safe_push (new_temp);
5066 vect_finalize_reduction:
5068 if (double_reduc)
5069 loop = loop->inner;
5071 /* 2.5 Adjust the final result by the initial value of the reduction
5072 variable. (When such adjustment is not needed, then
5073 'adjustment_def' is zero). For example, if code is PLUS we create:
5074 new_temp = loop_exit_def + adjustment_def */
5076 if (adjustment_def)
5078 gcc_assert (!slp_reduc);
5079 if (nested_in_vect_loop)
5081 new_phi = new_phis[0];
5082 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) == VECTOR_TYPE);
5083 expr = build2 (code, vectype, PHI_RESULT (new_phi), adjustment_def);
5084 new_dest = vect_create_destination_var (scalar_dest, vectype);
5086 else
5088 new_temp = scalar_results[0];
5089 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
5090 expr = build2 (code, scalar_type, new_temp, adjustment_def);
5091 new_dest = vect_create_destination_var (scalar_dest, scalar_type);
5094 epilog_stmt = gimple_build_assign (new_dest, expr);
5095 new_temp = make_ssa_name (new_dest, epilog_stmt);
5096 gimple_assign_set_lhs (epilog_stmt, new_temp);
5097 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5098 if (nested_in_vect_loop)
5100 set_vinfo_for_stmt (epilog_stmt,
5101 new_stmt_vec_info (epilog_stmt, loop_vinfo));
5102 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (epilog_stmt)) =
5103 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_phi));
5105 if (!double_reduc)
5106 scalar_results.quick_push (new_temp);
5107 else
5108 scalar_results[0] = new_temp;
5110 else
5111 scalar_results[0] = new_temp;
5113 new_phis[0] = epilog_stmt;
5116 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
5117 phis with new adjusted scalar results, i.e., replace use <s_out0>
5118 with use <s_out4>.
5120 Transform:
5121 loop_exit:
5122 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5123 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5124 v_out2 = reduce <v_out1>
5125 s_out3 = extract_field <v_out2, 0>
5126 s_out4 = adjust_result <s_out3>
5127 use <s_out0>
5128 use <s_out0>
5130 into:
5132 loop_exit:
5133 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5134 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5135 v_out2 = reduce <v_out1>
5136 s_out3 = extract_field <v_out2, 0>
5137 s_out4 = adjust_result <s_out3>
5138 use <s_out4>
5139 use <s_out4> */
5142 /* In SLP reduction chain we reduce vector results into one vector if
5143 necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of
5144 the last stmt in the reduction chain, since we are looking for the loop
5145 exit phi node. */
5146 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
5148 gimple *dest_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1];
5149 /* Handle reduction patterns. */
5150 if (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt)))
5151 dest_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt));
5153 scalar_dest = gimple_assign_lhs (dest_stmt);
5154 group_size = 1;
5157 /* In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in
5158 case that GROUP_SIZE is greater than vectorization factor). Therefore, we
5159 need to match SCALAR_RESULTS with corresponding statements. The first
5160 (GROUP_SIZE / number of new vector stmts) scalar results correspond to
5161 the first vector stmt, etc.
5162 (RATIO is equal to (GROUP_SIZE / number of new vector stmts)). */
5163 if (group_size > new_phis.length ())
5165 ratio = group_size / new_phis.length ();
5166 gcc_assert (!(group_size % new_phis.length ()));
5168 else
5169 ratio = 1;
5171 for (k = 0; k < group_size; k++)
5173 if (k % ratio == 0)
5175 epilog_stmt = new_phis[k / ratio];
5176 reduction_phi = reduction_phis[k / ratio];
5177 if (double_reduc)
5178 inner_phi = inner_phis[k / ratio];
5181 if (slp_reduc)
5183 gimple *current_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[k];
5185 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (current_stmt));
5186 /* SLP statements can't participate in patterns. */
5187 gcc_assert (!orig_stmt);
5188 scalar_dest = gimple_assign_lhs (current_stmt);
5191 phis.create (3);
5192 /* Find the loop-closed-use at the loop exit of the original scalar
5193 result. (The reduction result is expected to have two immediate uses -
5194 one at the latch block, and one at the loop exit). */
5195 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5196 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))
5197 && !is_gimple_debug (USE_STMT (use_p)))
5198 phis.safe_push (USE_STMT (use_p));
5200 /* While we expect to have found an exit_phi because of loop-closed-ssa
5201 form we can end up without one if the scalar cycle is dead. */
5203 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5205 if (outer_loop)
5207 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
5208 gphi *vect_phi;
5210 /* FORNOW. Currently not supporting the case that an inner-loop
5211 reduction is not used in the outer-loop (but only outside the
5212 outer-loop), unless it is double reduction. */
5213 gcc_assert ((STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
5214 && !STMT_VINFO_LIVE_P (exit_phi_vinfo))
5215 || double_reduc);
5217 if (double_reduc)
5218 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = inner_phi;
5219 else
5220 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = epilog_stmt;
5221 if (!double_reduc
5222 || STMT_VINFO_DEF_TYPE (exit_phi_vinfo)
5223 != vect_double_reduction_def)
5224 continue;
5226 /* Handle double reduction:
5228 stmt1: s1 = phi <s0, s2> - double reduction phi (outer loop)
5229 stmt2: s3 = phi <s1, s4> - (regular) reduc phi (inner loop)
5230 stmt3: s4 = use (s3) - (regular) reduc stmt (inner loop)
5231 stmt4: s2 = phi <s4> - double reduction stmt (outer loop)
5233 At that point the regular reduction (stmt2 and stmt3) is
5234 already vectorized, as well as the exit phi node, stmt4.
5235 Here we vectorize the phi node of double reduction, stmt1, and
5236 update all relevant statements. */
5238 /* Go through all the uses of s2 to find double reduction phi
5239 node, i.e., stmt1 above. */
5240 orig_name = PHI_RESULT (exit_phi);
5241 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5243 stmt_vec_info use_stmt_vinfo;
5244 stmt_vec_info new_phi_vinfo;
5245 tree vect_phi_init, preheader_arg, vect_phi_res, init_def;
5246 basic_block bb = gimple_bb (use_stmt);
5247 gimple *use;
5249 /* Check that USE_STMT is really double reduction phi
5250 node. */
5251 if (gimple_code (use_stmt) != GIMPLE_PHI
5252 || gimple_phi_num_args (use_stmt) != 2
5253 || bb->loop_father != outer_loop)
5254 continue;
5255 use_stmt_vinfo = vinfo_for_stmt (use_stmt);
5256 if (!use_stmt_vinfo
5257 || STMT_VINFO_DEF_TYPE (use_stmt_vinfo)
5258 != vect_double_reduction_def)
5259 continue;
5261 /* Create vector phi node for double reduction:
5262 vs1 = phi <vs0, vs2>
5263 vs1 was created previously in this function by a call to
5264 vect_get_vec_def_for_operand and is stored in
5265 vec_initial_def;
5266 vs2 is defined by INNER_PHI, the vectorized EXIT_PHI;
5267 vs0 is created here. */
5269 /* Create vector phi node. */
5270 vect_phi = create_phi_node (vec_initial_def, bb);
5271 new_phi_vinfo = new_stmt_vec_info (vect_phi,
5272 loop_vec_info_for_loop (outer_loop));
5273 set_vinfo_for_stmt (vect_phi, new_phi_vinfo);
5275 /* Create vs0 - initial def of the double reduction phi. */
5276 preheader_arg = PHI_ARG_DEF_FROM_EDGE (use_stmt,
5277 loop_preheader_edge (outer_loop));
5278 init_def = get_initial_def_for_reduction (stmt,
5279 preheader_arg, NULL);
5280 vect_phi_init = vect_init_vector (use_stmt, init_def,
5281 vectype, NULL);
5283 /* Update phi node arguments with vs0 and vs2. */
5284 add_phi_arg (vect_phi, vect_phi_init,
5285 loop_preheader_edge (outer_loop),
5286 UNKNOWN_LOCATION);
5287 add_phi_arg (vect_phi, PHI_RESULT (inner_phi),
5288 loop_latch_edge (outer_loop), UNKNOWN_LOCATION);
5289 if (dump_enabled_p ())
5291 dump_printf_loc (MSG_NOTE, vect_location,
5292 "created double reduction phi node: ");
5293 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, vect_phi, 0);
5296 vect_phi_res = PHI_RESULT (vect_phi);
5298 /* Replace the use, i.e., set the correct vs1 in the regular
5299 reduction phi node. FORNOW, NCOPIES is always 1, so the
5300 loop is redundant. */
5301 use = reduction_phi;
5302 for (j = 0; j < ncopies; j++)
5304 edge pr_edge = loop_preheader_edge (loop);
5305 SET_PHI_ARG_DEF (use, pr_edge->dest_idx, vect_phi_res);
5306 use = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use));
5312 phis.release ();
5313 if (nested_in_vect_loop)
5315 if (double_reduc)
5316 loop = outer_loop;
5317 else
5318 continue;
5321 phis.create (3);
5322 /* Find the loop-closed-use at the loop exit of the original scalar
5323 result. (The reduction result is expected to have two immediate uses,
5324 one at the latch block, and one at the loop exit). For double
5325 reductions we are looking for exit phis of the outer loop. */
5326 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5328 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
5330 if (!is_gimple_debug (USE_STMT (use_p)))
5331 phis.safe_push (USE_STMT (use_p));
5333 else
5335 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
5337 tree phi_res = PHI_RESULT (USE_STMT (use_p));
5339 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
5341 if (!flow_bb_inside_loop_p (loop,
5342 gimple_bb (USE_STMT (phi_use_p)))
5343 && !is_gimple_debug (USE_STMT (phi_use_p)))
5344 phis.safe_push (USE_STMT (phi_use_p));
5350 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5352 /* Replace the uses: */
5353 orig_name = PHI_RESULT (exit_phi);
5354 scalar_result = scalar_results[k];
5355 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5356 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
5357 SET_USE (use_p, scalar_result);
5360 phis.release ();
5365 /* Function is_nonwrapping_integer_induction.
5367 Check if STMT (which is part of loop LOOP) both increments and
5368 does not cause overflow. */
5370 static bool
5371 is_nonwrapping_integer_induction (gimple *stmt, struct loop *loop)
5373 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
5374 tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
5375 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
5376 tree lhs_type = TREE_TYPE (gimple_phi_result (stmt));
5377 widest_int ni, max_loop_value, lhs_max;
5378 bool overflow = false;
5380 /* Make sure the loop is integer based. */
5381 if (TREE_CODE (base) != INTEGER_CST
5382 || TREE_CODE (step) != INTEGER_CST)
5383 return false;
5385 /* Check that the induction increments. */
5386 if (tree_int_cst_sgn (step) == -1)
5387 return false;
5389 /* Check that the max size of the loop will not wrap. */
5391 if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
5392 return true;
5394 if (! max_stmt_executions (loop, &ni))
5395 return false;
5397 max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
5398 &overflow);
5399 if (overflow)
5400 return false;
5402 max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
5403 TYPE_SIGN (lhs_type), &overflow);
5404 if (overflow)
5405 return false;
5407 return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
5408 <= TYPE_PRECISION (lhs_type));
5411 /* Function vectorizable_reduction.
5413 Check if STMT performs a reduction operation that can be vectorized.
5414 If VEC_STMT is also passed, vectorize the STMT: create a vectorized
5415 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
5416 Return FALSE if not a vectorizable STMT, TRUE otherwise.
5418 This function also handles reduction idioms (patterns) that have been
5419 recognized in advance during vect_pattern_recog. In this case, STMT may be
5420 of this form:
5421 X = pattern_expr (arg0, arg1, ..., X)
5422 and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original
5423 sequence that had been detected and replaced by the pattern-stmt (STMT).
5425 This function also handles reduction of condition expressions, for example:
5426 for (int i = 0; i < N; i++)
5427 if (a[i] < value)
5428 last = a[i];
5429 This is handled by vectorising the loop and creating an additional vector
5430 containing the loop indexes for which "a[i] < value" was true. In the
5431 function epilogue this is reduced to a single max value and then used to
5432 index into the vector of results.
5434 In some cases of reduction patterns, the type of the reduction variable X is
5435 different than the type of the other arguments of STMT.
5436 In such cases, the vectype that is used when transforming STMT into a vector
5437 stmt is different than the vectype that is used to determine the
5438 vectorization factor, because it consists of a different number of elements
5439 than the actual number of elements that are being operated upon in parallel.
5441 For example, consider an accumulation of shorts into an int accumulator.
5442 On some targets it's possible to vectorize this pattern operating on 8
5443 shorts at a time (hence, the vectype for purposes of determining the
5444 vectorization factor should be V8HI); on the other hand, the vectype that
5445 is used to create the vector form is actually V4SI (the type of the result).
5447 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
5448 indicates what is the actual level of parallelism (V8HI in the example), so
5449 that the right vectorization factor would be derived. This vectype
5450 corresponds to the type of arguments to the reduction stmt, and should *NOT*
5451 be used to create the vectorized stmt. The right vectype for the vectorized
5452 stmt is obtained from the type of the result X:
5453 get_vectype_for_scalar_type (TREE_TYPE (X))
5455 This means that, contrary to "regular" reductions (or "regular" stmts in
5456 general), the following equation:
5457 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X))
5458 does *NOT* necessarily hold for reduction patterns. */
5460 bool
5461 vectorizable_reduction (gimple *stmt, gimple_stmt_iterator *gsi,
5462 gimple **vec_stmt, slp_tree slp_node)
5464 tree vec_dest;
5465 tree scalar_dest;
5466 tree loop_vec_def0 = NULL_TREE, loop_vec_def1 = NULL_TREE;
5467 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5468 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
5469 tree vectype_in = NULL_TREE;
5470 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5471 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5472 enum tree_code code, orig_code, epilog_reduc_code;
5473 machine_mode vec_mode;
5474 int op_type;
5475 optab optab, reduc_optab;
5476 tree new_temp = NULL_TREE;
5477 gimple *def_stmt;
5478 enum vect_def_type dt, cond_reduc_dt = vect_unknown_def_type;
5479 gphi *new_phi = NULL;
5480 tree scalar_type;
5481 bool is_simple_use;
5482 gimple *orig_stmt;
5483 stmt_vec_info orig_stmt_info;
5484 tree expr = NULL_TREE;
5485 int i;
5486 int ncopies;
5487 int epilog_copies;
5488 stmt_vec_info prev_stmt_info, prev_phi_info;
5489 bool single_defuse_cycle = false;
5490 tree reduc_def = NULL_TREE;
5491 gimple *new_stmt = NULL;
5492 int j;
5493 tree ops[3];
5494 bool nested_cycle = false, found_nested_cycle_def = false;
5495 gimple *reduc_def_stmt = NULL;
5496 bool double_reduc = false, dummy;
5497 basic_block def_bb;
5498 struct loop * def_stmt_loop, *outer_loop = NULL;
5499 tree def_arg;
5500 gimple *def_arg_stmt;
5501 auto_vec<tree> vec_oprnds0;
5502 auto_vec<tree> vec_oprnds1;
5503 auto_vec<tree> vect_defs;
5504 auto_vec<gimple *> phis;
5505 int vec_num;
5506 tree def0, def1, tem, op1 = NULL_TREE;
5507 bool first_p = true;
5508 tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
5509 tree cond_reduc_val = NULL_TREE;
5511 /* In case of reduction chain we switch to the first stmt in the chain, but
5512 we don't update STMT_INFO, since only the last stmt is marked as reduction
5513 and has reduction properties. */
5514 if (GROUP_FIRST_ELEMENT (stmt_info)
5515 && GROUP_FIRST_ELEMENT (stmt_info) != stmt)
5517 stmt = GROUP_FIRST_ELEMENT (stmt_info);
5518 first_p = false;
5521 if (nested_in_vect_loop_p (loop, stmt))
5523 outer_loop = loop;
5524 loop = loop->inner;
5525 nested_cycle = true;
5528 /* 1. Is vectorizable reduction? */
5529 /* Not supportable if the reduction variable is used in the loop, unless
5530 it's a reduction chain. */
5531 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
5532 && !GROUP_FIRST_ELEMENT (stmt_info))
5533 return false;
5535 /* Reductions that are not used even in an enclosing outer-loop,
5536 are expected to be "live" (used out of the loop). */
5537 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
5538 && !STMT_VINFO_LIVE_P (stmt_info))
5539 return false;
5541 /* Make sure it was already recognized as a reduction computation. */
5542 if (STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_reduction_def
5543 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_nested_cycle)
5544 return false;
5546 /* 2. Has this been recognized as a reduction pattern?
5548 Check if STMT represents a pattern that has been recognized
5549 in earlier analysis stages. For stmts that represent a pattern,
5550 the STMT_VINFO_RELATED_STMT field records the last stmt in
5551 the original sequence that constitutes the pattern. */
5553 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
5554 if (orig_stmt)
5556 orig_stmt_info = vinfo_for_stmt (orig_stmt);
5557 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
5558 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
5561 /* 3. Check the operands of the operation. The first operands are defined
5562 inside the loop body. The last operand is the reduction variable,
5563 which is defined by the loop-header-phi. */
5565 gcc_assert (is_gimple_assign (stmt));
5567 /* Flatten RHS. */
5568 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
5570 case GIMPLE_SINGLE_RHS:
5571 op_type = TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt));
5572 if (op_type == ternary_op)
5574 tree rhs = gimple_assign_rhs1 (stmt);
5575 ops[0] = TREE_OPERAND (rhs, 0);
5576 ops[1] = TREE_OPERAND (rhs, 1);
5577 ops[2] = TREE_OPERAND (rhs, 2);
5578 code = TREE_CODE (rhs);
5580 else
5581 return false;
5582 break;
5584 case GIMPLE_BINARY_RHS:
5585 code = gimple_assign_rhs_code (stmt);
5586 op_type = TREE_CODE_LENGTH (code);
5587 gcc_assert (op_type == binary_op);
5588 ops[0] = gimple_assign_rhs1 (stmt);
5589 ops[1] = gimple_assign_rhs2 (stmt);
5590 break;
5592 case GIMPLE_TERNARY_RHS:
5593 code = gimple_assign_rhs_code (stmt);
5594 op_type = TREE_CODE_LENGTH (code);
5595 gcc_assert (op_type == ternary_op);
5596 ops[0] = gimple_assign_rhs1 (stmt);
5597 ops[1] = gimple_assign_rhs2 (stmt);
5598 ops[2] = gimple_assign_rhs3 (stmt);
5599 break;
5601 case GIMPLE_UNARY_RHS:
5602 return false;
5604 default:
5605 gcc_unreachable ();
5607 /* The default is that the reduction variable is the last in statement. */
5608 int reduc_index = op_type - 1;
5609 if (code == MINUS_EXPR)
5610 reduc_index = 0;
5612 if (code == COND_EXPR && slp_node)
5613 return false;
5615 scalar_dest = gimple_assign_lhs (stmt);
5616 scalar_type = TREE_TYPE (scalar_dest);
5617 if (!POINTER_TYPE_P (scalar_type) && !INTEGRAL_TYPE_P (scalar_type)
5618 && !SCALAR_FLOAT_TYPE_P (scalar_type))
5619 return false;
5621 /* Do not try to vectorize bit-precision reductions. */
5622 if ((TYPE_PRECISION (scalar_type)
5623 != GET_MODE_PRECISION (TYPE_MODE (scalar_type))))
5624 return false;
5626 /* All uses but the last are expected to be defined in the loop.
5627 The last use is the reduction variable. In case of nested cycle this
5628 assumption is not true: we use reduc_index to record the index of the
5629 reduction variable. */
5630 for (i = 0; i < op_type; i++)
5632 if (i == reduc_index)
5633 continue;
5635 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
5636 if (i == 0 && code == COND_EXPR)
5637 continue;
5639 is_simple_use = vect_is_simple_use (ops[i], loop_vinfo,
5640 &def_stmt, &dt, &tem);
5641 if (!vectype_in)
5642 vectype_in = tem;
5643 gcc_assert (is_simple_use);
5645 if (dt != vect_internal_def
5646 && dt != vect_external_def
5647 && dt != vect_constant_def
5648 && dt != vect_induction_def
5649 && !(dt == vect_nested_cycle && nested_cycle))
5650 return false;
5652 if (dt == vect_nested_cycle)
5654 found_nested_cycle_def = true;
5655 reduc_def_stmt = def_stmt;
5656 reduc_index = i;
5659 if (i == 1 && code == COND_EXPR)
5661 /* Record how value of COND_EXPR is defined. */
5662 if (dt == vect_constant_def)
5664 cond_reduc_dt = dt;
5665 cond_reduc_val = ops[i];
5667 if (dt == vect_induction_def && def_stmt != NULL
5668 && is_nonwrapping_integer_induction (def_stmt, loop))
5669 cond_reduc_dt = dt;
5673 is_simple_use = vect_is_simple_use (ops[reduc_index], loop_vinfo,
5674 &def_stmt, &dt, &tem);
5675 if (!vectype_in)
5676 vectype_in = tem;
5677 gcc_assert (is_simple_use);
5678 if (!found_nested_cycle_def)
5679 reduc_def_stmt = def_stmt;
5681 if (reduc_def_stmt && gimple_code (reduc_def_stmt) != GIMPLE_PHI)
5682 return false;
5684 if (!(dt == vect_reduction_def
5685 || dt == vect_nested_cycle
5686 || ((dt == vect_internal_def || dt == vect_external_def
5687 || dt == vect_constant_def || dt == vect_induction_def)
5688 && nested_cycle && found_nested_cycle_def)))
5690 /* For pattern recognized stmts, orig_stmt might be a reduction,
5691 but some helper statements for the pattern might not, or
5692 might be COND_EXPRs with reduction uses in the condition. */
5693 gcc_assert (orig_stmt);
5694 return false;
5697 enum vect_reduction_type v_reduc_type;
5698 gimple *tmp = vect_is_simple_reduction (loop_vinfo, reduc_def_stmt,
5699 !nested_cycle, &dummy, false,
5700 &v_reduc_type);
5702 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = v_reduc_type;
5703 /* If we have a condition reduction, see if we can simplify it further. */
5704 if (v_reduc_type == COND_REDUCTION)
5706 if (cond_reduc_dt == vect_induction_def)
5708 if (dump_enabled_p ())
5709 dump_printf_loc (MSG_NOTE, vect_location,
5710 "condition expression based on "
5711 "integer induction.\n");
5712 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5713 = INTEGER_INDUC_COND_REDUCTION;
5716 /* Loop peeling modifies initial value of reduction PHI, which
5717 makes the reduction stmt to be transformed different to the
5718 original stmt analyzed. We need to record reduction code for
5719 CONST_COND_REDUCTION type reduction at analyzing stage, thus
5720 it can be used directly at transform stage. */
5721 if (STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MAX_EXPR
5722 || STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MIN_EXPR)
5724 /* Also set the reduction type to CONST_COND_REDUCTION. */
5725 gcc_assert (cond_reduc_dt == vect_constant_def);
5726 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = CONST_COND_REDUCTION;
5728 else if (cond_reduc_dt == vect_constant_def)
5730 enum vect_def_type cond_initial_dt;
5731 gimple *def_stmt = SSA_NAME_DEF_STMT (ops[reduc_index]);
5732 tree cond_initial_val
5733 = PHI_ARG_DEF_FROM_EDGE (def_stmt, loop_preheader_edge (loop));
5735 gcc_assert (cond_reduc_val != NULL_TREE);
5736 vect_is_simple_use (cond_initial_val, loop_vinfo,
5737 &def_stmt, &cond_initial_dt);
5738 if (cond_initial_dt == vect_constant_def
5739 && types_compatible_p (TREE_TYPE (cond_initial_val),
5740 TREE_TYPE (cond_reduc_val)))
5742 tree e = fold_build2 (LE_EXPR, boolean_type_node,
5743 cond_initial_val, cond_reduc_val);
5744 if (e && (integer_onep (e) || integer_zerop (e)))
5746 if (dump_enabled_p ())
5747 dump_printf_loc (MSG_NOTE, vect_location,
5748 "condition expression based on "
5749 "compile time constant.\n");
5750 /* Record reduction code at analysis stage. */
5751 STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info)
5752 = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
5753 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5754 = CONST_COND_REDUCTION;
5760 if (orig_stmt)
5761 gcc_assert (tmp == orig_stmt
5762 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == orig_stmt);
5763 else
5764 /* We changed STMT to be the first stmt in reduction chain, hence we
5765 check that in this case the first element in the chain is STMT. */
5766 gcc_assert (stmt == tmp
5767 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == stmt);
5769 if (STMT_VINFO_LIVE_P (vinfo_for_stmt (reduc_def_stmt)))
5770 return false;
5772 if (slp_node)
5773 ncopies = 1;
5774 else
5775 ncopies = (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5776 / TYPE_VECTOR_SUBPARTS (vectype_in));
5778 gcc_assert (ncopies >= 1);
5780 vec_mode = TYPE_MODE (vectype_in);
5782 if (code == COND_EXPR)
5784 /* Only call during the analysis stage, otherwise we'll lose
5785 STMT_VINFO_TYPE. */
5786 if (!vec_stmt && !vectorizable_condition (stmt, gsi, NULL,
5787 ops[reduc_index], 0, NULL))
5789 if (dump_enabled_p ())
5790 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5791 "unsupported condition in reduction\n");
5792 return false;
5795 else
5797 /* 4. Supportable by target? */
5799 if (code == LSHIFT_EXPR || code == RSHIFT_EXPR
5800 || code == LROTATE_EXPR || code == RROTATE_EXPR)
5802 /* Shifts and rotates are only supported by vectorizable_shifts,
5803 not vectorizable_reduction. */
5804 if (dump_enabled_p ())
5805 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5806 "unsupported shift or rotation.\n");
5807 return false;
5810 /* 4.1. check support for the operation in the loop */
5811 optab = optab_for_tree_code (code, vectype_in, optab_default);
5812 if (!optab)
5814 if (dump_enabled_p ())
5815 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5816 "no optab.\n");
5818 return false;
5821 if (optab_handler (optab, vec_mode) == CODE_FOR_nothing)
5823 if (dump_enabled_p ())
5824 dump_printf (MSG_NOTE, "op not supported by target.\n");
5826 if (GET_MODE_SIZE (vec_mode) != UNITS_PER_WORD
5827 || LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5828 < vect_min_worthwhile_factor (code))
5829 return false;
5831 if (dump_enabled_p ())
5832 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
5835 /* Worthwhile without SIMD support? */
5836 if (!VECTOR_MODE_P (TYPE_MODE (vectype_in))
5837 && LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5838 < vect_min_worthwhile_factor (code))
5840 if (dump_enabled_p ())
5841 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5842 "not worthwhile without SIMD support.\n");
5844 return false;
5848 /* 4.2. Check support for the epilog operation.
5850 If STMT represents a reduction pattern, then the type of the
5851 reduction variable may be different than the type of the rest
5852 of the arguments. For example, consider the case of accumulation
5853 of shorts into an int accumulator; The original code:
5854 S1: int_a = (int) short_a;
5855 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
5857 was replaced with:
5858 STMT: int_acc = widen_sum <short_a, int_acc>
5860 This means that:
5861 1. The tree-code that is used to create the vector operation in the
5862 epilog code (that reduces the partial results) is not the
5863 tree-code of STMT, but is rather the tree-code of the original
5864 stmt from the pattern that STMT is replacing. I.e, in the example
5865 above we want to use 'widen_sum' in the loop, but 'plus' in the
5866 epilog.
5867 2. The type (mode) we use to check available target support
5868 for the vector operation to be created in the *epilog*, is
5869 determined by the type of the reduction variable (in the example
5870 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
5871 However the type (mode) we use to check available target support
5872 for the vector operation to be created *inside the loop*, is
5873 determined by the type of the other arguments to STMT (in the
5874 example we'd check this: optab_handler (widen_sum_optab,
5875 vect_short_mode)).
5877 This is contrary to "regular" reductions, in which the types of all
5878 the arguments are the same as the type of the reduction variable.
5879 For "regular" reductions we can therefore use the same vector type
5880 (and also the same tree-code) when generating the epilog code and
5881 when generating the code inside the loop. */
5883 if (orig_stmt)
5885 /* This is a reduction pattern: get the vectype from the type of the
5886 reduction variable, and get the tree-code from orig_stmt. */
5887 gcc_assert (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5888 == TREE_CODE_REDUCTION);
5889 orig_code = gimple_assign_rhs_code (orig_stmt);
5890 gcc_assert (vectype_out);
5891 vec_mode = TYPE_MODE (vectype_out);
5893 else
5895 /* Regular reduction: use the same vectype and tree-code as used for
5896 the vector code inside the loop can be used for the epilog code. */
5897 orig_code = code;
5899 if (code == MINUS_EXPR)
5900 orig_code = PLUS_EXPR;
5902 /* For simple condition reductions, replace with the actual expression
5903 we want to base our reduction around. */
5904 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == CONST_COND_REDUCTION)
5906 orig_code = STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info);
5907 gcc_assert (orig_code == MAX_EXPR || orig_code == MIN_EXPR);
5909 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5910 == INTEGER_INDUC_COND_REDUCTION)
5911 orig_code = MAX_EXPR;
5914 if (nested_cycle)
5916 def_bb = gimple_bb (reduc_def_stmt);
5917 def_stmt_loop = def_bb->loop_father;
5918 def_arg = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
5919 loop_preheader_edge (def_stmt_loop));
5920 if (TREE_CODE (def_arg) == SSA_NAME
5921 && (def_arg_stmt = SSA_NAME_DEF_STMT (def_arg))
5922 && gimple_code (def_arg_stmt) == GIMPLE_PHI
5923 && flow_bb_inside_loop_p (outer_loop, gimple_bb (def_arg_stmt))
5924 && vinfo_for_stmt (def_arg_stmt)
5925 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_arg_stmt))
5926 == vect_double_reduction_def)
5927 double_reduc = true;
5930 epilog_reduc_code = ERROR_MARK;
5932 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != COND_REDUCTION)
5934 if (reduction_code_for_scalar_code (orig_code, &epilog_reduc_code))
5936 reduc_optab = optab_for_tree_code (epilog_reduc_code, vectype_out,
5937 optab_default);
5938 if (!reduc_optab)
5940 if (dump_enabled_p ())
5941 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5942 "no optab for reduction.\n");
5944 epilog_reduc_code = ERROR_MARK;
5946 else if (optab_handler (reduc_optab, vec_mode) == CODE_FOR_nothing)
5948 if (dump_enabled_p ())
5949 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5950 "reduc op not supported by target.\n");
5952 epilog_reduc_code = ERROR_MARK;
5955 /* When epilog_reduc_code is ERROR_MARK then a reduction will be
5956 generated in the epilog using multiple expressions. This does not
5957 work for condition reductions. */
5958 if (epilog_reduc_code == ERROR_MARK
5959 && (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5960 == INTEGER_INDUC_COND_REDUCTION
5961 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5962 == CONST_COND_REDUCTION))
5964 if (dump_enabled_p ())
5965 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5966 "no reduc code for scalar code.\n");
5967 return false;
5970 else
5972 if (!nested_cycle || double_reduc)
5974 if (dump_enabled_p ())
5975 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5976 "no reduc code for scalar code.\n");
5978 return false;
5982 else
5984 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
5985 cr_index_scalar_type = make_unsigned_type (scalar_precision);
5986 cr_index_vector_type = build_vector_type
5987 (cr_index_scalar_type, TYPE_VECTOR_SUBPARTS (vectype_out));
5989 epilog_reduc_code = REDUC_MAX_EXPR;
5990 optab = optab_for_tree_code (REDUC_MAX_EXPR, cr_index_vector_type,
5991 optab_default);
5992 if (optab_handler (optab, TYPE_MODE (cr_index_vector_type))
5993 == CODE_FOR_nothing)
5995 if (dump_enabled_p ())
5996 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5997 "reduc max op not supported by target.\n");
5998 return false;
6002 if ((double_reduc
6003 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != TREE_CODE_REDUCTION)
6004 && ncopies > 1)
6006 if (dump_enabled_p ())
6007 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6008 "multiple types in double reduction or condition "
6009 "reduction.\n");
6010 return false;
6013 /* In case of widenning multiplication by a constant, we update the type
6014 of the constant to be the type of the other operand. We check that the
6015 constant fits the type in the pattern recognition pass. */
6016 if (code == DOT_PROD_EXPR
6017 && !types_compatible_p (TREE_TYPE (ops[0]), TREE_TYPE (ops[1])))
6019 if (TREE_CODE (ops[0]) == INTEGER_CST)
6020 ops[0] = fold_convert (TREE_TYPE (ops[1]), ops[0]);
6021 else if (TREE_CODE (ops[1]) == INTEGER_CST)
6022 ops[1] = fold_convert (TREE_TYPE (ops[0]), ops[1]);
6023 else
6025 if (dump_enabled_p ())
6026 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6027 "invalid types in dot-prod\n");
6029 return false;
6033 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
6035 widest_int ni;
6037 if (! max_loop_iterations (loop, &ni))
6039 if (dump_enabled_p ())
6040 dump_printf_loc (MSG_NOTE, vect_location,
6041 "loop count not known, cannot create cond "
6042 "reduction.\n");
6043 return false;
6045 /* Convert backedges to iterations. */
6046 ni += 1;
6048 /* The additional index will be the same type as the condition. Check
6049 that the loop can fit into this less one (because we'll use up the
6050 zero slot for when there are no matches). */
6051 tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
6052 if (wi::geu_p (ni, wi::to_widest (max_index)))
6054 if (dump_enabled_p ())
6055 dump_printf_loc (MSG_NOTE, vect_location,
6056 "loop size is greater than data size.\n");
6057 return false;
6061 if (!vec_stmt) /* transformation not required. */
6063 if (first_p
6064 && !vect_model_reduction_cost (stmt_info, epilog_reduc_code, ncopies,
6065 reduc_index))
6066 return false;
6067 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
6068 return true;
6071 /** Transform. **/
6073 if (dump_enabled_p ())
6074 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
6076 /* FORNOW: Multiple types are not supported for condition. */
6077 if (code == COND_EXPR)
6078 gcc_assert (ncopies == 1);
6080 /* Create the destination vector */
6081 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
6083 /* In case the vectorization factor (VF) is bigger than the number
6084 of elements that we can fit in a vectype (nunits), we have to generate
6085 more than one vector stmt - i.e - we need to "unroll" the
6086 vector stmt by a factor VF/nunits. For more details see documentation
6087 in vectorizable_operation. */
6089 /* If the reduction is used in an outer loop we need to generate
6090 VF intermediate results, like so (e.g. for ncopies=2):
6091 r0 = phi (init, r0)
6092 r1 = phi (init, r1)
6093 r0 = x0 + r0;
6094 r1 = x1 + r1;
6095 (i.e. we generate VF results in 2 registers).
6096 In this case we have a separate def-use cycle for each copy, and therefore
6097 for each copy we get the vector def for the reduction variable from the
6098 respective phi node created for this copy.
6100 Otherwise (the reduction is unused in the loop nest), we can combine
6101 together intermediate results, like so (e.g. for ncopies=2):
6102 r = phi (init, r)
6103 r = x0 + r;
6104 r = x1 + r;
6105 (i.e. we generate VF/2 results in a single register).
6106 In this case for each copy we get the vector def for the reduction variable
6107 from the vectorized reduction operation generated in the previous iteration.
6110 if (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
6112 single_defuse_cycle = true;
6113 epilog_copies = 1;
6115 else
6116 epilog_copies = ncopies;
6118 prev_stmt_info = NULL;
6119 prev_phi_info = NULL;
6120 if (slp_node)
6121 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6122 else
6124 vec_num = 1;
6125 vec_oprnds0.create (1);
6126 if (op_type == ternary_op)
6127 vec_oprnds1.create (1);
6130 phis.create (vec_num);
6131 vect_defs.create (vec_num);
6132 if (!slp_node)
6133 vect_defs.quick_push (NULL_TREE);
6135 for (j = 0; j < ncopies; j++)
6137 if (j == 0 || !single_defuse_cycle)
6139 for (i = 0; i < vec_num; i++)
6141 /* Create the reduction-phi that defines the reduction
6142 operand. */
6143 new_phi = create_phi_node (vec_dest, loop->header);
6144 set_vinfo_for_stmt (new_phi,
6145 new_stmt_vec_info (new_phi, loop_vinfo));
6146 if (j == 0 || slp_node)
6147 phis.quick_push (new_phi);
6151 if (code == COND_EXPR)
6153 gcc_assert (!slp_node);
6154 vectorizable_condition (stmt, gsi, vec_stmt,
6155 PHI_RESULT (phis[0]),
6156 reduc_index, NULL);
6157 /* Multiple types are not supported for condition. */
6158 break;
6161 /* Handle uses. */
6162 if (j == 0)
6164 if (slp_node)
6166 /* Get vec defs for all the operands except the reduction index,
6167 ensuring the ordering of the ops in the vector is kept. */
6168 auto_vec<tree, 3> slp_ops;
6169 auto_vec<vec<tree>, 3> vec_defs;
6171 slp_ops.quick_push ((reduc_index == 0) ? NULL : ops[0]);
6172 slp_ops.quick_push ((reduc_index == 1) ? NULL : ops[1]);
6173 if (op_type == ternary_op)
6174 slp_ops.quick_push ((reduc_index == 2) ? NULL : ops[2]);
6176 vect_get_slp_defs (slp_ops, slp_node, &vec_defs, -1);
6178 vec_oprnds0.safe_splice (vec_defs[(reduc_index == 0) ? 1 : 0]);
6179 if (op_type == ternary_op)
6180 vec_oprnds1.safe_splice (vec_defs[(reduc_index == 2) ? 1 : 2]);
6182 else
6184 loop_vec_def0 = vect_get_vec_def_for_operand (ops[!reduc_index],
6185 stmt);
6186 vec_oprnds0.quick_push (loop_vec_def0);
6187 if (op_type == ternary_op)
6189 op1 = (reduc_index == 0) ? ops[2] : ops[1];
6190 loop_vec_def1 = vect_get_vec_def_for_operand (op1, stmt);
6191 vec_oprnds1.quick_push (loop_vec_def1);
6195 else
6197 if (!slp_node)
6199 enum vect_def_type dt;
6200 gimple *dummy_stmt;
6202 vect_is_simple_use (ops[!reduc_index], loop_vinfo,
6203 &dummy_stmt, &dt);
6204 loop_vec_def0 = vect_get_vec_def_for_stmt_copy (dt,
6205 loop_vec_def0);
6206 vec_oprnds0[0] = loop_vec_def0;
6207 if (op_type == ternary_op)
6209 vect_is_simple_use (op1, loop_vinfo, &dummy_stmt, &dt);
6210 loop_vec_def1 = vect_get_vec_def_for_stmt_copy (dt,
6211 loop_vec_def1);
6212 vec_oprnds1[0] = loop_vec_def1;
6216 if (single_defuse_cycle)
6217 reduc_def = gimple_assign_lhs (new_stmt);
6219 STMT_VINFO_RELATED_STMT (prev_phi_info) = new_phi;
6222 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
6224 if (slp_node)
6225 reduc_def = PHI_RESULT (phis[i]);
6226 else
6228 if (!single_defuse_cycle || j == 0)
6229 reduc_def = PHI_RESULT (new_phi);
6232 def1 = ((op_type == ternary_op)
6233 ? vec_oprnds1[i] : NULL);
6234 if (op_type == binary_op)
6236 if (reduc_index == 0)
6237 expr = build2 (code, vectype_out, reduc_def, def0);
6238 else
6239 expr = build2 (code, vectype_out, def0, reduc_def);
6241 else
6243 if (reduc_index == 0)
6244 expr = build3 (code, vectype_out, reduc_def, def0, def1);
6245 else
6247 if (reduc_index == 1)
6248 expr = build3 (code, vectype_out, def0, reduc_def, def1);
6249 else
6250 expr = build3 (code, vectype_out, def0, def1, reduc_def);
6254 new_stmt = gimple_build_assign (vec_dest, expr);
6255 new_temp = make_ssa_name (vec_dest, new_stmt);
6256 gimple_assign_set_lhs (new_stmt, new_temp);
6257 vect_finish_stmt_generation (stmt, new_stmt, gsi);
6259 if (slp_node)
6261 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
6262 vect_defs.quick_push (new_temp);
6264 else
6265 vect_defs[0] = new_temp;
6268 if (slp_node)
6269 continue;
6271 if (j == 0)
6272 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt;
6273 else
6274 STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt;
6276 prev_stmt_info = vinfo_for_stmt (new_stmt);
6277 prev_phi_info = vinfo_for_stmt (new_phi);
6280 tree indx_before_incr, indx_after_incr, cond_name = NULL;
6282 /* Finalize the reduction-phi (set its arguments) and create the
6283 epilog reduction code. */
6284 if ((!single_defuse_cycle || code == COND_EXPR) && !slp_node)
6286 new_temp = gimple_assign_lhs (*vec_stmt);
6287 vect_defs[0] = new_temp;
6289 /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
6290 which is updated with the current index of the loop for every match of
6291 the original loop's cond_expr (VEC_STMT). This results in a vector
6292 containing the last time the condition passed for that vector lane.
6293 The first match will be a 1 to allow 0 to be used for non-matching
6294 indexes. If there are no matches at all then the vector will be all
6295 zeroes. */
6296 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
6298 int nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
6299 int k;
6301 gcc_assert (gimple_assign_rhs_code (*vec_stmt) == VEC_COND_EXPR);
6303 /* First we create a simple vector induction variable which starts
6304 with the values {1,2,3,...} (SERIES_VECT) and increments by the
6305 vector size (STEP). */
6307 /* Create a {1,2,3,...} vector. */
6308 tree *vtemp = XALLOCAVEC (tree, nunits_out);
6309 for (k = 0; k < nunits_out; ++k)
6310 vtemp[k] = build_int_cst (cr_index_scalar_type, k + 1);
6311 tree series_vect = build_vector (cr_index_vector_type, vtemp);
6313 /* Create a vector of the step value. */
6314 tree step = build_int_cst (cr_index_scalar_type, nunits_out);
6315 tree vec_step = build_vector_from_val (cr_index_vector_type, step);
6317 /* Create an induction variable. */
6318 gimple_stmt_iterator incr_gsi;
6319 bool insert_after;
6320 standard_iv_increment_position (loop, &incr_gsi, &insert_after);
6321 create_iv (series_vect, vec_step, NULL_TREE, loop, &incr_gsi,
6322 insert_after, &indx_before_incr, &indx_after_incr);
6324 /* Next create a new phi node vector (NEW_PHI_TREE) which starts
6325 filled with zeros (VEC_ZERO). */
6327 /* Create a vector of 0s. */
6328 tree zero = build_zero_cst (cr_index_scalar_type);
6329 tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
6331 /* Create a vector phi node. */
6332 tree new_phi_tree = make_ssa_name (cr_index_vector_type);
6333 new_phi = create_phi_node (new_phi_tree, loop->header);
6334 set_vinfo_for_stmt (new_phi,
6335 new_stmt_vec_info (new_phi, loop_vinfo));
6336 add_phi_arg (new_phi, vec_zero, loop_preheader_edge (loop),
6337 UNKNOWN_LOCATION);
6339 /* Now take the condition from the loops original cond_expr
6340 (VEC_STMT) and produce a new cond_expr (INDEX_COND_EXPR) which for
6341 every match uses values from the induction variable
6342 (INDEX_BEFORE_INCR) otherwise uses values from the phi node
6343 (NEW_PHI_TREE).
6344 Finally, we update the phi (NEW_PHI_TREE) to take the value of
6345 the new cond_expr (INDEX_COND_EXPR). */
6347 /* Duplicate the condition from vec_stmt. */
6348 tree ccompare = unshare_expr (gimple_assign_rhs1 (*vec_stmt));
6350 /* Create a conditional, where the condition is taken from vec_stmt
6351 (CCOMPARE), then is the induction index (INDEX_BEFORE_INCR) and
6352 else is the phi (NEW_PHI_TREE). */
6353 tree index_cond_expr = build3 (VEC_COND_EXPR, cr_index_vector_type,
6354 ccompare, indx_before_incr,
6355 new_phi_tree);
6356 cond_name = make_ssa_name (cr_index_vector_type);
6357 gimple *index_condition = gimple_build_assign (cond_name,
6358 index_cond_expr);
6359 gsi_insert_before (&incr_gsi, index_condition, GSI_SAME_STMT);
6360 stmt_vec_info index_vec_info = new_stmt_vec_info (index_condition,
6361 loop_vinfo);
6362 STMT_VINFO_VECTYPE (index_vec_info) = cr_index_vector_type;
6363 set_vinfo_for_stmt (index_condition, index_vec_info);
6365 /* Update the phi with the vec cond. */
6366 add_phi_arg (new_phi, cond_name, loop_latch_edge (loop),
6367 UNKNOWN_LOCATION);
6371 vect_create_epilog_for_reduction (vect_defs, stmt, epilog_copies,
6372 epilog_reduc_code, phis, reduc_index,
6373 double_reduc, slp_node, cond_name);
6375 return true;
6378 /* Function vect_min_worthwhile_factor.
6380 For a loop where we could vectorize the operation indicated by CODE,
6381 return the minimum vectorization factor that makes it worthwhile
6382 to use generic vectors. */
6384 vect_min_worthwhile_factor (enum tree_code code)
6386 switch (code)
6388 case PLUS_EXPR:
6389 case MINUS_EXPR:
6390 case NEGATE_EXPR:
6391 return 4;
6393 case BIT_AND_EXPR:
6394 case BIT_IOR_EXPR:
6395 case BIT_XOR_EXPR:
6396 case BIT_NOT_EXPR:
6397 return 2;
6399 default:
6400 return INT_MAX;
6405 /* Function vectorizable_induction
6407 Check if PHI performs an induction computation that can be vectorized.
6408 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
6409 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
6410 Return FALSE if not a vectorizable STMT, TRUE otherwise. */
6412 bool
6413 vectorizable_induction (gimple *phi,
6414 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6415 gimple **vec_stmt)
6417 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
6418 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6419 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6420 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6421 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6422 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6423 tree vec_def;
6425 gcc_assert (ncopies >= 1);
6426 /* FORNOW. These restrictions should be relaxed. */
6427 if (nested_in_vect_loop_p (loop, phi))
6429 imm_use_iterator imm_iter;
6430 use_operand_p use_p;
6431 gimple *exit_phi;
6432 edge latch_e;
6433 tree loop_arg;
6435 if (ncopies > 1)
6437 if (dump_enabled_p ())
6438 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6439 "multiple types in nested loop.\n");
6440 return false;
6443 exit_phi = NULL;
6444 latch_e = loop_latch_edge (loop->inner);
6445 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
6446 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
6448 gimple *use_stmt = USE_STMT (use_p);
6449 if (is_gimple_debug (use_stmt))
6450 continue;
6452 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
6454 exit_phi = use_stmt;
6455 break;
6458 if (exit_phi)
6460 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
6461 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
6462 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
6464 if (dump_enabled_p ())
6465 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6466 "inner-loop induction only used outside "
6467 "of the outer vectorized loop.\n");
6468 return false;
6473 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6474 return false;
6476 /* FORNOW: SLP not supported. */
6477 if (STMT_SLP_TYPE (stmt_info))
6478 return false;
6480 gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def);
6482 if (gimple_code (phi) != GIMPLE_PHI)
6483 return false;
6485 if (!vec_stmt) /* transformation not required. */
6487 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
6488 if (dump_enabled_p ())
6489 dump_printf_loc (MSG_NOTE, vect_location,
6490 "=== vectorizable_induction ===\n");
6491 vect_model_induction_cost (stmt_info, ncopies);
6492 return true;
6495 /** Transform. **/
6497 if (dump_enabled_p ())
6498 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
6500 vec_def = get_initial_def_for_induction (phi);
6501 *vec_stmt = SSA_NAME_DEF_STMT (vec_def);
6502 return true;
6505 /* Function vectorizable_live_operation.
6507 STMT computes a value that is used outside the loop. Check if
6508 it can be supported. */
6510 bool
6511 vectorizable_live_operation (gimple *stmt,
6512 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6513 slp_tree slp_node, int slp_index,
6514 gimple **vec_stmt)
6516 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
6517 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6518 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6519 imm_use_iterator imm_iter;
6520 tree lhs, lhs_type, bitsize, vec_bitsize;
6521 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6522 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6523 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6524 gimple *use_stmt;
6525 auto_vec<tree> vec_oprnds;
6527 gcc_assert (STMT_VINFO_LIVE_P (stmt_info));
6529 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def)
6530 return false;
6532 /* FORNOW. CHECKME. */
6533 if (nested_in_vect_loop_p (loop, stmt))
6534 return false;
6536 /* If STMT is not relevant and it is a simple assignment and its inputs are
6537 invariant then it can remain in place, unvectorized. The original last
6538 scalar value that it computes will be used. */
6539 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6541 gcc_assert (is_simple_and_all_uses_invariant (stmt, loop_vinfo));
6542 if (dump_enabled_p ())
6543 dump_printf_loc (MSG_NOTE, vect_location,
6544 "statement is simple and uses invariant. Leaving in "
6545 "place.\n");
6546 return true;
6549 if (!vec_stmt)
6550 /* No transformation required. */
6551 return true;
6553 /* If stmt has a related stmt, then use that for getting the lhs. */
6554 if (is_pattern_stmt_p (stmt_info))
6555 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
6557 lhs = (is_a <gphi *> (stmt)) ? gimple_phi_result (stmt)
6558 : gimple_get_lhs (stmt);
6559 lhs_type = TREE_TYPE (lhs);
6561 bitsize = TYPE_SIZE (TREE_TYPE (vectype));
6562 vec_bitsize = TYPE_SIZE (vectype);
6564 /* Get the vectorized lhs of STMT and the lane to use (counted in bits). */
6565 tree vec_lhs, bitstart;
6566 if (slp_node)
6568 gcc_assert (slp_index >= 0);
6570 int num_scalar = SLP_TREE_SCALAR_STMTS (slp_node).length ();
6571 int num_vec = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6573 /* Get the last occurrence of the scalar index from the concatenation of
6574 all the slp vectors. Calculate which slp vector it is and the index
6575 within. */
6576 int pos = (num_vec * nunits) - num_scalar + slp_index;
6577 int vec_entry = pos / nunits;
6578 int vec_index = pos % nunits;
6580 /* Get the correct slp vectorized stmt. */
6581 vec_lhs = gimple_get_lhs (SLP_TREE_VEC_STMTS (slp_node)[vec_entry]);
6583 /* Get entry to use. */
6584 bitstart = build_int_cst (unsigned_type_node, vec_index);
6585 bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
6587 else
6589 enum vect_def_type dt = STMT_VINFO_DEF_TYPE (stmt_info);
6590 vec_lhs = vect_get_vec_def_for_operand_1 (stmt, dt);
6592 /* For multiple copies, get the last copy. */
6593 for (int i = 1; i < ncopies; ++i)
6594 vec_lhs = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type,
6595 vec_lhs);
6597 /* Get the last lane in the vector. */
6598 bitstart = int_const_binop (MINUS_EXPR, vec_bitsize, bitsize);
6601 /* Create a new vectorized stmt for the uses of STMT and insert outside the
6602 loop. */
6603 gimple_seq stmts = NULL;
6604 tree new_tree = build3 (BIT_FIELD_REF, TREE_TYPE (vectype), vec_lhs, bitsize,
6605 bitstart);
6606 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree), &stmts,
6607 true, NULL_TREE);
6608 if (stmts)
6609 gsi_insert_seq_on_edge_immediate (single_exit (loop), stmts);
6611 /* Replace use of lhs with newly computed result. If the use stmt is a
6612 single arg PHI, just replace all uses of PHI result. It's necessary
6613 because lcssa PHI defining lhs may be before newly inserted stmt. */
6614 use_operand_p use_p;
6615 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
6616 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt))
6617 && !is_gimple_debug (use_stmt))
6619 if (gimple_code (use_stmt) == GIMPLE_PHI
6620 && gimple_phi_num_args (use_stmt) == 1)
6622 replace_uses_by (gimple_phi_result (use_stmt), new_tree);
6624 else
6626 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
6627 SET_USE (use_p, new_tree);
6629 update_stmt (use_stmt);
6632 return true;
6635 /* Kill any debug uses outside LOOP of SSA names defined in STMT. */
6637 static void
6638 vect_loop_kill_debug_uses (struct loop *loop, gimple *stmt)
6640 ssa_op_iter op_iter;
6641 imm_use_iterator imm_iter;
6642 def_operand_p def_p;
6643 gimple *ustmt;
6645 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt, op_iter, SSA_OP_DEF)
6647 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
6649 basic_block bb;
6651 if (!is_gimple_debug (ustmt))
6652 continue;
6654 bb = gimple_bb (ustmt);
6656 if (!flow_bb_inside_loop_p (loop, bb))
6658 if (gimple_debug_bind_p (ustmt))
6660 if (dump_enabled_p ())
6661 dump_printf_loc (MSG_NOTE, vect_location,
6662 "killing debug use\n");
6664 gimple_debug_bind_reset_value (ustmt);
6665 update_stmt (ustmt);
6667 else
6668 gcc_unreachable ();
6674 /* Given loop represented by LOOP_VINFO, return true if computation of
6675 LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
6676 otherwise. */
6678 static bool
6679 loop_niters_no_overflow (loop_vec_info loop_vinfo)
6681 /* Constant case. */
6682 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6684 tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
6685 tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
6687 gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
6688 gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
6689 if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
6690 return true;
6693 widest_int max;
6694 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6695 /* Check the upper bound of loop niters. */
6696 if (get_max_loop_iterations (loop, &max))
6698 tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
6699 signop sgn = TYPE_SIGN (type);
6700 widest_int type_max = widest_int::from (wi::max_value (type), sgn);
6701 if (max < type_max)
6702 return true;
6704 return false;
6707 /* Function vect_transform_loop.
6709 The analysis phase has determined that the loop is vectorizable.
6710 Vectorize the loop - created vectorized stmts to replace the scalar
6711 stmts in the loop, and update the loop exit condition.
6712 Returns scalar epilogue loop if any. */
6714 struct loop *
6715 vect_transform_loop (loop_vec_info loop_vinfo)
6717 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6718 struct loop *epilogue = NULL;
6719 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
6720 int nbbs = loop->num_nodes;
6721 int i;
6722 tree niters_vector = NULL;
6723 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6724 bool grouped_store;
6725 bool slp_scheduled = false;
6726 gimple *stmt, *pattern_stmt;
6727 gimple_seq pattern_def_seq = NULL;
6728 gimple_stmt_iterator pattern_def_si = gsi_none ();
6729 bool transform_pattern_stmt = false;
6730 bool check_profitability = false;
6731 int th;
6732 /* Record number of iterations before we started tampering with the profile. */
6733 gcov_type expected_iterations = expected_loop_iterations_unbounded (loop);
6735 if (dump_enabled_p ())
6736 dump_printf_loc (MSG_NOTE, vect_location, "=== vec_transform_loop ===\n");
6738 /* If profile is inprecise, we have chance to fix it up. */
6739 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6740 expected_iterations = LOOP_VINFO_INT_NITERS (loop_vinfo);
6742 /* Use the more conservative vectorization threshold. If the number
6743 of iterations is constant assume the cost check has been performed
6744 by our caller. If the threshold makes all loops profitable that
6745 run at least the vectorization factor number of times checking
6746 is pointless, too. */
6747 th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
6748 if (th >= LOOP_VINFO_VECT_FACTOR (loop_vinfo) - 1
6749 && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6751 if (dump_enabled_p ())
6752 dump_printf_loc (MSG_NOTE, vect_location,
6753 "Profitability threshold is %d loop iterations.\n",
6754 th);
6755 check_profitability = true;
6758 /* Make sure there exists a single-predecessor exit bb. Do this before
6759 versioning. */
6760 edge e = single_exit (loop);
6761 if (! single_pred_p (e->dest))
6763 split_loop_exit_edge (e);
6764 if (dump_enabled_p ())
6765 dump_printf (MSG_NOTE, "split exit edge\n");
6768 /* Version the loop first, if required, so the profitability check
6769 comes first. */
6771 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
6773 vect_loop_versioning (loop_vinfo, th, check_profitability);
6774 check_profitability = false;
6777 /* Make sure there exists a single-predecessor exit bb also on the
6778 scalar loop copy. Do this after versioning but before peeling
6779 so CFG structure is fine for both scalar and if-converted loop
6780 to make slpeel_duplicate_current_defs_from_edges face matched
6781 loop closed PHI nodes on the exit. */
6782 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
6784 e = single_exit (LOOP_VINFO_SCALAR_LOOP (loop_vinfo));
6785 if (! single_pred_p (e->dest))
6787 split_loop_exit_edge (e);
6788 if (dump_enabled_p ())
6789 dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
6793 tree niters = vect_build_loop_niters (loop_vinfo);
6794 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
6795 tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
6796 bool niters_no_overflow = loop_niters_no_overflow (loop_vinfo);
6797 epilogue = vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector, th,
6798 check_profitability, niters_no_overflow);
6799 if (niters_vector == NULL_TREE)
6801 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6802 niters_vector
6803 = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
6804 LOOP_VINFO_INT_NITERS (loop_vinfo) / vf);
6805 else
6806 vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
6807 niters_no_overflow);
6810 /* 1) Make sure the loop header has exactly two entries
6811 2) Make sure we have a preheader basic block. */
6813 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
6815 split_edge (loop_preheader_edge (loop));
6817 /* FORNOW: the vectorizer supports only loops which body consist
6818 of one basic block (header + empty latch). When the vectorizer will
6819 support more involved loop forms, the order by which the BBs are
6820 traversed need to be reconsidered. */
6822 for (i = 0; i < nbbs; i++)
6824 basic_block bb = bbs[i];
6825 stmt_vec_info stmt_info;
6827 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6828 gsi_next (&si))
6830 gphi *phi = si.phi ();
6831 if (dump_enabled_p ())
6833 dump_printf_loc (MSG_NOTE, vect_location,
6834 "------>vectorizing phi: ");
6835 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
6837 stmt_info = vinfo_for_stmt (phi);
6838 if (!stmt_info)
6839 continue;
6841 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6842 vect_loop_kill_debug_uses (loop, phi);
6844 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6845 && !STMT_VINFO_LIVE_P (stmt_info))
6846 continue;
6848 if (STMT_VINFO_VECTYPE (stmt_info)
6849 && (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info))
6850 != (unsigned HOST_WIDE_INT) vf)
6851 && dump_enabled_p ())
6852 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6854 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
6856 if (dump_enabled_p ())
6857 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
6858 vect_transform_stmt (phi, NULL, NULL, NULL, NULL);
6862 pattern_stmt = NULL;
6863 for (gimple_stmt_iterator si = gsi_start_bb (bb);
6864 !gsi_end_p (si) || transform_pattern_stmt;)
6866 bool is_store;
6868 if (transform_pattern_stmt)
6869 stmt = pattern_stmt;
6870 else
6872 stmt = gsi_stmt (si);
6873 /* During vectorization remove existing clobber stmts. */
6874 if (gimple_clobber_p (stmt))
6876 unlink_stmt_vdef (stmt);
6877 gsi_remove (&si, true);
6878 release_defs (stmt);
6879 continue;
6883 if (dump_enabled_p ())
6885 dump_printf_loc (MSG_NOTE, vect_location,
6886 "------>vectorizing statement: ");
6887 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
6890 stmt_info = vinfo_for_stmt (stmt);
6892 /* vector stmts created in the outer-loop during vectorization of
6893 stmts in an inner-loop may not have a stmt_info, and do not
6894 need to be vectorized. */
6895 if (!stmt_info)
6897 gsi_next (&si);
6898 continue;
6901 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6902 vect_loop_kill_debug_uses (loop, stmt);
6904 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6905 && !STMT_VINFO_LIVE_P (stmt_info))
6907 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6908 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6909 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6910 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6912 stmt = pattern_stmt;
6913 stmt_info = vinfo_for_stmt (stmt);
6915 else
6917 gsi_next (&si);
6918 continue;
6921 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6922 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6923 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6924 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6925 transform_pattern_stmt = true;
6927 /* If pattern statement has def stmts, vectorize them too. */
6928 if (is_pattern_stmt_p (stmt_info))
6930 if (pattern_def_seq == NULL)
6932 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
6933 pattern_def_si = gsi_start (pattern_def_seq);
6935 else if (!gsi_end_p (pattern_def_si))
6936 gsi_next (&pattern_def_si);
6937 if (pattern_def_seq != NULL)
6939 gimple *pattern_def_stmt = NULL;
6940 stmt_vec_info pattern_def_stmt_info = NULL;
6942 while (!gsi_end_p (pattern_def_si))
6944 pattern_def_stmt = gsi_stmt (pattern_def_si);
6945 pattern_def_stmt_info
6946 = vinfo_for_stmt (pattern_def_stmt);
6947 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
6948 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
6949 break;
6950 gsi_next (&pattern_def_si);
6953 if (!gsi_end_p (pattern_def_si))
6955 if (dump_enabled_p ())
6957 dump_printf_loc (MSG_NOTE, vect_location,
6958 "==> vectorizing pattern def "
6959 "stmt: ");
6960 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
6961 pattern_def_stmt, 0);
6964 stmt = pattern_def_stmt;
6965 stmt_info = pattern_def_stmt_info;
6967 else
6969 pattern_def_si = gsi_none ();
6970 transform_pattern_stmt = false;
6973 else
6974 transform_pattern_stmt = false;
6977 if (STMT_VINFO_VECTYPE (stmt_info))
6979 unsigned int nunits
6980 = (unsigned int)
6981 TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
6982 if (!STMT_SLP_TYPE (stmt_info)
6983 && nunits != (unsigned int) vf
6984 && dump_enabled_p ())
6985 /* For SLP VF is set according to unrolling factor, and not
6986 to vector size, hence for SLP this print is not valid. */
6987 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6990 /* SLP. Schedule all the SLP instances when the first SLP stmt is
6991 reached. */
6992 if (STMT_SLP_TYPE (stmt_info))
6994 if (!slp_scheduled)
6996 slp_scheduled = true;
6998 if (dump_enabled_p ())
6999 dump_printf_loc (MSG_NOTE, vect_location,
7000 "=== scheduling SLP instances ===\n");
7002 vect_schedule_slp (loop_vinfo);
7005 /* Hybrid SLP stmts must be vectorized in addition to SLP. */
7006 if (!vinfo_for_stmt (stmt) || PURE_SLP_STMT (stmt_info))
7008 if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7010 pattern_def_seq = NULL;
7011 gsi_next (&si);
7013 continue;
7017 /* -------- vectorize statement ------------ */
7018 if (dump_enabled_p ())
7019 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
7021 grouped_store = false;
7022 is_store = vect_transform_stmt (stmt, &si, &grouped_store, NULL, NULL);
7023 if (is_store)
7025 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
7027 /* Interleaving. If IS_STORE is TRUE, the vectorization of the
7028 interleaving chain was completed - free all the stores in
7029 the chain. */
7030 gsi_next (&si);
7031 vect_remove_stores (GROUP_FIRST_ELEMENT (stmt_info));
7033 else
7035 /* Free the attached stmt_vec_info and remove the stmt. */
7036 gimple *store = gsi_stmt (si);
7037 free_stmt_vec_info (store);
7038 unlink_stmt_vdef (store);
7039 gsi_remove (&si, true);
7040 release_defs (store);
7043 /* Stores can only appear at the end of pattern statements. */
7044 gcc_assert (!transform_pattern_stmt);
7045 pattern_def_seq = NULL;
7047 else if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7049 pattern_def_seq = NULL;
7050 gsi_next (&si);
7052 } /* stmts in BB */
7053 } /* BBs in loop */
7055 slpeel_make_loop_iterate_ntimes (loop, niters_vector);
7057 /* Reduce loop iterations by the vectorization factor. */
7058 scale_loop_profile (loop, GCOV_COMPUTE_SCALE (1, vf),
7059 expected_iterations / vf);
7060 /* The minimum number of iterations performed by the epilogue. This
7061 is 1 when peeling for gaps because we always need a final scalar
7062 iteration. */
7063 int min_epilogue_iters = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
7064 /* +1 to convert latch counts to loop iteration counts,
7065 -min_epilogue_iters to remove iterations that cannot be performed
7066 by the vector code. */
7067 int bias = 1 - min_epilogue_iters;
7068 /* In these calculations the "- 1" converts loop iteration counts
7069 back to latch counts. */
7070 if (loop->any_upper_bound)
7071 loop->nb_iterations_upper_bound
7072 = wi::udiv_floor (loop->nb_iterations_upper_bound + bias, vf) - 1;
7073 if (loop->any_likely_upper_bound)
7074 loop->nb_iterations_likely_upper_bound
7075 = wi::udiv_floor (loop->nb_iterations_likely_upper_bound + bias, vf) - 1;
7076 if (loop->any_estimate)
7077 loop->nb_iterations_estimate
7078 = wi::udiv_floor (loop->nb_iterations_estimate + bias, vf) - 1;
7080 if (dump_enabled_p ())
7082 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
7084 dump_printf_loc (MSG_NOTE, vect_location,
7085 "LOOP VECTORIZED\n");
7086 if (loop->inner)
7087 dump_printf_loc (MSG_NOTE, vect_location,
7088 "OUTER LOOP VECTORIZED\n");
7089 dump_printf (MSG_NOTE, "\n");
7091 else
7092 dump_printf_loc (MSG_NOTE, vect_location,
7093 "LOOP EPILOGUE VECTORIZED (VS=%d)\n",
7094 current_vector_size);
7097 /* Free SLP instances here because otherwise stmt reference counting
7098 won't work. */
7099 slp_instance instance;
7100 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
7101 vect_free_slp_instance (instance);
7102 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
7103 /* Clear-up safelen field since its value is invalid after vectorization
7104 since vectorized loop can have loop-carried dependencies. */
7105 loop->safelen = 0;
7107 /* Don't vectorize epilogue for epilogue. */
7108 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
7109 epilogue = NULL;
7111 if (epilogue)
7113 unsigned int vector_sizes
7114 = targetm.vectorize.autovectorize_vector_sizes ();
7115 vector_sizes &= current_vector_size - 1;
7117 if (!PARAM_VALUE (PARAM_VECT_EPILOGUES_NOMASK))
7118 epilogue = NULL;
7119 else if (!vector_sizes)
7120 epilogue = NULL;
7121 else if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
7122 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) >= 0)
7124 int smallest_vec_size = 1 << ctz_hwi (vector_sizes);
7125 int ratio = current_vector_size / smallest_vec_size;
7126 int eiters = LOOP_VINFO_INT_NITERS (loop_vinfo)
7127 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
7128 eiters = eiters % vf;
7130 epilogue->nb_iterations_upper_bound = eiters - 1;
7132 if (eiters < vf / ratio)
7133 epilogue = NULL;
7137 if (epilogue)
7139 epilogue->force_vectorize = loop->force_vectorize;
7140 epilogue->safelen = loop->safelen;
7141 epilogue->dont_vectorize = false;
7143 /* We may need to if-convert epilogue to vectorize it. */
7144 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
7145 tree_if_conversion (epilogue);
7148 return epilogue;
7151 /* The code below is trying to perform simple optimization - revert
7152 if-conversion for masked stores, i.e. if the mask of a store is zero
7153 do not perform it and all stored value producers also if possible.
7154 For example,
7155 for (i=0; i<n; i++)
7156 if (c[i])
7158 p1[i] += 1;
7159 p2[i] = p3[i] +2;
7161 this transformation will produce the following semi-hammock:
7163 if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
7165 vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
7166 vect__12.22_172 = vect__11.19_170 + vect_cst__171;
7167 MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
7168 vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
7169 vect__19.28_184 = vect__18.25_182 + vect_cst__183;
7170 MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
7174 void
7175 optimize_mask_stores (struct loop *loop)
7177 basic_block *bbs = get_loop_body (loop);
7178 unsigned nbbs = loop->num_nodes;
7179 unsigned i;
7180 basic_block bb;
7181 gimple_stmt_iterator gsi;
7182 gimple *stmt;
7183 auto_vec<gimple *> worklist;
7185 vect_location = find_loop_location (loop);
7186 /* Pick up all masked stores in loop if any. */
7187 for (i = 0; i < nbbs; i++)
7189 bb = bbs[i];
7190 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7191 gsi_next (&gsi))
7193 stmt = gsi_stmt (gsi);
7194 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
7195 worklist.safe_push (stmt);
7199 free (bbs);
7200 if (worklist.is_empty ())
7201 return;
7203 /* Loop has masked stores. */
7204 while (!worklist.is_empty ())
7206 gimple *last, *last_store;
7207 edge e, efalse;
7208 tree mask;
7209 basic_block store_bb, join_bb;
7210 gimple_stmt_iterator gsi_to;
7211 tree vdef, new_vdef;
7212 gphi *phi;
7213 tree vectype;
7214 tree zero;
7216 last = worklist.pop ();
7217 mask = gimple_call_arg (last, 2);
7218 bb = gimple_bb (last);
7219 /* Create new bb. */
7220 e = split_block (bb, last);
7221 join_bb = e->dest;
7222 store_bb = create_empty_bb (bb);
7223 add_bb_to_loop (store_bb, loop);
7224 e->flags = EDGE_TRUE_VALUE;
7225 efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
7226 /* Put STORE_BB to likely part. */
7227 efalse->probability = PROB_UNLIKELY;
7228 store_bb->frequency = PROB_ALWAYS - EDGE_FREQUENCY (efalse);
7229 make_edge (store_bb, join_bb, EDGE_FALLTHRU);
7230 if (dom_info_available_p (CDI_DOMINATORS))
7231 set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
7232 if (dump_enabled_p ())
7233 dump_printf_loc (MSG_NOTE, vect_location,
7234 "Create new block %d to sink mask stores.",
7235 store_bb->index);
7236 /* Create vector comparison with boolean result. */
7237 vectype = TREE_TYPE (mask);
7238 zero = build_zero_cst (vectype);
7239 stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
7240 gsi = gsi_last_bb (bb);
7241 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
7242 /* Create new PHI node for vdef of the last masked store:
7243 .MEM_2 = VDEF <.MEM_1>
7244 will be converted to
7245 .MEM.3 = VDEF <.MEM_1>
7246 and new PHI node will be created in join bb
7247 .MEM_2 = PHI <.MEM_1, .MEM_3>
7249 vdef = gimple_vdef (last);
7250 new_vdef = make_ssa_name (gimple_vop (cfun), last);
7251 gimple_set_vdef (last, new_vdef);
7252 phi = create_phi_node (vdef, join_bb);
7253 add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
7255 /* Put all masked stores with the same mask to STORE_BB if possible. */
7256 while (true)
7258 gimple_stmt_iterator gsi_from;
7259 gimple *stmt1 = NULL;
7261 /* Move masked store to STORE_BB. */
7262 last_store = last;
7263 gsi = gsi_for_stmt (last);
7264 gsi_from = gsi;
7265 /* Shift GSI to the previous stmt for further traversal. */
7266 gsi_prev (&gsi);
7267 gsi_to = gsi_start_bb (store_bb);
7268 gsi_move_before (&gsi_from, &gsi_to);
7269 /* Setup GSI_TO to the non-empty block start. */
7270 gsi_to = gsi_start_bb (store_bb);
7271 if (dump_enabled_p ())
7273 dump_printf_loc (MSG_NOTE, vect_location,
7274 "Move stmt to created bb\n");
7275 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, last, 0);
7277 /* Move all stored value producers if possible. */
7278 while (!gsi_end_p (gsi))
7280 tree lhs;
7281 imm_use_iterator imm_iter;
7282 use_operand_p use_p;
7283 bool res;
7285 /* Skip debug statements. */
7286 if (is_gimple_debug (gsi_stmt (gsi)))
7288 gsi_prev (&gsi);
7289 continue;
7291 stmt1 = gsi_stmt (gsi);
7292 /* Do not consider statements writing to memory or having
7293 volatile operand. */
7294 if (gimple_vdef (stmt1)
7295 || gimple_has_volatile_ops (stmt1))
7296 break;
7297 gsi_from = gsi;
7298 gsi_prev (&gsi);
7299 lhs = gimple_get_lhs (stmt1);
7300 if (!lhs)
7301 break;
7303 /* LHS of vectorized stmt must be SSA_NAME. */
7304 if (TREE_CODE (lhs) != SSA_NAME)
7305 break;
7307 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
7309 /* Remove dead scalar statement. */
7310 if (has_zero_uses (lhs))
7312 gsi_remove (&gsi_from, true);
7313 continue;
7317 /* Check that LHS does not have uses outside of STORE_BB. */
7318 res = true;
7319 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
7321 gimple *use_stmt;
7322 use_stmt = USE_STMT (use_p);
7323 if (is_gimple_debug (use_stmt))
7324 continue;
7325 if (gimple_bb (use_stmt) != store_bb)
7327 res = false;
7328 break;
7331 if (!res)
7332 break;
7334 if (gimple_vuse (stmt1)
7335 && gimple_vuse (stmt1) != gimple_vuse (last_store))
7336 break;
7338 /* Can move STMT1 to STORE_BB. */
7339 if (dump_enabled_p ())
7341 dump_printf_loc (MSG_NOTE, vect_location,
7342 "Move stmt to created bb\n");
7343 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt1, 0);
7345 gsi_move_before (&gsi_from, &gsi_to);
7346 /* Shift GSI_TO for further insertion. */
7347 gsi_prev (&gsi_to);
7349 /* Put other masked stores with the same mask to STORE_BB. */
7350 if (worklist.is_empty ()
7351 || gimple_call_arg (worklist.last (), 2) != mask
7352 || worklist.last () != stmt1)
7353 break;
7354 last = worklist.pop ();
7356 add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);