[AArch64] Fix ICEs in aarch64_print_operand
[official-gcc.git] / gcc / tree-vect-loop.c
blob1759655fd0728bdb6faf99b9be3a362df260da32
1 /* Loop Vectorization
2 Copyright (C) 2003-2017 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"
53 #include "internal-fn.h"
54 #include "tree-vector-builder.h"
56 /* Loop Vectorization Pass.
58 This pass tries to vectorize loops.
60 For example, the vectorizer transforms the following simple loop:
62 short a[N]; short b[N]; short c[N]; int i;
64 for (i=0; i<N; i++){
65 a[i] = b[i] + c[i];
68 as if it was manually vectorized by rewriting the source code into:
70 typedef int __attribute__((mode(V8HI))) v8hi;
71 short a[N]; short b[N]; short c[N]; int i;
72 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
73 v8hi va, vb, vc;
75 for (i=0; i<N/8; i++){
76 vb = pb[i];
77 vc = pc[i];
78 va = vb + vc;
79 pa[i] = va;
82 The main entry to this pass is vectorize_loops(), in which
83 the vectorizer applies a set of analyses on a given set of loops,
84 followed by the actual vectorization transformation for the loops that
85 had successfully passed the analysis phase.
86 Throughout this pass we make a distinction between two types of
87 data: scalars (which are represented by SSA_NAMES), and memory references
88 ("data-refs"). These two types of data require different handling both
89 during analysis and transformation. The types of data-refs that the
90 vectorizer currently supports are ARRAY_REFS which base is an array DECL
91 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
92 accesses are required to have a simple (consecutive) access pattern.
94 Analysis phase:
95 ===============
96 The driver for the analysis phase is vect_analyze_loop().
97 It applies a set of analyses, some of which rely on the scalar evolution
98 analyzer (scev) developed by Sebastian Pop.
100 During the analysis phase the vectorizer records some information
101 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
102 loop, as well as general information about the loop as a whole, which is
103 recorded in a "loop_vec_info" struct attached to each loop.
105 Transformation phase:
106 =====================
107 The loop transformation phase scans all the stmts in the loop, and
108 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
109 the loop that needs to be vectorized. It inserts the vector code sequence
110 just before the scalar stmt S, and records a pointer to the vector code
111 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
112 attached to S). This pointer will be used for the vectorization of following
113 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
114 otherwise, we rely on dead code elimination for removing it.
116 For example, say stmt S1 was vectorized into stmt VS1:
118 VS1: vb = px[i];
119 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
120 S2: a = b;
122 To vectorize stmt S2, the vectorizer first finds the stmt that defines
123 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
124 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
125 resulting sequence would be:
127 VS1: vb = px[i];
128 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
129 VS2: va = vb;
130 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
132 Operands that are not SSA_NAMEs, are data-refs that appear in
133 load/store operations (like 'x[i]' in S1), and are handled differently.
135 Target modeling:
136 =================
137 Currently the only target specific information that is used is the
138 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
139 Targets that can support different sizes of vectors, for now will need
140 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
141 flexibility will be added in the future.
143 Since we only vectorize operations which vector form can be
144 expressed using existing tree codes, to verify that an operation is
145 supported, the vectorizer checks the relevant optab at the relevant
146 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
147 the value found is CODE_FOR_nothing, then there's no target support, and
148 we can't vectorize the stmt.
150 For additional information on this project see:
151 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
154 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *);
156 /* Function vect_determine_vectorization_factor
158 Determine the vectorization factor (VF). VF is the number of data elements
159 that are operated upon in parallel in a single iteration of the vectorized
160 loop. For example, when vectorizing a loop that operates on 4byte elements,
161 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
162 elements can fit in a single vector register.
164 We currently support vectorization of loops in which all types operated upon
165 are of the same size. Therefore this function currently sets VF according to
166 the size of the types operated upon, and fails if there are multiple sizes
167 in the loop.
169 VF is also the factor by which the loop iterations are strip-mined, e.g.:
170 original loop:
171 for (i=0; i<N; i++){
172 a[i] = b[i] + c[i];
175 vectorized loop:
176 for (i=0; i<N; i+=VF){
177 a[i:VF] = b[i:VF] + c[i:VF];
181 static bool
182 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
184 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
185 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
186 unsigned nbbs = loop->num_nodes;
187 unsigned int vectorization_factor = 0;
188 tree scalar_type = NULL_TREE;
189 gphi *phi;
190 tree vectype;
191 unsigned int nunits;
192 stmt_vec_info stmt_info;
193 unsigned i;
194 HOST_WIDE_INT dummy;
195 gimple *stmt, *pattern_stmt = NULL;
196 gimple_seq pattern_def_seq = NULL;
197 gimple_stmt_iterator pattern_def_si = gsi_none ();
198 bool analyze_pattern_stmt = false;
199 bool bool_result;
200 auto_vec<stmt_vec_info> mask_producers;
202 if (dump_enabled_p ())
203 dump_printf_loc (MSG_NOTE, vect_location,
204 "=== vect_determine_vectorization_factor ===\n");
206 for (i = 0; i < nbbs; i++)
208 basic_block bb = bbs[i];
210 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
211 gsi_next (&si))
213 phi = si.phi ();
214 stmt_info = vinfo_for_stmt (phi);
215 if (dump_enabled_p ())
217 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: ");
218 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
221 gcc_assert (stmt_info);
223 if (STMT_VINFO_RELEVANT_P (stmt_info)
224 || STMT_VINFO_LIVE_P (stmt_info))
226 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
227 scalar_type = TREE_TYPE (PHI_RESULT (phi));
229 if (dump_enabled_p ())
231 dump_printf_loc (MSG_NOTE, vect_location,
232 "get vectype for scalar type: ");
233 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
234 dump_printf (MSG_NOTE, "\n");
237 vectype = get_vectype_for_scalar_type (scalar_type);
238 if (!vectype)
240 if (dump_enabled_p ())
242 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
243 "not vectorized: unsupported "
244 "data-type ");
245 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
246 scalar_type);
247 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
249 return false;
251 STMT_VINFO_VECTYPE (stmt_info) = vectype;
253 if (dump_enabled_p ())
255 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
256 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
257 dump_printf (MSG_NOTE, "\n");
260 nunits = TYPE_VECTOR_SUBPARTS (vectype);
261 if (dump_enabled_p ())
262 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n",
263 nunits);
265 if (!vectorization_factor
266 || (nunits > vectorization_factor))
267 vectorization_factor = nunits;
271 for (gimple_stmt_iterator si = gsi_start_bb (bb);
272 !gsi_end_p (si) || analyze_pattern_stmt;)
274 tree vf_vectype;
276 if (analyze_pattern_stmt)
277 stmt = pattern_stmt;
278 else
279 stmt = gsi_stmt (si);
281 stmt_info = vinfo_for_stmt (stmt);
283 if (dump_enabled_p ())
285 dump_printf_loc (MSG_NOTE, vect_location,
286 "==> examining statement: ");
287 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
290 gcc_assert (stmt_info);
292 /* Skip stmts which do not need to be vectorized. */
293 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
294 && !STMT_VINFO_LIVE_P (stmt_info))
295 || gimple_clobber_p (stmt))
297 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
298 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
299 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
300 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
302 stmt = pattern_stmt;
303 stmt_info = vinfo_for_stmt (pattern_stmt);
304 if (dump_enabled_p ())
306 dump_printf_loc (MSG_NOTE, vect_location,
307 "==> examining pattern statement: ");
308 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
311 else
313 if (dump_enabled_p ())
314 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
315 gsi_next (&si);
316 continue;
319 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
320 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
321 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
322 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
323 analyze_pattern_stmt = true;
325 /* If a pattern statement has def stmts, analyze them too. */
326 if (is_pattern_stmt_p (stmt_info))
328 if (pattern_def_seq == NULL)
330 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
331 pattern_def_si = gsi_start (pattern_def_seq);
333 else if (!gsi_end_p (pattern_def_si))
334 gsi_next (&pattern_def_si);
335 if (pattern_def_seq != NULL)
337 gimple *pattern_def_stmt = NULL;
338 stmt_vec_info pattern_def_stmt_info = NULL;
340 while (!gsi_end_p (pattern_def_si))
342 pattern_def_stmt = gsi_stmt (pattern_def_si);
343 pattern_def_stmt_info
344 = vinfo_for_stmt (pattern_def_stmt);
345 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
346 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
347 break;
348 gsi_next (&pattern_def_si);
351 if (!gsi_end_p (pattern_def_si))
353 if (dump_enabled_p ())
355 dump_printf_loc (MSG_NOTE, vect_location,
356 "==> examining pattern def stmt: ");
357 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
358 pattern_def_stmt, 0);
361 stmt = pattern_def_stmt;
362 stmt_info = pattern_def_stmt_info;
364 else
366 pattern_def_si = gsi_none ();
367 analyze_pattern_stmt = false;
370 else
371 analyze_pattern_stmt = false;
374 if (gimple_get_lhs (stmt) == NULL_TREE
375 /* MASK_STORE has no lhs, but is ok. */
376 && (!is_gimple_call (stmt)
377 || !gimple_call_internal_p (stmt)
378 || gimple_call_internal_fn (stmt) != IFN_MASK_STORE))
380 if (is_gimple_call (stmt))
382 /* Ignore calls with no lhs. These must be calls to
383 #pragma omp simd functions, and what vectorization factor
384 it really needs can't be determined until
385 vectorizable_simd_clone_call. */
386 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
388 pattern_def_seq = NULL;
389 gsi_next (&si);
391 continue;
393 if (dump_enabled_p ())
395 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
396 "not vectorized: irregular stmt.");
397 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
400 return false;
403 if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
405 if (dump_enabled_p ())
407 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
408 "not vectorized: vector stmt in loop:");
409 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
411 return false;
414 bool_result = false;
416 if (STMT_VINFO_VECTYPE (stmt_info))
418 /* The only case when a vectype had been already set is for stmts
419 that contain a dataref, or for "pattern-stmts" (stmts
420 generated by the vectorizer to represent/replace a certain
421 idiom). */
422 gcc_assert (STMT_VINFO_DATA_REF (stmt_info)
423 || is_pattern_stmt_p (stmt_info)
424 || !gsi_end_p (pattern_def_si));
425 vectype = STMT_VINFO_VECTYPE (stmt_info);
427 else
429 gcc_assert (!STMT_VINFO_DATA_REF (stmt_info));
430 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
431 scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
432 else
433 scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
435 /* Bool ops don't participate in vectorization factor
436 computation. For comparison use compared types to
437 compute a factor. */
438 if (VECT_SCALAR_BOOLEAN_TYPE_P (scalar_type)
439 && is_gimple_assign (stmt)
440 && gimple_assign_rhs_code (stmt) != COND_EXPR)
442 if (STMT_VINFO_RELEVANT_P (stmt_info)
443 || STMT_VINFO_LIVE_P (stmt_info))
444 mask_producers.safe_push (stmt_info);
445 bool_result = true;
447 if (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
448 == tcc_comparison
449 && !VECT_SCALAR_BOOLEAN_TYPE_P
450 (TREE_TYPE (gimple_assign_rhs1 (stmt))))
451 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
452 else
454 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
456 pattern_def_seq = NULL;
457 gsi_next (&si);
459 continue;
463 if (dump_enabled_p ())
465 dump_printf_loc (MSG_NOTE, vect_location,
466 "get vectype for scalar type: ");
467 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
468 dump_printf (MSG_NOTE, "\n");
470 vectype = get_vectype_for_scalar_type (scalar_type);
471 if (!vectype)
473 if (dump_enabled_p ())
475 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
476 "not vectorized: unsupported "
477 "data-type ");
478 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
479 scalar_type);
480 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
482 return false;
485 if (!bool_result)
486 STMT_VINFO_VECTYPE (stmt_info) = vectype;
488 if (dump_enabled_p ())
490 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
491 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
492 dump_printf (MSG_NOTE, "\n");
496 /* Don't try to compute VF out scalar types if we stmt
497 produces boolean vector. Use result vectype instead. */
498 if (VECTOR_BOOLEAN_TYPE_P (vectype))
499 vf_vectype = vectype;
500 else
502 /* The vectorization factor is according to the smallest
503 scalar type (or the largest vector size, but we only
504 support one vector size per loop). */
505 if (!bool_result)
506 scalar_type = vect_get_smallest_scalar_type (stmt, &dummy,
507 &dummy);
508 if (dump_enabled_p ())
510 dump_printf_loc (MSG_NOTE, vect_location,
511 "get vectype for scalar type: ");
512 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
513 dump_printf (MSG_NOTE, "\n");
515 vf_vectype = get_vectype_for_scalar_type (scalar_type);
517 if (!vf_vectype)
519 if (dump_enabled_p ())
521 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
522 "not vectorized: unsupported data-type ");
523 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
524 scalar_type);
525 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
527 return false;
530 if ((GET_MODE_SIZE (TYPE_MODE (vectype))
531 != GET_MODE_SIZE (TYPE_MODE (vf_vectype))))
533 if (dump_enabled_p ())
535 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
536 "not vectorized: different sized vector "
537 "types in statement, ");
538 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
539 vectype);
540 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
541 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
542 vf_vectype);
543 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
545 return false;
548 if (dump_enabled_p ())
550 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
551 dump_generic_expr (MSG_NOTE, TDF_SLIM, vf_vectype);
552 dump_printf (MSG_NOTE, "\n");
555 nunits = TYPE_VECTOR_SUBPARTS (vf_vectype);
556 if (dump_enabled_p ())
557 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n", nunits);
558 if (!vectorization_factor
559 || (nunits > vectorization_factor))
560 vectorization_factor = nunits;
562 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
564 pattern_def_seq = NULL;
565 gsi_next (&si);
570 /* TODO: Analyze cost. Decide if worth while to vectorize. */
571 if (dump_enabled_p ())
572 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = %d\n",
573 vectorization_factor);
574 if (vectorization_factor <= 1)
576 if (dump_enabled_p ())
577 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
578 "not vectorized: unsupported data-type\n");
579 return false;
581 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
583 for (i = 0; i < mask_producers.length (); i++)
585 tree mask_type = NULL;
587 stmt = STMT_VINFO_STMT (mask_producers[i]);
589 if (is_gimple_assign (stmt)
590 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison
591 && !VECT_SCALAR_BOOLEAN_TYPE_P
592 (TREE_TYPE (gimple_assign_rhs1 (stmt))))
594 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
595 mask_type = get_mask_type_for_scalar_type (scalar_type);
597 if (!mask_type)
599 if (dump_enabled_p ())
600 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
601 "not vectorized: unsupported mask\n");
602 return false;
605 else
607 tree rhs;
608 ssa_op_iter iter;
609 gimple *def_stmt;
610 enum vect_def_type dt;
612 FOR_EACH_SSA_TREE_OPERAND (rhs, stmt, iter, SSA_OP_USE)
614 if (!vect_is_simple_use (rhs, mask_producers[i]->vinfo,
615 &def_stmt, &dt, &vectype))
617 if (dump_enabled_p ())
619 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
620 "not vectorized: can't compute mask type "
621 "for statement, ");
622 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
625 return false;
628 /* No vectype probably means external definition.
629 Allow it in case there is another operand which
630 allows to determine mask type. */
631 if (!vectype)
632 continue;
634 if (!mask_type)
635 mask_type = vectype;
636 else if (TYPE_VECTOR_SUBPARTS (mask_type)
637 != TYPE_VECTOR_SUBPARTS (vectype))
639 if (dump_enabled_p ())
641 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
642 "not vectorized: different sized masks "
643 "types in statement, ");
644 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
645 mask_type);
646 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
647 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
648 vectype);
649 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
651 return false;
653 else if (VECTOR_BOOLEAN_TYPE_P (mask_type)
654 != VECTOR_BOOLEAN_TYPE_P (vectype))
656 if (dump_enabled_p ())
658 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
659 "not vectorized: mixed mask and "
660 "nonmask vector types in statement, ");
661 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
662 mask_type);
663 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
664 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
665 vectype);
666 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
668 return false;
672 /* We may compare boolean value loaded as vector of integers.
673 Fix mask_type in such case. */
674 if (mask_type
675 && !VECTOR_BOOLEAN_TYPE_P (mask_type)
676 && gimple_code (stmt) == GIMPLE_ASSIGN
677 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
678 mask_type = build_same_sized_truth_vector_type (mask_type);
681 /* No mask_type should mean loop invariant predicate.
682 This is probably a subject for optimization in
683 if-conversion. */
684 if (!mask_type)
686 if (dump_enabled_p ())
688 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
689 "not vectorized: can't compute mask type "
690 "for statement, ");
691 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
694 return false;
697 STMT_VINFO_VECTYPE (mask_producers[i]) = mask_type;
700 return true;
704 /* Function vect_is_simple_iv_evolution.
706 FORNOW: A simple evolution of an induction variables in the loop is
707 considered a polynomial evolution. */
709 static bool
710 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
711 tree * step)
713 tree init_expr;
714 tree step_expr;
715 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
716 basic_block bb;
718 /* When there is no evolution in this loop, the evolution function
719 is not "simple". */
720 if (evolution_part == NULL_TREE)
721 return false;
723 /* When the evolution is a polynomial of degree >= 2
724 the evolution function is not "simple". */
725 if (tree_is_chrec (evolution_part))
726 return false;
728 step_expr = evolution_part;
729 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
731 if (dump_enabled_p ())
733 dump_printf_loc (MSG_NOTE, vect_location, "step: ");
734 dump_generic_expr (MSG_NOTE, TDF_SLIM, step_expr);
735 dump_printf (MSG_NOTE, ", init: ");
736 dump_generic_expr (MSG_NOTE, TDF_SLIM, init_expr);
737 dump_printf (MSG_NOTE, "\n");
740 *init = init_expr;
741 *step = step_expr;
743 if (TREE_CODE (step_expr) != INTEGER_CST
744 && (TREE_CODE (step_expr) != SSA_NAME
745 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
746 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
747 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
748 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
749 || !flag_associative_math)))
750 && (TREE_CODE (step_expr) != REAL_CST
751 || !flag_associative_math))
753 if (dump_enabled_p ())
754 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
755 "step unknown.\n");
756 return false;
759 return true;
762 /* Function vect_analyze_scalar_cycles_1.
764 Examine the cross iteration def-use cycles of scalar variables
765 in LOOP. LOOP_VINFO represents the loop that is now being
766 considered for vectorization (can be LOOP, or an outer-loop
767 enclosing LOOP). */
769 static void
770 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, struct loop *loop)
772 basic_block bb = loop->header;
773 tree init, step;
774 auto_vec<gimple *, 64> worklist;
775 gphi_iterator gsi;
776 bool double_reduc;
778 if (dump_enabled_p ())
779 dump_printf_loc (MSG_NOTE, vect_location,
780 "=== vect_analyze_scalar_cycles ===\n");
782 /* First - identify all inductions. Reduction detection assumes that all the
783 inductions have been identified, therefore, this order must not be
784 changed. */
785 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
787 gphi *phi = gsi.phi ();
788 tree access_fn = NULL;
789 tree def = PHI_RESULT (phi);
790 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
792 if (dump_enabled_p ())
794 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
795 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
798 /* Skip virtual phi's. The data dependences that are associated with
799 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
800 if (virtual_operand_p (def))
801 continue;
803 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
805 /* Analyze the evolution function. */
806 access_fn = analyze_scalar_evolution (loop, def);
807 if (access_fn)
809 STRIP_NOPS (access_fn);
810 if (dump_enabled_p ())
812 dump_printf_loc (MSG_NOTE, vect_location,
813 "Access function of PHI: ");
814 dump_generic_expr (MSG_NOTE, TDF_SLIM, access_fn);
815 dump_printf (MSG_NOTE, "\n");
817 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
818 = initial_condition_in_loop_num (access_fn, loop->num);
819 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
820 = evolution_part_in_loop_num (access_fn, loop->num);
823 if (!access_fn
824 || !vect_is_simple_iv_evolution (loop->num, access_fn, &init, &step)
825 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
826 && TREE_CODE (step) != INTEGER_CST))
828 worklist.safe_push (phi);
829 continue;
832 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
833 != NULL_TREE);
834 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
836 if (dump_enabled_p ())
837 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
838 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
842 /* Second - identify all reductions and nested cycles. */
843 while (worklist.length () > 0)
845 gimple *phi = worklist.pop ();
846 tree def = PHI_RESULT (phi);
847 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
848 gimple *reduc_stmt;
850 if (dump_enabled_p ())
852 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
853 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
856 gcc_assert (!virtual_operand_p (def)
857 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
859 reduc_stmt = vect_force_simple_reduction (loop_vinfo, phi,
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 (loop != LOOP_VINFO_LOOP (loop_vinfo))
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 if it was not detected as reduction
896 chain. */
897 if (! GROUP_FIRST_ELEMENT (vinfo_for_stmt (reduc_stmt)))
898 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt);
902 else
903 if (dump_enabled_p ())
904 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
905 "Unknown def-use cycle pattern.\n");
910 /* Function vect_analyze_scalar_cycles.
912 Examine the cross iteration def-use cycles of scalar variables, by
913 analyzing the loop-header PHIs of scalar variables. Classify each
914 cycle as one of the following: invariant, induction, reduction, unknown.
915 We do that for the loop represented by LOOP_VINFO, and also to its
916 inner-loop, if exists.
917 Examples for scalar cycles:
919 Example1: reduction:
921 loop1:
922 for (i=0; i<N; i++)
923 sum += a[i];
925 Example2: induction:
927 loop2:
928 for (i=0; i<N; i++)
929 a[i] = i; */
931 static void
932 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
934 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
936 vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
938 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
939 Reductions in such inner-loop therefore have different properties than
940 the reductions in the nest that gets vectorized:
941 1. When vectorized, they are executed in the same order as in the original
942 scalar loop, so we can't change the order of computation when
943 vectorizing them.
944 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
945 current checks are too strict. */
947 if (loop->inner)
948 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
951 /* Transfer group and reduction information from STMT to its pattern stmt. */
953 static void
954 vect_fixup_reduc_chain (gimple *stmt)
956 gimple *firstp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
957 gimple *stmtp;
958 gcc_assert (!GROUP_FIRST_ELEMENT (vinfo_for_stmt (firstp))
959 && GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
960 GROUP_SIZE (vinfo_for_stmt (firstp)) = GROUP_SIZE (vinfo_for_stmt (stmt));
963 stmtp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
964 GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmtp)) = firstp;
965 stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmt));
966 if (stmt)
967 GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmtp))
968 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
970 while (stmt);
971 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmtp)) = vect_reduction_def;
974 /* Fixup scalar cycles that now have their stmts detected as patterns. */
976 static void
977 vect_fixup_scalar_cycles_with_patterns (loop_vec_info loop_vinfo)
979 gimple *first;
980 unsigned i;
982 FOR_EACH_VEC_ELT (LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo), i, first)
983 if (STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (first)))
985 gimple *next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (first));
986 while (next)
988 if (! STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (next)))
989 break;
990 next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
992 /* If not all stmt in the chain are patterns try to handle
993 the chain without patterns. */
994 if (! next)
996 vect_fixup_reduc_chain (first);
997 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo)[i]
998 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (first));
1003 /* Function vect_get_loop_niters.
1005 Determine how many iterations the loop is executed and place it
1006 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
1007 in NUMBER_OF_ITERATIONSM1. Place the condition under which the
1008 niter information holds in ASSUMPTIONS.
1010 Return the loop exit condition. */
1013 static gcond *
1014 vect_get_loop_niters (struct loop *loop, tree *assumptions,
1015 tree *number_of_iterations, tree *number_of_iterationsm1)
1017 edge exit = single_exit (loop);
1018 struct tree_niter_desc niter_desc;
1019 tree niter_assumptions, niter, may_be_zero;
1020 gcond *cond = get_loop_exit_condition (loop);
1022 *assumptions = boolean_true_node;
1023 *number_of_iterationsm1 = chrec_dont_know;
1024 *number_of_iterations = chrec_dont_know;
1025 if (dump_enabled_p ())
1026 dump_printf_loc (MSG_NOTE, vect_location,
1027 "=== get_loop_niters ===\n");
1029 if (!exit)
1030 return cond;
1032 niter = chrec_dont_know;
1033 may_be_zero = NULL_TREE;
1034 niter_assumptions = boolean_true_node;
1035 if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
1036 || chrec_contains_undetermined (niter_desc.niter))
1037 return cond;
1039 niter_assumptions = niter_desc.assumptions;
1040 may_be_zero = niter_desc.may_be_zero;
1041 niter = niter_desc.niter;
1043 if (may_be_zero && integer_zerop (may_be_zero))
1044 may_be_zero = NULL_TREE;
1046 if (may_be_zero)
1048 if (COMPARISON_CLASS_P (may_be_zero))
1050 /* Try to combine may_be_zero with assumptions, this can simplify
1051 computation of niter expression. */
1052 if (niter_assumptions && !integer_nonzerop (niter_assumptions))
1053 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1054 niter_assumptions,
1055 fold_build1 (TRUTH_NOT_EXPR,
1056 boolean_type_node,
1057 may_be_zero));
1058 else
1059 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
1060 build_int_cst (TREE_TYPE (niter), 0), niter);
1062 may_be_zero = NULL_TREE;
1064 else if (integer_nonzerop (may_be_zero))
1066 *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
1067 *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
1068 return cond;
1070 else
1071 return cond;
1074 *assumptions = niter_assumptions;
1075 *number_of_iterationsm1 = niter;
1077 /* We want the number of loop header executions which is the number
1078 of latch executions plus one.
1079 ??? For UINT_MAX latch executions this number overflows to zero
1080 for loops like do { n++; } while (n != 0); */
1081 if (niter && !chrec_contains_undetermined (niter))
1082 niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), unshare_expr (niter),
1083 build_int_cst (TREE_TYPE (niter), 1));
1084 *number_of_iterations = niter;
1086 return cond;
1089 /* Function bb_in_loop_p
1091 Used as predicate for dfs order traversal of the loop bbs. */
1093 static bool
1094 bb_in_loop_p (const_basic_block bb, const void *data)
1096 const struct loop *const loop = (const struct loop *)data;
1097 if (flow_bb_inside_loop_p (loop, bb))
1098 return true;
1099 return false;
1103 /* Create and initialize a new loop_vec_info struct for LOOP_IN, as well as
1104 stmt_vec_info structs for all the stmts in LOOP_IN. */
1106 _loop_vec_info::_loop_vec_info (struct loop *loop_in)
1107 : vec_info (vec_info::loop, init_cost (loop_in)),
1108 loop (loop_in),
1109 bbs (XCNEWVEC (basic_block, loop->num_nodes)),
1110 num_itersm1 (NULL_TREE),
1111 num_iters (NULL_TREE),
1112 num_iters_unchanged (NULL_TREE),
1113 num_iters_assumptions (NULL_TREE),
1114 th (0),
1115 vectorization_factor (0),
1116 max_vectorization_factor (0),
1117 unaligned_dr (NULL),
1118 peeling_for_alignment (0),
1119 ptr_mask (0),
1120 slp_unrolling_factor (1),
1121 single_scalar_iteration_cost (0),
1122 vectorizable (false),
1123 peeling_for_gaps (false),
1124 peeling_for_niter (false),
1125 operands_swapped (false),
1126 no_data_dependencies (false),
1127 has_mask_store (false),
1128 scalar_loop (NULL),
1129 orig_loop_info (NULL)
1131 /* Create/Update stmt_info for all stmts in the loop. */
1132 basic_block *body = get_loop_body (loop);
1133 for (unsigned int i = 0; i < loop->num_nodes; i++)
1135 basic_block bb = body[i];
1136 gimple_stmt_iterator si;
1138 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1140 gimple *phi = gsi_stmt (si);
1141 gimple_set_uid (phi, 0);
1142 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, this));
1145 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1147 gimple *stmt = gsi_stmt (si);
1148 gimple_set_uid (stmt, 0);
1149 set_vinfo_for_stmt (stmt, new_stmt_vec_info (stmt, this));
1152 free (body);
1154 /* CHECKME: We want to visit all BBs before their successors (except for
1155 latch blocks, for which this assertion wouldn't hold). In the simple
1156 case of the loop forms we allow, a dfs order of the BBs would the same
1157 as reversed postorder traversal, so we are safe. */
1159 unsigned int nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p,
1160 bbs, loop->num_nodes, loop);
1161 gcc_assert (nbbs == loop->num_nodes);
1165 /* Free all memory used by the _loop_vec_info, as well as all the
1166 stmt_vec_info structs of all the stmts in the loop. */
1168 _loop_vec_info::~_loop_vec_info ()
1170 int nbbs;
1171 gimple_stmt_iterator si;
1172 int j;
1174 nbbs = loop->num_nodes;
1175 for (j = 0; j < nbbs; j++)
1177 basic_block bb = bbs[j];
1178 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1179 free_stmt_vec_info (gsi_stmt (si));
1181 for (si = gsi_start_bb (bb); !gsi_end_p (si); )
1183 gimple *stmt = gsi_stmt (si);
1185 /* We may have broken canonical form by moving a constant
1186 into RHS1 of a commutative op. Fix such occurrences. */
1187 if (operands_swapped && is_gimple_assign (stmt))
1189 enum tree_code code = gimple_assign_rhs_code (stmt);
1191 if ((code == PLUS_EXPR
1192 || code == POINTER_PLUS_EXPR
1193 || code == MULT_EXPR)
1194 && CONSTANT_CLASS_P (gimple_assign_rhs1 (stmt)))
1195 swap_ssa_operands (stmt,
1196 gimple_assign_rhs1_ptr (stmt),
1197 gimple_assign_rhs2_ptr (stmt));
1198 else if (code == COND_EXPR
1199 && CONSTANT_CLASS_P (gimple_assign_rhs2 (stmt)))
1201 tree cond_expr = gimple_assign_rhs1 (stmt);
1202 enum tree_code cond_code = TREE_CODE (cond_expr);
1204 if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
1206 bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr,
1207 0));
1208 cond_code = invert_tree_comparison (cond_code,
1209 honor_nans);
1210 if (cond_code != ERROR_MARK)
1212 TREE_SET_CODE (cond_expr, cond_code);
1213 swap_ssa_operands (stmt,
1214 gimple_assign_rhs2_ptr (stmt),
1215 gimple_assign_rhs3_ptr (stmt));
1221 /* Free stmt_vec_info. */
1222 free_stmt_vec_info (stmt);
1223 gsi_next (&si);
1227 free (bbs);
1229 loop->aux = NULL;
1233 /* Calculate the cost of one scalar iteration of the loop. */
1234 static void
1235 vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
1237 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1238 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1239 int nbbs = loop->num_nodes, factor, scalar_single_iter_cost = 0;
1240 int innerloop_iters, i;
1242 /* Count statements in scalar loop. Using this as scalar cost for a single
1243 iteration for now.
1245 TODO: Add outer loop support.
1247 TODO: Consider assigning different costs to different scalar
1248 statements. */
1250 /* FORNOW. */
1251 innerloop_iters = 1;
1252 if (loop->inner)
1253 innerloop_iters = 50; /* FIXME */
1255 for (i = 0; i < nbbs; i++)
1257 gimple_stmt_iterator si;
1258 basic_block bb = bbs[i];
1260 if (bb->loop_father == loop->inner)
1261 factor = innerloop_iters;
1262 else
1263 factor = 1;
1265 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1267 gimple *stmt = gsi_stmt (si);
1268 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1270 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1271 continue;
1273 /* Skip stmts that are not vectorized inside the loop. */
1274 if (stmt_info
1275 && !STMT_VINFO_RELEVANT_P (stmt_info)
1276 && (!STMT_VINFO_LIVE_P (stmt_info)
1277 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1278 && !STMT_VINFO_IN_PATTERN_P (stmt_info))
1279 continue;
1281 vect_cost_for_stmt kind;
1282 if (STMT_VINFO_DATA_REF (stmt_info))
1284 if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
1285 kind = scalar_load;
1286 else
1287 kind = scalar_store;
1289 else
1290 kind = scalar_stmt;
1292 scalar_single_iter_cost
1293 += record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1294 factor, kind, stmt_info, 0, vect_prologue);
1297 LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo)
1298 = scalar_single_iter_cost;
1302 /* Function vect_analyze_loop_form_1.
1304 Verify that certain CFG restrictions hold, including:
1305 - the loop has a pre-header
1306 - the loop has a single entry and exit
1307 - the loop exit condition is simple enough
1308 - the number of iterations can be analyzed, i.e, a countable loop. The
1309 niter could be analyzed under some assumptions. */
1311 bool
1312 vect_analyze_loop_form_1 (struct loop *loop, gcond **loop_cond,
1313 tree *assumptions, tree *number_of_iterationsm1,
1314 tree *number_of_iterations, gcond **inner_loop_cond)
1316 if (dump_enabled_p ())
1317 dump_printf_loc (MSG_NOTE, vect_location,
1318 "=== vect_analyze_loop_form ===\n");
1320 /* Different restrictions apply when we are considering an inner-most loop,
1321 vs. an outer (nested) loop.
1322 (FORNOW. May want to relax some of these restrictions in the future). */
1324 if (!loop->inner)
1326 /* Inner-most loop. We currently require that the number of BBs is
1327 exactly 2 (the header and latch). Vectorizable inner-most loops
1328 look like this:
1330 (pre-header)
1332 header <--------+
1333 | | |
1334 | +--> latch --+
1336 (exit-bb) */
1338 if (loop->num_nodes != 2)
1340 if (dump_enabled_p ())
1341 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1342 "not vectorized: control flow in loop.\n");
1343 return false;
1346 if (empty_block_p (loop->header))
1348 if (dump_enabled_p ())
1349 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1350 "not vectorized: empty loop.\n");
1351 return false;
1354 else
1356 struct loop *innerloop = loop->inner;
1357 edge entryedge;
1359 /* Nested loop. We currently require that the loop is doubly-nested,
1360 contains a single inner loop, and the number of BBs is exactly 5.
1361 Vectorizable outer-loops look like this:
1363 (pre-header)
1365 header <---+
1367 inner-loop |
1369 tail ------+
1371 (exit-bb)
1373 The inner-loop has the properties expected of inner-most loops
1374 as described above. */
1376 if ((loop->inner)->inner || (loop->inner)->next)
1378 if (dump_enabled_p ())
1379 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1380 "not vectorized: multiple nested loops.\n");
1381 return false;
1384 if (loop->num_nodes != 5)
1386 if (dump_enabled_p ())
1387 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1388 "not vectorized: control flow in loop.\n");
1389 return false;
1392 entryedge = loop_preheader_edge (innerloop);
1393 if (entryedge->src != loop->header
1394 || !single_exit (innerloop)
1395 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1397 if (dump_enabled_p ())
1398 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1399 "not vectorized: unsupported outerloop form.\n");
1400 return false;
1403 /* Analyze the inner-loop. */
1404 tree inner_niterm1, inner_niter, inner_assumptions;
1405 if (! vect_analyze_loop_form_1 (loop->inner, inner_loop_cond,
1406 &inner_assumptions, &inner_niterm1,
1407 &inner_niter, NULL)
1408 /* Don't support analyzing niter under assumptions for inner
1409 loop. */
1410 || !integer_onep (inner_assumptions))
1412 if (dump_enabled_p ())
1413 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1414 "not vectorized: Bad inner loop.\n");
1415 return false;
1418 if (!expr_invariant_in_loop_p (loop, inner_niter))
1420 if (dump_enabled_p ())
1421 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1422 "not vectorized: inner-loop count not"
1423 " invariant.\n");
1424 return false;
1427 if (dump_enabled_p ())
1428 dump_printf_loc (MSG_NOTE, vect_location,
1429 "Considering outer-loop vectorization.\n");
1432 if (!single_exit (loop)
1433 || EDGE_COUNT (loop->header->preds) != 2)
1435 if (dump_enabled_p ())
1437 if (!single_exit (loop))
1438 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1439 "not vectorized: multiple exits.\n");
1440 else if (EDGE_COUNT (loop->header->preds) != 2)
1441 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1442 "not vectorized: too many incoming edges.\n");
1444 return false;
1447 /* We assume that the loop exit condition is at the end of the loop. i.e,
1448 that the loop is represented as a do-while (with a proper if-guard
1449 before the loop if needed), where the loop header contains all the
1450 executable statements, and the latch is empty. */
1451 if (!empty_block_p (loop->latch)
1452 || !gimple_seq_empty_p (phi_nodes (loop->latch)))
1454 if (dump_enabled_p ())
1455 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1456 "not vectorized: latch block not empty.\n");
1457 return false;
1460 /* Make sure the exit is not abnormal. */
1461 edge e = single_exit (loop);
1462 if (e->flags & EDGE_ABNORMAL)
1464 if (dump_enabled_p ())
1465 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1466 "not vectorized: abnormal loop exit edge.\n");
1467 return false;
1470 *loop_cond = vect_get_loop_niters (loop, assumptions, number_of_iterations,
1471 number_of_iterationsm1);
1472 if (!*loop_cond)
1474 if (dump_enabled_p ())
1475 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1476 "not vectorized: complicated exit condition.\n");
1477 return false;
1480 if (integer_zerop (*assumptions)
1481 || !*number_of_iterations
1482 || chrec_contains_undetermined (*number_of_iterations))
1484 if (dump_enabled_p ())
1485 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1486 "not vectorized: number of iterations cannot be "
1487 "computed.\n");
1488 return false;
1491 if (integer_zerop (*number_of_iterations))
1493 if (dump_enabled_p ())
1494 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1495 "not vectorized: number of iterations = 0.\n");
1496 return false;
1499 return true;
1502 /* Analyze LOOP form and return a loop_vec_info if it is of suitable form. */
1504 loop_vec_info
1505 vect_analyze_loop_form (struct loop *loop)
1507 tree assumptions, number_of_iterations, number_of_iterationsm1;
1508 gcond *loop_cond, *inner_loop_cond = NULL;
1510 if (! vect_analyze_loop_form_1 (loop, &loop_cond,
1511 &assumptions, &number_of_iterationsm1,
1512 &number_of_iterations, &inner_loop_cond))
1513 return NULL;
1515 loop_vec_info loop_vinfo = new _loop_vec_info (loop);
1516 LOOP_VINFO_NITERSM1 (loop_vinfo) = number_of_iterationsm1;
1517 LOOP_VINFO_NITERS (loop_vinfo) = number_of_iterations;
1518 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = number_of_iterations;
1519 if (!integer_onep (assumptions))
1521 /* We consider to vectorize this loop by versioning it under
1522 some assumptions. In order to do this, we need to clear
1523 existing information computed by scev and niter analyzer. */
1524 scev_reset_htab ();
1525 free_numbers_of_iterations_estimates (loop);
1526 /* Also set flag for this loop so that following scev and niter
1527 analysis are done under the assumptions. */
1528 loop_constraint_set (loop, LOOP_C_FINITE);
1529 /* Also record the assumptions for versioning. */
1530 LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = assumptions;
1533 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
1535 if (dump_enabled_p ())
1537 dump_printf_loc (MSG_NOTE, vect_location,
1538 "Symbolic number of iterations is ");
1539 dump_generic_expr (MSG_NOTE, TDF_DETAILS, number_of_iterations);
1540 dump_printf (MSG_NOTE, "\n");
1544 STMT_VINFO_TYPE (vinfo_for_stmt (loop_cond)) = loop_exit_ctrl_vec_info_type;
1545 if (inner_loop_cond)
1546 STMT_VINFO_TYPE (vinfo_for_stmt (inner_loop_cond))
1547 = loop_exit_ctrl_vec_info_type;
1549 gcc_assert (!loop->aux);
1550 loop->aux = loop_vinfo;
1551 return loop_vinfo;
1556 /* Scan the loop stmts and dependent on whether there are any (non-)SLP
1557 statements update the vectorization factor. */
1559 static void
1560 vect_update_vf_for_slp (loop_vec_info loop_vinfo)
1562 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1563 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1564 int nbbs = loop->num_nodes;
1565 unsigned int vectorization_factor;
1566 int i;
1568 if (dump_enabled_p ())
1569 dump_printf_loc (MSG_NOTE, vect_location,
1570 "=== vect_update_vf_for_slp ===\n");
1572 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1573 gcc_assert (vectorization_factor != 0);
1575 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
1576 vectorization factor of the loop is the unrolling factor required by
1577 the SLP instances. If that unrolling factor is 1, we say, that we
1578 perform pure SLP on loop - cross iteration parallelism is not
1579 exploited. */
1580 bool only_slp_in_loop = true;
1581 for (i = 0; i < nbbs; i++)
1583 basic_block bb = bbs[i];
1584 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1585 gsi_next (&si))
1587 gimple *stmt = gsi_stmt (si);
1588 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1589 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
1590 && STMT_VINFO_RELATED_STMT (stmt_info))
1592 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
1593 stmt_info = vinfo_for_stmt (stmt);
1595 if ((STMT_VINFO_RELEVANT_P (stmt_info)
1596 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1597 && !PURE_SLP_STMT (stmt_info))
1598 /* STMT needs both SLP and loop-based vectorization. */
1599 only_slp_in_loop = false;
1603 if (only_slp_in_loop)
1605 dump_printf_loc (MSG_NOTE, vect_location,
1606 "Loop contains only SLP stmts\n");
1607 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
1609 else
1611 dump_printf_loc (MSG_NOTE, vect_location,
1612 "Loop contains SLP and non-SLP stmts\n");
1613 vectorization_factor
1614 = least_common_multiple (vectorization_factor,
1615 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
1618 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
1619 if (dump_enabled_p ())
1620 dump_printf_loc (MSG_NOTE, vect_location,
1621 "Updating vectorization factor to %d\n",
1622 vectorization_factor);
1625 /* Function vect_analyze_loop_operations.
1627 Scan the loop stmts and make sure they are all vectorizable. */
1629 static bool
1630 vect_analyze_loop_operations (loop_vec_info loop_vinfo)
1632 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1633 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1634 int nbbs = loop->num_nodes;
1635 int i;
1636 stmt_vec_info stmt_info;
1637 bool need_to_vectorize = false;
1638 bool ok;
1640 if (dump_enabled_p ())
1641 dump_printf_loc (MSG_NOTE, vect_location,
1642 "=== vect_analyze_loop_operations ===\n");
1644 for (i = 0; i < nbbs; i++)
1646 basic_block bb = bbs[i];
1648 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
1649 gsi_next (&si))
1651 gphi *phi = si.phi ();
1652 ok = true;
1654 stmt_info = vinfo_for_stmt (phi);
1655 if (dump_enabled_p ())
1657 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: ");
1658 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
1660 if (virtual_operand_p (gimple_phi_result (phi)))
1661 continue;
1663 /* Inner-loop loop-closed exit phi in outer-loop vectorization
1664 (i.e., a phi in the tail of the outer-loop). */
1665 if (! is_loop_header_bb_p (bb))
1667 /* FORNOW: we currently don't support the case that these phis
1668 are not used in the outerloop (unless it is double reduction,
1669 i.e., this phi is vect_reduction_def), cause this case
1670 requires to actually do something here. */
1671 if (STMT_VINFO_LIVE_P (stmt_info)
1672 && STMT_VINFO_DEF_TYPE (stmt_info)
1673 != vect_double_reduction_def)
1675 if (dump_enabled_p ())
1676 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1677 "Unsupported loop-closed phi in "
1678 "outer-loop.\n");
1679 return false;
1682 /* If PHI is used in the outer loop, we check that its operand
1683 is defined in the inner loop. */
1684 if (STMT_VINFO_RELEVANT_P (stmt_info))
1686 tree phi_op;
1687 gimple *op_def_stmt;
1689 if (gimple_phi_num_args (phi) != 1)
1690 return false;
1692 phi_op = PHI_ARG_DEF (phi, 0);
1693 if (TREE_CODE (phi_op) != SSA_NAME)
1694 return false;
1696 op_def_stmt = SSA_NAME_DEF_STMT (phi_op);
1697 if (gimple_nop_p (op_def_stmt)
1698 || !flow_bb_inside_loop_p (loop, gimple_bb (op_def_stmt))
1699 || !vinfo_for_stmt (op_def_stmt))
1700 return false;
1702 if (STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1703 != vect_used_in_outer
1704 && STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1705 != vect_used_in_outer_by_reduction)
1706 return false;
1709 continue;
1712 gcc_assert (stmt_info);
1714 if ((STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
1715 || STMT_VINFO_LIVE_P (stmt_info))
1716 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
1718 /* A scalar-dependence cycle that we don't support. */
1719 if (dump_enabled_p ())
1720 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1721 "not vectorized: scalar dependence cycle.\n");
1722 return false;
1725 if (STMT_VINFO_RELEVANT_P (stmt_info))
1727 need_to_vectorize = true;
1728 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
1729 && ! PURE_SLP_STMT (stmt_info))
1730 ok = vectorizable_induction (phi, NULL, NULL, NULL);
1731 else if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
1732 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
1733 && ! PURE_SLP_STMT (stmt_info))
1734 ok = vectorizable_reduction (phi, NULL, NULL, NULL, NULL);
1737 if (ok && STMT_VINFO_LIVE_P (stmt_info))
1738 ok = vectorizable_live_operation (phi, NULL, NULL, -1, NULL);
1740 if (!ok)
1742 if (dump_enabled_p ())
1744 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1745 "not vectorized: relevant phi not "
1746 "supported: ");
1747 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, phi, 0);
1749 return false;
1753 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1754 gsi_next (&si))
1756 gimple *stmt = gsi_stmt (si);
1757 if (!gimple_clobber_p (stmt)
1758 && !vect_analyze_stmt (stmt, &need_to_vectorize, NULL, NULL))
1759 return false;
1761 } /* bbs */
1763 /* All operations in the loop are either irrelevant (deal with loop
1764 control, or dead), or only used outside the loop and can be moved
1765 out of the loop (e.g. invariants, inductions). The loop can be
1766 optimized away by scalar optimizations. We're better off not
1767 touching this loop. */
1768 if (!need_to_vectorize)
1770 if (dump_enabled_p ())
1771 dump_printf_loc (MSG_NOTE, vect_location,
1772 "All the computation can be taken out of the loop.\n");
1773 if (dump_enabled_p ())
1774 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1775 "not vectorized: redundant loop. no profit to "
1776 "vectorize.\n");
1777 return false;
1780 return true;
1784 /* Function vect_analyze_loop_2.
1786 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1787 for it. The different analyses will record information in the
1788 loop_vec_info struct. */
1789 static bool
1790 vect_analyze_loop_2 (loop_vec_info loop_vinfo, bool &fatal)
1792 bool ok;
1793 int max_vf = MAX_VECTORIZATION_FACTOR;
1794 int min_vf = 2;
1795 unsigned int n_stmts = 0;
1797 /* The first group of checks is independent of the vector size. */
1798 fatal = true;
1800 /* Find all data references in the loop (which correspond to vdefs/vuses)
1801 and analyze their evolution in the loop. */
1803 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1805 loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
1806 if (!find_loop_nest (loop, &LOOP_VINFO_LOOP_NEST (loop_vinfo)))
1808 if (dump_enabled_p ())
1809 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1810 "not vectorized: loop nest containing two "
1811 "or more consecutive inner loops cannot be "
1812 "vectorized\n");
1813 return false;
1816 for (unsigned i = 0; i < loop->num_nodes; i++)
1817 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
1818 !gsi_end_p (gsi); gsi_next (&gsi))
1820 gimple *stmt = gsi_stmt (gsi);
1821 if (is_gimple_debug (stmt))
1822 continue;
1823 ++n_stmts;
1824 if (!find_data_references_in_stmt (loop, stmt,
1825 &LOOP_VINFO_DATAREFS (loop_vinfo)))
1827 if (is_gimple_call (stmt) && loop->safelen)
1829 tree fndecl = gimple_call_fndecl (stmt), op;
1830 if (fndecl != NULL_TREE)
1832 cgraph_node *node = cgraph_node::get (fndecl);
1833 if (node != NULL && node->simd_clones != NULL)
1835 unsigned int j, n = gimple_call_num_args (stmt);
1836 for (j = 0; j < n; j++)
1838 op = gimple_call_arg (stmt, j);
1839 if (DECL_P (op)
1840 || (REFERENCE_CLASS_P (op)
1841 && get_base_address (op)))
1842 break;
1844 op = gimple_call_lhs (stmt);
1845 /* Ignore #pragma omp declare simd functions
1846 if they don't have data references in the
1847 call stmt itself. */
1848 if (j == n
1849 && !(op
1850 && (DECL_P (op)
1851 || (REFERENCE_CLASS_P (op)
1852 && get_base_address (op)))))
1853 continue;
1857 if (dump_enabled_p ())
1858 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1859 "not vectorized: loop contains function "
1860 "calls or data references that cannot "
1861 "be analyzed\n");
1862 return false;
1866 /* Analyze the data references and also adjust the minimal
1867 vectorization factor according to the loads and stores. */
1869 ok = vect_analyze_data_refs (loop_vinfo, &min_vf);
1870 if (!ok)
1872 if (dump_enabled_p ())
1873 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1874 "bad data references.\n");
1875 return false;
1878 /* Classify all cross-iteration scalar data-flow cycles.
1879 Cross-iteration cycles caused by virtual phis are analyzed separately. */
1880 vect_analyze_scalar_cycles (loop_vinfo);
1882 vect_pattern_recog (loop_vinfo);
1884 vect_fixup_scalar_cycles_with_patterns (loop_vinfo);
1886 /* Analyze the access patterns of the data-refs in the loop (consecutive,
1887 complex, etc.). FORNOW: Only handle consecutive access pattern. */
1889 ok = vect_analyze_data_ref_accesses (loop_vinfo);
1890 if (!ok)
1892 if (dump_enabled_p ())
1893 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1894 "bad data access.\n");
1895 return false;
1898 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
1900 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo);
1901 if (!ok)
1903 if (dump_enabled_p ())
1904 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1905 "unexpected pattern.\n");
1906 return false;
1909 /* While the rest of the analysis below depends on it in some way. */
1910 fatal = false;
1912 /* Analyze data dependences between the data-refs in the loop
1913 and adjust the maximum vectorization factor according to
1914 the dependences.
1915 FORNOW: fail at the first data dependence that we encounter. */
1917 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
1918 if (!ok
1919 || max_vf < min_vf)
1921 if (dump_enabled_p ())
1922 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1923 "bad data dependence.\n");
1924 return false;
1926 LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) = max_vf;
1928 ok = vect_determine_vectorization_factor (loop_vinfo);
1929 if (!ok)
1931 if (dump_enabled_p ())
1932 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1933 "can't determine vectorization factor.\n");
1934 return false;
1936 if (max_vf < LOOP_VINFO_VECT_FACTOR (loop_vinfo))
1938 if (dump_enabled_p ())
1939 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1940 "bad data dependence.\n");
1941 return false;
1944 /* Compute the scalar iteration cost. */
1945 vect_compute_single_scalar_iteration_cost (loop_vinfo);
1947 int saved_vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1948 HOST_WIDE_INT estimated_niter;
1949 unsigned th;
1950 int min_scalar_loop_bound;
1952 /* Check the SLP opportunities in the loop, analyze and build SLP trees. */
1953 ok = vect_analyze_slp (loop_vinfo, n_stmts);
1954 if (!ok)
1955 return false;
1957 /* If there are any SLP instances mark them as pure_slp. */
1958 bool slp = vect_make_slp_decision (loop_vinfo);
1959 if (slp)
1961 /* Find stmts that need to be both vectorized and SLPed. */
1962 vect_detect_hybrid_slp (loop_vinfo);
1964 /* Update the vectorization factor based on the SLP decision. */
1965 vect_update_vf_for_slp (loop_vinfo);
1968 /* This is the point where we can re-start analysis with SLP forced off. */
1969 start_over:
1971 /* Now the vectorization factor is final. */
1972 unsigned vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1973 gcc_assert (vectorization_factor != 0);
1975 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
1976 dump_printf_loc (MSG_NOTE, vect_location,
1977 "vectorization_factor = %d, niters = "
1978 HOST_WIDE_INT_PRINT_DEC "\n", vectorization_factor,
1979 LOOP_VINFO_INT_NITERS (loop_vinfo));
1981 HOST_WIDE_INT max_niter
1982 = likely_max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
1983 if ((LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1984 && (LOOP_VINFO_INT_NITERS (loop_vinfo) < vectorization_factor))
1985 || (max_niter != -1
1986 && (unsigned HOST_WIDE_INT) max_niter < vectorization_factor))
1988 if (dump_enabled_p ())
1989 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1990 "not vectorized: iteration count smaller than "
1991 "vectorization factor.\n");
1992 return false;
1995 /* Analyze the alignment of the data-refs in the loop.
1996 Fail if a data reference is found that cannot be vectorized. */
1998 ok = vect_analyze_data_refs_alignment (loop_vinfo);
1999 if (!ok)
2001 if (dump_enabled_p ())
2002 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2003 "bad data alignment.\n");
2004 return false;
2007 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
2008 It is important to call pruning after vect_analyze_data_ref_accesses,
2009 since we use grouping information gathered by interleaving analysis. */
2010 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
2011 if (!ok)
2012 return false;
2014 /* Do not invoke vect_enhance_data_refs_alignment for eplilogue
2015 vectorization. */
2016 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
2018 /* This pass will decide on using loop versioning and/or loop peeling in
2019 order to enhance the alignment of data references in the loop. */
2020 ok = vect_enhance_data_refs_alignment (loop_vinfo);
2021 if (!ok)
2023 if (dump_enabled_p ())
2024 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2025 "bad data alignment.\n");
2026 return false;
2030 if (slp)
2032 /* Analyze operations in the SLP instances. Note this may
2033 remove unsupported SLP instances which makes the above
2034 SLP kind detection invalid. */
2035 unsigned old_size = LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length ();
2036 vect_slp_analyze_operations (loop_vinfo);
2037 if (LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length () != old_size)
2038 goto again;
2041 /* Scan all the remaining operations in the loop that are not subject
2042 to SLP and make sure they are vectorizable. */
2043 ok = vect_analyze_loop_operations (loop_vinfo);
2044 if (!ok)
2046 if (dump_enabled_p ())
2047 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2048 "bad operation or unsupported loop bound.\n");
2049 return false;
2052 /* If epilog loop is required because of data accesses with gaps,
2053 one additional iteration needs to be peeled. Check if there is
2054 enough iterations for vectorization. */
2055 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2056 && LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
2058 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2059 tree scalar_niters = LOOP_VINFO_NITERSM1 (loop_vinfo);
2061 if (wi::to_widest (scalar_niters) < vf)
2063 if (dump_enabled_p ())
2064 dump_printf_loc (MSG_NOTE, vect_location,
2065 "loop has no enough iterations to support"
2066 " peeling for gaps.\n");
2067 return false;
2071 /* Analyze cost. Decide if worth while to vectorize. */
2072 int min_profitable_estimate, min_profitable_iters;
2073 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
2074 &min_profitable_estimate);
2076 if (min_profitable_iters < 0)
2078 if (dump_enabled_p ())
2079 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2080 "not vectorized: vectorization not profitable.\n");
2081 if (dump_enabled_p ())
2082 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2083 "not vectorized: vector version will never be "
2084 "profitable.\n");
2085 goto again;
2088 min_scalar_loop_bound = (PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
2089 * vectorization_factor);
2091 /* Use the cost model only if it is more conservative than user specified
2092 threshold. */
2093 th = (unsigned) MAX (min_scalar_loop_bound, min_profitable_iters);
2095 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
2097 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2098 && LOOP_VINFO_INT_NITERS (loop_vinfo) < th)
2100 if (dump_enabled_p ())
2101 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2102 "not vectorized: vectorization not profitable.\n");
2103 if (dump_enabled_p ())
2104 dump_printf_loc (MSG_NOTE, vect_location,
2105 "not vectorized: iteration count smaller than user "
2106 "specified loop bound parameter or minimum profitable "
2107 "iterations (whichever is more conservative).\n");
2108 goto again;
2111 estimated_niter
2112 = estimated_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2113 if (estimated_niter == -1)
2114 estimated_niter = max_niter;
2115 if (estimated_niter != -1
2116 && ((unsigned HOST_WIDE_INT) estimated_niter
2117 < MAX (th, (unsigned) min_profitable_estimate)))
2119 if (dump_enabled_p ())
2120 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2121 "not vectorized: estimated iteration count too "
2122 "small.\n");
2123 if (dump_enabled_p ())
2124 dump_printf_loc (MSG_NOTE, vect_location,
2125 "not vectorized: estimated iteration count smaller "
2126 "than specified loop bound parameter or minimum "
2127 "profitable iterations (whichever is more "
2128 "conservative).\n");
2129 goto again;
2132 /* Decide whether we need to create an epilogue loop to handle
2133 remaining scalar iterations. */
2134 th = ((LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo)
2135 / LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2136 * LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2138 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2139 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
2141 if (ctz_hwi (LOOP_VINFO_INT_NITERS (loop_vinfo)
2142 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
2143 < exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
2144 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2146 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2147 || (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
2148 < (unsigned)exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2149 /* In case of versioning, check if the maximum number of
2150 iterations is greater than th. If they are identical,
2151 the epilogue is unnecessary. */
2152 && (!LOOP_REQUIRES_VERSIONING (loop_vinfo)
2153 || (unsigned HOST_WIDE_INT) max_niter > th)))
2154 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2156 /* If an epilogue loop is required make sure we can create one. */
2157 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2158 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
2160 if (dump_enabled_p ())
2161 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
2162 if (!vect_can_advance_ivs_p (loop_vinfo)
2163 || !slpeel_can_duplicate_loop_p (LOOP_VINFO_LOOP (loop_vinfo),
2164 single_exit (LOOP_VINFO_LOOP
2165 (loop_vinfo))))
2167 if (dump_enabled_p ())
2168 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2169 "not vectorized: can't create required "
2170 "epilog loop\n");
2171 goto again;
2175 /* During peeling, we need to check if number of loop iterations is
2176 enough for both peeled prolog loop and vector loop. This check
2177 can be merged along with threshold check of loop versioning, so
2178 increase threshold for this case if necessary. */
2179 if (LOOP_REQUIRES_VERSIONING (loop_vinfo)
2180 && (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2181 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)))
2183 unsigned niters_th;
2185 /* Niters for peeled prolog loop. */
2186 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
2188 struct data_reference *dr = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
2189 tree vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (DR_STMT (dr)));
2191 niters_th = TYPE_VECTOR_SUBPARTS (vectype) - 1;
2193 else
2194 niters_th = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
2196 /* Niters for at least one iteration of vectorized loop. */
2197 niters_th += LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2198 /* One additional iteration because of peeling for gap. */
2199 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
2200 niters_th++;
2201 if (LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) < niters_th)
2202 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = niters_th;
2205 gcc_assert (vectorization_factor
2206 == (unsigned)LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2208 /* Ok to vectorize! */
2209 return true;
2211 again:
2212 /* Try again with SLP forced off but if we didn't do any SLP there is
2213 no point in re-trying. */
2214 if (!slp)
2215 return false;
2217 /* If there are reduction chains re-trying will fail anyway. */
2218 if (! LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).is_empty ())
2219 return false;
2221 /* Likewise if the grouped loads or stores in the SLP cannot be handled
2222 via interleaving or lane instructions. */
2223 slp_instance instance;
2224 slp_tree node;
2225 unsigned i, j;
2226 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
2228 stmt_vec_info vinfo;
2229 vinfo = vinfo_for_stmt
2230 (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0]);
2231 if (! STMT_VINFO_GROUPED_ACCESS (vinfo))
2232 continue;
2233 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2234 unsigned int size = STMT_VINFO_GROUP_SIZE (vinfo);
2235 tree vectype = STMT_VINFO_VECTYPE (vinfo);
2236 if (! vect_store_lanes_supported (vectype, size)
2237 && ! vect_grouped_store_supported (vectype, size))
2238 return false;
2239 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
2241 vinfo = vinfo_for_stmt (SLP_TREE_SCALAR_STMTS (node)[0]);
2242 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2243 bool single_element_p = !STMT_VINFO_GROUP_NEXT_ELEMENT (vinfo);
2244 size = STMT_VINFO_GROUP_SIZE (vinfo);
2245 vectype = STMT_VINFO_VECTYPE (vinfo);
2246 if (! vect_load_lanes_supported (vectype, size)
2247 && ! vect_grouped_load_supported (vectype, single_element_p,
2248 size))
2249 return false;
2253 if (dump_enabled_p ())
2254 dump_printf_loc (MSG_NOTE, vect_location,
2255 "re-trying with SLP disabled\n");
2257 /* Roll back state appropriately. No SLP this time. */
2258 slp = false;
2259 /* Restore vectorization factor as it were without SLP. */
2260 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = saved_vectorization_factor;
2261 /* Free the SLP instances. */
2262 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
2263 vect_free_slp_instance (instance);
2264 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
2265 /* Reset SLP type to loop_vect on all stmts. */
2266 for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
2268 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
2269 for (gimple_stmt_iterator si = gsi_start_phis (bb);
2270 !gsi_end_p (si); gsi_next (&si))
2272 stmt_vec_info stmt_info = vinfo_for_stmt (gsi_stmt (si));
2273 STMT_SLP_TYPE (stmt_info) = loop_vect;
2275 for (gimple_stmt_iterator si = gsi_start_bb (bb);
2276 !gsi_end_p (si); gsi_next (&si))
2278 stmt_vec_info stmt_info = vinfo_for_stmt (gsi_stmt (si));
2279 STMT_SLP_TYPE (stmt_info) = loop_vect;
2280 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
2282 stmt_info = vinfo_for_stmt (STMT_VINFO_RELATED_STMT (stmt_info));
2283 STMT_SLP_TYPE (stmt_info) = loop_vect;
2284 for (gimple_stmt_iterator pi
2285 = gsi_start (STMT_VINFO_PATTERN_DEF_SEQ (stmt_info));
2286 !gsi_end_p (pi); gsi_next (&pi))
2288 gimple *pstmt = gsi_stmt (pi);
2289 STMT_SLP_TYPE (vinfo_for_stmt (pstmt)) = loop_vect;
2294 /* Free optimized alias test DDRS. */
2295 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
2296 LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).release ();
2297 /* Reset target cost data. */
2298 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2299 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo)
2300 = init_cost (LOOP_VINFO_LOOP (loop_vinfo));
2301 /* Reset assorted flags. */
2302 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
2303 LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
2304 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
2306 goto start_over;
2309 /* Function vect_analyze_loop.
2311 Apply a set of analyses on LOOP, and create a loop_vec_info struct
2312 for it. The different analyses will record information in the
2313 loop_vec_info struct. If ORIG_LOOP_VINFO is not NULL epilogue must
2314 be vectorized. */
2315 loop_vec_info
2316 vect_analyze_loop (struct loop *loop, loop_vec_info orig_loop_vinfo)
2318 loop_vec_info loop_vinfo;
2319 unsigned int vector_sizes;
2321 /* Autodetect first vector size we try. */
2322 current_vector_size = 0;
2323 vector_sizes = targetm.vectorize.autovectorize_vector_sizes ();
2325 if (dump_enabled_p ())
2326 dump_printf_loc (MSG_NOTE, vect_location,
2327 "===== analyze_loop_nest =====\n");
2329 if (loop_outer (loop)
2330 && loop_vec_info_for_loop (loop_outer (loop))
2331 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
2333 if (dump_enabled_p ())
2334 dump_printf_loc (MSG_NOTE, vect_location,
2335 "outer-loop already vectorized.\n");
2336 return NULL;
2339 while (1)
2341 /* Check the CFG characteristics of the loop (nesting, entry/exit). */
2342 loop_vinfo = vect_analyze_loop_form (loop);
2343 if (!loop_vinfo)
2345 if (dump_enabled_p ())
2346 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2347 "bad loop form.\n");
2348 return NULL;
2351 bool fatal = false;
2353 if (orig_loop_vinfo)
2354 LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo) = orig_loop_vinfo;
2356 if (vect_analyze_loop_2 (loop_vinfo, fatal))
2358 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
2360 return loop_vinfo;
2363 delete loop_vinfo;
2365 vector_sizes &= ~current_vector_size;
2366 if (fatal
2367 || vector_sizes == 0
2368 || current_vector_size == 0)
2369 return NULL;
2371 /* Try the next biggest vector size. */
2372 current_vector_size = 1 << floor_log2 (vector_sizes);
2373 if (dump_enabled_p ())
2374 dump_printf_loc (MSG_NOTE, vect_location,
2375 "***** Re-trying analysis with "
2376 "vector size %d\n", current_vector_size);
2381 /* Function reduction_fn_for_scalar_code
2383 Input:
2384 CODE - tree_code of a reduction operations.
2386 Output:
2387 REDUC_FN - the corresponding internal function to be used to reduce the
2388 vector of partial results into a single scalar result, or IFN_LAST
2389 if the operation is a supported reduction operation, but does not have
2390 such an internal function.
2392 Return FALSE if CODE currently cannot be vectorized as reduction. */
2394 static bool
2395 reduction_fn_for_scalar_code (enum tree_code code, internal_fn *reduc_fn)
2397 switch (code)
2399 case MAX_EXPR:
2400 *reduc_fn = IFN_REDUC_MAX;
2401 return true;
2403 case MIN_EXPR:
2404 *reduc_fn = IFN_REDUC_MIN;
2405 return true;
2407 case PLUS_EXPR:
2408 *reduc_fn = IFN_REDUC_PLUS;
2409 return true;
2411 case MULT_EXPR:
2412 case MINUS_EXPR:
2413 case BIT_IOR_EXPR:
2414 case BIT_XOR_EXPR:
2415 case BIT_AND_EXPR:
2416 *reduc_fn = IFN_LAST;
2417 return true;
2419 default:
2420 return false;
2425 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
2426 STMT is printed with a message MSG. */
2428 static void
2429 report_vect_op (dump_flags_t msg_type, gimple *stmt, const char *msg)
2431 dump_printf_loc (msg_type, vect_location, "%s", msg);
2432 dump_gimple_stmt (msg_type, TDF_SLIM, stmt, 0);
2436 /* Detect SLP reduction of the form:
2438 #a1 = phi <a5, a0>
2439 a2 = operation (a1)
2440 a3 = operation (a2)
2441 a4 = operation (a3)
2442 a5 = operation (a4)
2444 #a = phi <a5>
2446 PHI is the reduction phi node (#a1 = phi <a5, a0> above)
2447 FIRST_STMT is the first reduction stmt in the chain
2448 (a2 = operation (a1)).
2450 Return TRUE if a reduction chain was detected. */
2452 static bool
2453 vect_is_slp_reduction (loop_vec_info loop_info, gimple *phi,
2454 gimple *first_stmt)
2456 struct loop *loop = (gimple_bb (phi))->loop_father;
2457 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2458 enum tree_code code;
2459 gimple *current_stmt = NULL, *loop_use_stmt = NULL, *first, *next_stmt;
2460 stmt_vec_info use_stmt_info, current_stmt_info;
2461 tree lhs;
2462 imm_use_iterator imm_iter;
2463 use_operand_p use_p;
2464 int nloop_uses, size = 0, n_out_of_loop_uses;
2465 bool found = false;
2467 if (loop != vect_loop)
2468 return false;
2470 lhs = PHI_RESULT (phi);
2471 code = gimple_assign_rhs_code (first_stmt);
2472 while (1)
2474 nloop_uses = 0;
2475 n_out_of_loop_uses = 0;
2476 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2478 gimple *use_stmt = USE_STMT (use_p);
2479 if (is_gimple_debug (use_stmt))
2480 continue;
2482 /* Check if we got back to the reduction phi. */
2483 if (use_stmt == phi)
2485 loop_use_stmt = use_stmt;
2486 found = true;
2487 break;
2490 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2492 loop_use_stmt = use_stmt;
2493 nloop_uses++;
2495 else
2496 n_out_of_loop_uses++;
2498 /* There are can be either a single use in the loop or two uses in
2499 phi nodes. */
2500 if (nloop_uses > 1 || (n_out_of_loop_uses && nloop_uses))
2501 return false;
2504 if (found)
2505 break;
2507 /* We reached a statement with no loop uses. */
2508 if (nloop_uses == 0)
2509 return false;
2511 /* This is a loop exit phi, and we haven't reached the reduction phi. */
2512 if (gimple_code (loop_use_stmt) == GIMPLE_PHI)
2513 return false;
2515 if (!is_gimple_assign (loop_use_stmt)
2516 || code != gimple_assign_rhs_code (loop_use_stmt)
2517 || !flow_bb_inside_loop_p (loop, gimple_bb (loop_use_stmt)))
2518 return false;
2520 /* Insert USE_STMT into reduction chain. */
2521 use_stmt_info = vinfo_for_stmt (loop_use_stmt);
2522 if (current_stmt)
2524 current_stmt_info = vinfo_for_stmt (current_stmt);
2525 GROUP_NEXT_ELEMENT (current_stmt_info) = loop_use_stmt;
2526 GROUP_FIRST_ELEMENT (use_stmt_info)
2527 = GROUP_FIRST_ELEMENT (current_stmt_info);
2529 else
2530 GROUP_FIRST_ELEMENT (use_stmt_info) = loop_use_stmt;
2532 lhs = gimple_assign_lhs (loop_use_stmt);
2533 current_stmt = loop_use_stmt;
2534 size++;
2537 if (!found || loop_use_stmt != phi || size < 2)
2538 return false;
2540 /* Swap the operands, if needed, to make the reduction operand be the second
2541 operand. */
2542 lhs = PHI_RESULT (phi);
2543 next_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2544 while (next_stmt)
2546 if (gimple_assign_rhs2 (next_stmt) == lhs)
2548 tree op = gimple_assign_rhs1 (next_stmt);
2549 gimple *def_stmt = NULL;
2551 if (TREE_CODE (op) == SSA_NAME)
2552 def_stmt = SSA_NAME_DEF_STMT (op);
2554 /* Check that the other def is either defined in the loop
2555 ("vect_internal_def"), or it's an induction (defined by a
2556 loop-header phi-node). */
2557 if (def_stmt
2558 && gimple_bb (def_stmt)
2559 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2560 && (is_gimple_assign (def_stmt)
2561 || is_gimple_call (def_stmt)
2562 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2563 == vect_induction_def
2564 || (gimple_code (def_stmt) == GIMPLE_PHI
2565 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2566 == vect_internal_def
2567 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2569 lhs = gimple_assign_lhs (next_stmt);
2570 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2571 continue;
2574 return false;
2576 else
2578 tree op = gimple_assign_rhs2 (next_stmt);
2579 gimple *def_stmt = NULL;
2581 if (TREE_CODE (op) == SSA_NAME)
2582 def_stmt = SSA_NAME_DEF_STMT (op);
2584 /* Check that the other def is either defined in the loop
2585 ("vect_internal_def"), or it's an induction (defined by a
2586 loop-header phi-node). */
2587 if (def_stmt
2588 && gimple_bb (def_stmt)
2589 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2590 && (is_gimple_assign (def_stmt)
2591 || is_gimple_call (def_stmt)
2592 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2593 == vect_induction_def
2594 || (gimple_code (def_stmt) == GIMPLE_PHI
2595 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2596 == vect_internal_def
2597 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2599 if (dump_enabled_p ())
2601 dump_printf_loc (MSG_NOTE, vect_location, "swapping oprnds: ");
2602 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, next_stmt, 0);
2605 swap_ssa_operands (next_stmt,
2606 gimple_assign_rhs1_ptr (next_stmt),
2607 gimple_assign_rhs2_ptr (next_stmt));
2608 update_stmt (next_stmt);
2610 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (next_stmt)))
2611 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2613 else
2614 return false;
2617 lhs = gimple_assign_lhs (next_stmt);
2618 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2621 /* Save the chain for further analysis in SLP detection. */
2622 first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2623 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (first);
2624 GROUP_SIZE (vinfo_for_stmt (first)) = size;
2626 return true;
2630 /* Return true if the reduction PHI in LOOP with latch arg LOOP_ARG and
2631 reduction operation CODE has a handled computation expression. */
2633 bool
2634 check_reduction_path (location_t loc, loop_p loop, gphi *phi, tree loop_arg,
2635 enum tree_code code)
2637 auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
2638 auto_bitmap visited;
2639 tree lookfor = PHI_RESULT (phi);
2640 ssa_op_iter curri;
2641 use_operand_p curr = op_iter_init_phiuse (&curri, phi, SSA_OP_USE);
2642 while (USE_FROM_PTR (curr) != loop_arg)
2643 curr = op_iter_next_use (&curri);
2644 curri.i = curri.numops;
2647 path.safe_push (std::make_pair (curri, curr));
2648 tree use = USE_FROM_PTR (curr);
2649 if (use == lookfor)
2650 break;
2651 gimple *def = SSA_NAME_DEF_STMT (use);
2652 if (gimple_nop_p (def)
2653 || ! flow_bb_inside_loop_p (loop, gimple_bb (def)))
2655 pop:
2658 std::pair<ssa_op_iter, use_operand_p> x = path.pop ();
2659 curri = x.first;
2660 curr = x.second;
2662 curr = op_iter_next_use (&curri);
2663 /* Skip already visited or non-SSA operands (from iterating
2664 over PHI args). */
2665 while (curr != NULL_USE_OPERAND_P
2666 && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
2667 || ! bitmap_set_bit (visited,
2668 SSA_NAME_VERSION
2669 (USE_FROM_PTR (curr)))));
2671 while (curr == NULL_USE_OPERAND_P && ! path.is_empty ());
2672 if (curr == NULL_USE_OPERAND_P)
2673 break;
2675 else
2677 if (gimple_code (def) == GIMPLE_PHI)
2678 curr = op_iter_init_phiuse (&curri, as_a <gphi *>(def), SSA_OP_USE);
2679 else
2680 curr = op_iter_init_use (&curri, def, SSA_OP_USE);
2681 while (curr != NULL_USE_OPERAND_P
2682 && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
2683 || ! bitmap_set_bit (visited,
2684 SSA_NAME_VERSION
2685 (USE_FROM_PTR (curr)))))
2686 curr = op_iter_next_use (&curri);
2687 if (curr == NULL_USE_OPERAND_P)
2688 goto pop;
2691 while (1);
2692 if (dump_file && (dump_flags & TDF_DETAILS))
2694 dump_printf_loc (MSG_NOTE, loc, "reduction path: ");
2695 unsigned i;
2696 std::pair<ssa_op_iter, use_operand_p> *x;
2697 FOR_EACH_VEC_ELT (path, i, x)
2699 dump_generic_expr (MSG_NOTE, TDF_SLIM, USE_FROM_PTR (x->second));
2700 dump_printf (MSG_NOTE, " ");
2702 dump_printf (MSG_NOTE, "\n");
2705 /* Check whether the reduction path detected is valid. */
2706 bool fail = path.length () == 0;
2707 bool neg = false;
2708 for (unsigned i = 1; i < path.length (); ++i)
2710 gimple *use_stmt = USE_STMT (path[i].second);
2711 tree op = USE_FROM_PTR (path[i].second);
2712 if (! has_single_use (op)
2713 || ! is_gimple_assign (use_stmt))
2715 fail = true;
2716 break;
2718 if (gimple_assign_rhs_code (use_stmt) != code)
2720 if (code == PLUS_EXPR
2721 && gimple_assign_rhs_code (use_stmt) == MINUS_EXPR)
2723 /* Track whether we negate the reduction value each iteration. */
2724 if (gimple_assign_rhs2 (use_stmt) == op)
2725 neg = ! neg;
2727 else
2729 fail = true;
2730 break;
2734 return ! fail && ! neg;
2738 /* Function vect_is_simple_reduction
2740 (1) Detect a cross-iteration def-use cycle that represents a simple
2741 reduction computation. We look for the following pattern:
2743 loop_header:
2744 a1 = phi < a0, a2 >
2745 a3 = ...
2746 a2 = operation (a3, a1)
2750 a3 = ...
2751 loop_header:
2752 a1 = phi < a0, a2 >
2753 a2 = operation (a3, a1)
2755 such that:
2756 1. operation is commutative and associative and it is safe to
2757 change the order of the computation
2758 2. no uses for a2 in the loop (a2 is used out of the loop)
2759 3. no uses of a1 in the loop besides the reduction operation
2760 4. no uses of a1 outside the loop.
2762 Conditions 1,4 are tested here.
2763 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
2765 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
2766 nested cycles.
2768 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
2769 reductions:
2771 a1 = phi < a0, a2 >
2772 inner loop (def of a3)
2773 a2 = phi < a3 >
2775 (4) Detect condition expressions, ie:
2776 for (int i = 0; i < N; i++)
2777 if (a[i] < val)
2778 ret_val = a[i];
2782 static gimple *
2783 vect_is_simple_reduction (loop_vec_info loop_info, gimple *phi,
2784 bool *double_reduc,
2785 bool need_wrapping_integral_overflow,
2786 enum vect_reduction_type *v_reduc_type)
2788 struct loop *loop = (gimple_bb (phi))->loop_father;
2789 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2790 gimple *def_stmt, *def1 = NULL, *def2 = NULL, *phi_use_stmt = NULL;
2791 enum tree_code orig_code, code;
2792 tree op1, op2, op3 = NULL_TREE, op4 = NULL_TREE;
2793 tree type;
2794 int nloop_uses;
2795 tree name;
2796 imm_use_iterator imm_iter;
2797 use_operand_p use_p;
2798 bool phi_def;
2800 *double_reduc = false;
2801 *v_reduc_type = TREE_CODE_REDUCTION;
2803 tree phi_name = PHI_RESULT (phi);
2804 /* ??? If there are no uses of the PHI result the inner loop reduction
2805 won't be detected as possibly double-reduction by vectorizable_reduction
2806 because that tries to walk the PHI arg from the preheader edge which
2807 can be constant. See PR60382. */
2808 if (has_zero_uses (phi_name))
2809 return NULL;
2810 nloop_uses = 0;
2811 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, phi_name)
2813 gimple *use_stmt = USE_STMT (use_p);
2814 if (is_gimple_debug (use_stmt))
2815 continue;
2817 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2819 if (dump_enabled_p ())
2820 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2821 "intermediate value used outside loop.\n");
2823 return NULL;
2826 nloop_uses++;
2827 if (nloop_uses > 1)
2829 if (dump_enabled_p ())
2830 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2831 "reduction value used in loop.\n");
2832 return NULL;
2835 phi_use_stmt = use_stmt;
2838 edge latch_e = loop_latch_edge (loop);
2839 tree loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
2840 if (TREE_CODE (loop_arg) != SSA_NAME)
2842 if (dump_enabled_p ())
2844 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2845 "reduction: not ssa_name: ");
2846 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, loop_arg);
2847 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
2849 return NULL;
2852 def_stmt = SSA_NAME_DEF_STMT (loop_arg);
2853 if (is_gimple_assign (def_stmt))
2855 name = gimple_assign_lhs (def_stmt);
2856 phi_def = false;
2858 else if (gimple_code (def_stmt) == GIMPLE_PHI)
2860 name = PHI_RESULT (def_stmt);
2861 phi_def = true;
2863 else
2865 if (dump_enabled_p ())
2867 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2868 "reduction: unhandled reduction operation: ");
2869 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, def_stmt, 0);
2871 return NULL;
2874 if (! flow_bb_inside_loop_p (loop, gimple_bb (def_stmt)))
2875 return NULL;
2877 nloop_uses = 0;
2878 auto_vec<gphi *, 3> lcphis;
2879 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2881 gimple *use_stmt = USE_STMT (use_p);
2882 if (is_gimple_debug (use_stmt))
2883 continue;
2884 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2885 nloop_uses++;
2886 else
2887 /* We can have more than one loop-closed PHI. */
2888 lcphis.safe_push (as_a <gphi *> (use_stmt));
2889 if (nloop_uses > 1)
2891 if (dump_enabled_p ())
2892 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2893 "reduction used in loop.\n");
2894 return NULL;
2898 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
2899 defined in the inner loop. */
2900 if (phi_def)
2902 op1 = PHI_ARG_DEF (def_stmt, 0);
2904 if (gimple_phi_num_args (def_stmt) != 1
2905 || TREE_CODE (op1) != SSA_NAME)
2907 if (dump_enabled_p ())
2908 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2909 "unsupported phi node definition.\n");
2911 return NULL;
2914 def1 = SSA_NAME_DEF_STMT (op1);
2915 if (gimple_bb (def1)
2916 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2917 && loop->inner
2918 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
2919 && is_gimple_assign (def1)
2920 && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt)))
2922 if (dump_enabled_p ())
2923 report_vect_op (MSG_NOTE, def_stmt,
2924 "detected double reduction: ");
2926 *double_reduc = true;
2927 return def_stmt;
2930 return NULL;
2933 /* If we are vectorizing an inner reduction we are executing that
2934 in the original order only in case we are not dealing with a
2935 double reduction. */
2936 bool check_reduction = true;
2937 if (flow_loop_nested_p (vect_loop, loop))
2939 gphi *lcphi;
2940 unsigned i;
2941 check_reduction = false;
2942 FOR_EACH_VEC_ELT (lcphis, i, lcphi)
2943 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, gimple_phi_result (lcphi))
2945 gimple *use_stmt = USE_STMT (use_p);
2946 if (is_gimple_debug (use_stmt))
2947 continue;
2948 if (! flow_bb_inside_loop_p (vect_loop, gimple_bb (use_stmt)))
2949 check_reduction = true;
2953 bool nested_in_vect_loop = flow_loop_nested_p (vect_loop, loop);
2954 code = orig_code = gimple_assign_rhs_code (def_stmt);
2956 /* We can handle "res -= x[i]", which is non-associative by
2957 simply rewriting this into "res += -x[i]". Avoid changing
2958 gimple instruction for the first simple tests and only do this
2959 if we're allowed to change code at all. */
2960 if (code == MINUS_EXPR && gimple_assign_rhs2 (def_stmt) != phi_name)
2961 code = PLUS_EXPR;
2963 if (code == COND_EXPR)
2965 if (! nested_in_vect_loop)
2966 *v_reduc_type = COND_REDUCTION;
2968 op3 = gimple_assign_rhs1 (def_stmt);
2969 if (COMPARISON_CLASS_P (op3))
2971 op4 = TREE_OPERAND (op3, 1);
2972 op3 = TREE_OPERAND (op3, 0);
2974 if (op3 == phi_name || op4 == phi_name)
2976 if (dump_enabled_p ())
2977 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2978 "reduction: condition depends on previous"
2979 " iteration: ");
2980 return NULL;
2983 op1 = gimple_assign_rhs2 (def_stmt);
2984 op2 = gimple_assign_rhs3 (def_stmt);
2986 else if (!commutative_tree_code (code) || !associative_tree_code (code))
2988 if (dump_enabled_p ())
2989 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2990 "reduction: not commutative/associative: ");
2991 return NULL;
2993 else if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
2995 op1 = gimple_assign_rhs1 (def_stmt);
2996 op2 = gimple_assign_rhs2 (def_stmt);
2998 else
3000 if (dump_enabled_p ())
3001 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3002 "reduction: not handled operation: ");
3003 return NULL;
3006 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
3008 if (dump_enabled_p ())
3009 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3010 "reduction: both uses not ssa_names: ");
3012 return NULL;
3015 type = TREE_TYPE (gimple_assign_lhs (def_stmt));
3016 if ((TREE_CODE (op1) == SSA_NAME
3017 && !types_compatible_p (type,TREE_TYPE (op1)))
3018 || (TREE_CODE (op2) == SSA_NAME
3019 && !types_compatible_p (type, TREE_TYPE (op2)))
3020 || (op3 && TREE_CODE (op3) == SSA_NAME
3021 && !types_compatible_p (type, TREE_TYPE (op3)))
3022 || (op4 && TREE_CODE (op4) == SSA_NAME
3023 && !types_compatible_p (type, TREE_TYPE (op4))))
3025 if (dump_enabled_p ())
3027 dump_printf_loc (MSG_NOTE, vect_location,
3028 "reduction: multiple types: operation type: ");
3029 dump_generic_expr (MSG_NOTE, TDF_SLIM, type);
3030 dump_printf (MSG_NOTE, ", operands types: ");
3031 dump_generic_expr (MSG_NOTE, TDF_SLIM,
3032 TREE_TYPE (op1));
3033 dump_printf (MSG_NOTE, ",");
3034 dump_generic_expr (MSG_NOTE, TDF_SLIM,
3035 TREE_TYPE (op2));
3036 if (op3)
3038 dump_printf (MSG_NOTE, ",");
3039 dump_generic_expr (MSG_NOTE, TDF_SLIM,
3040 TREE_TYPE (op3));
3043 if (op4)
3045 dump_printf (MSG_NOTE, ",");
3046 dump_generic_expr (MSG_NOTE, TDF_SLIM,
3047 TREE_TYPE (op4));
3049 dump_printf (MSG_NOTE, "\n");
3052 return NULL;
3055 /* Check that it's ok to change the order of the computation.
3056 Generally, when vectorizing a reduction we change the order of the
3057 computation. This may change the behavior of the program in some
3058 cases, so we need to check that this is ok. One exception is when
3059 vectorizing an outer-loop: the inner-loop is executed sequentially,
3060 and therefore vectorizing reductions in the inner-loop during
3061 outer-loop vectorization is safe. */
3063 if (*v_reduc_type != COND_REDUCTION
3064 && check_reduction)
3066 /* CHECKME: check for !flag_finite_math_only too? */
3067 if (SCALAR_FLOAT_TYPE_P (type) && !flag_associative_math)
3069 /* Changing the order of operations changes the semantics. */
3070 if (dump_enabled_p ())
3071 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3072 "reduction: unsafe fp math optimization: ");
3073 return NULL;
3075 else if (INTEGRAL_TYPE_P (type))
3077 if (!operation_no_trapping_overflow (type, code))
3079 /* Changing the order of operations changes the semantics. */
3080 if (dump_enabled_p ())
3081 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3082 "reduction: unsafe int math optimization"
3083 " (overflow traps): ");
3084 return NULL;
3086 if (need_wrapping_integral_overflow
3087 && !TYPE_OVERFLOW_WRAPS (type)
3088 && operation_can_overflow (code))
3090 /* Changing the order of operations changes the semantics. */
3091 if (dump_enabled_p ())
3092 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3093 "reduction: unsafe int math optimization"
3094 " (overflow doesn't wrap): ");
3095 return NULL;
3098 else if (SAT_FIXED_POINT_TYPE_P (type))
3100 /* Changing the order of operations changes the semantics. */
3101 if (dump_enabled_p ())
3102 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3103 "reduction: unsafe fixed-point math optimization: ");
3104 return NULL;
3108 /* Reduction is safe. We're dealing with one of the following:
3109 1) integer arithmetic and no trapv
3110 2) floating point arithmetic, and special flags permit this optimization
3111 3) nested cycle (i.e., outer loop vectorization). */
3112 if (TREE_CODE (op1) == SSA_NAME)
3113 def1 = SSA_NAME_DEF_STMT (op1);
3115 if (TREE_CODE (op2) == SSA_NAME)
3116 def2 = SSA_NAME_DEF_STMT (op2);
3118 if (code != COND_EXPR
3119 && ((!def1 || gimple_nop_p (def1)) && (!def2 || gimple_nop_p (def2))))
3121 if (dump_enabled_p ())
3122 report_vect_op (MSG_NOTE, def_stmt, "reduction: no defs for operands: ");
3123 return NULL;
3126 /* Check that one def is the reduction def, defined by PHI,
3127 the other def is either defined in the loop ("vect_internal_def"),
3128 or it's an induction (defined by a loop-header phi-node). */
3130 if (def2 && def2 == phi
3131 && (code == COND_EXPR
3132 || !def1 || gimple_nop_p (def1)
3133 || !flow_bb_inside_loop_p (loop, gimple_bb (def1))
3134 || (def1 && flow_bb_inside_loop_p (loop, gimple_bb (def1))
3135 && (is_gimple_assign (def1)
3136 || is_gimple_call (def1)
3137 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
3138 == vect_induction_def
3139 || (gimple_code (def1) == GIMPLE_PHI
3140 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
3141 == vect_internal_def
3142 && !is_loop_header_bb_p (gimple_bb (def1)))))))
3144 if (dump_enabled_p ())
3145 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3146 return def_stmt;
3149 if (def1 && def1 == phi
3150 && (code == COND_EXPR
3151 || !def2 || gimple_nop_p (def2)
3152 || !flow_bb_inside_loop_p (loop, gimple_bb (def2))
3153 || (def2 && flow_bb_inside_loop_p (loop, gimple_bb (def2))
3154 && (is_gimple_assign (def2)
3155 || is_gimple_call (def2)
3156 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3157 == vect_induction_def
3158 || (gimple_code (def2) == GIMPLE_PHI
3159 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
3160 == vect_internal_def
3161 && !is_loop_header_bb_p (gimple_bb (def2)))))))
3163 if (! nested_in_vect_loop && orig_code != MINUS_EXPR)
3165 /* Check if we can swap operands (just for simplicity - so that
3166 the rest of the code can assume that the reduction variable
3167 is always the last (second) argument). */
3168 if (code == COND_EXPR)
3170 /* Swap cond_expr by inverting the condition. */
3171 tree cond_expr = gimple_assign_rhs1 (def_stmt);
3172 enum tree_code invert_code = ERROR_MARK;
3173 enum tree_code cond_code = TREE_CODE (cond_expr);
3175 if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
3177 bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr, 0));
3178 invert_code = invert_tree_comparison (cond_code, honor_nans);
3180 if (invert_code != ERROR_MARK)
3182 TREE_SET_CODE (cond_expr, invert_code);
3183 swap_ssa_operands (def_stmt,
3184 gimple_assign_rhs2_ptr (def_stmt),
3185 gimple_assign_rhs3_ptr (def_stmt));
3187 else
3189 if (dump_enabled_p ())
3190 report_vect_op (MSG_NOTE, def_stmt,
3191 "detected reduction: cannot swap operands "
3192 "for cond_expr");
3193 return NULL;
3196 else
3197 swap_ssa_operands (def_stmt, gimple_assign_rhs1_ptr (def_stmt),
3198 gimple_assign_rhs2_ptr (def_stmt));
3200 if (dump_enabled_p ())
3201 report_vect_op (MSG_NOTE, def_stmt,
3202 "detected reduction: need to swap operands: ");
3204 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (def_stmt)))
3205 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
3207 else
3209 if (dump_enabled_p ())
3210 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3213 return def_stmt;
3216 /* Try to find SLP reduction chain. */
3217 if (! nested_in_vect_loop
3218 && code != COND_EXPR
3219 && orig_code != MINUS_EXPR
3220 && vect_is_slp_reduction (loop_info, phi, def_stmt))
3222 if (dump_enabled_p ())
3223 report_vect_op (MSG_NOTE, def_stmt,
3224 "reduction: detected reduction chain: ");
3226 return def_stmt;
3229 /* Dissolve group eventually half-built by vect_is_slp_reduction. */
3230 gimple *first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (def_stmt));
3231 while (first)
3233 gimple *next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (first));
3234 GROUP_FIRST_ELEMENT (vinfo_for_stmt (first)) = NULL;
3235 GROUP_NEXT_ELEMENT (vinfo_for_stmt (first)) = NULL;
3236 first = next;
3239 /* Look for the expression computing loop_arg from loop PHI result. */
3240 if (check_reduction_path (vect_location, loop, as_a <gphi *> (phi), loop_arg,
3241 code))
3242 return def_stmt;
3244 if (dump_enabled_p ())
3246 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3247 "reduction: unknown pattern: ");
3250 return NULL;
3253 /* Wrapper around vect_is_simple_reduction, which will modify code
3254 in-place if it enables detection of more reductions. Arguments
3255 as there. */
3257 gimple *
3258 vect_force_simple_reduction (loop_vec_info loop_info, gimple *phi,
3259 bool *double_reduc,
3260 bool need_wrapping_integral_overflow)
3262 enum vect_reduction_type v_reduc_type;
3263 gimple *def = vect_is_simple_reduction (loop_info, phi, double_reduc,
3264 need_wrapping_integral_overflow,
3265 &v_reduc_type);
3266 if (def)
3268 stmt_vec_info reduc_def_info = vinfo_for_stmt (phi);
3269 STMT_VINFO_REDUC_TYPE (reduc_def_info) = v_reduc_type;
3270 STMT_VINFO_REDUC_DEF (reduc_def_info) = def;
3271 reduc_def_info = vinfo_for_stmt (def);
3272 STMT_VINFO_REDUC_DEF (reduc_def_info) = phi;
3274 return def;
3277 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
3279 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
3280 int *peel_iters_epilogue,
3281 stmt_vector_for_cost *scalar_cost_vec,
3282 stmt_vector_for_cost *prologue_cost_vec,
3283 stmt_vector_for_cost *epilogue_cost_vec)
3285 int retval = 0;
3286 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3288 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
3290 *peel_iters_epilogue = vf/2;
3291 if (dump_enabled_p ())
3292 dump_printf_loc (MSG_NOTE, vect_location,
3293 "cost model: epilogue peel iters set to vf/2 "
3294 "because loop iterations are unknown .\n");
3296 /* If peeled iterations are known but number of scalar loop
3297 iterations are unknown, count a taken branch per peeled loop. */
3298 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3299 NULL, 0, vect_prologue);
3300 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3301 NULL, 0, vect_epilogue);
3303 else
3305 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
3306 peel_iters_prologue = niters < peel_iters_prologue ?
3307 niters : peel_iters_prologue;
3308 *peel_iters_epilogue = (niters - peel_iters_prologue) % vf;
3309 /* If we need to peel for gaps, but no peeling is required, we have to
3310 peel VF iterations. */
3311 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !*peel_iters_epilogue)
3312 *peel_iters_epilogue = vf;
3315 stmt_info_for_cost *si;
3316 int j;
3317 if (peel_iters_prologue)
3318 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3320 stmt_vec_info stmt_info
3321 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3322 retval += record_stmt_cost (prologue_cost_vec,
3323 si->count * peel_iters_prologue,
3324 si->kind, stmt_info, si->misalign,
3325 vect_prologue);
3327 if (*peel_iters_epilogue)
3328 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3330 stmt_vec_info stmt_info
3331 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3332 retval += record_stmt_cost (epilogue_cost_vec,
3333 si->count * *peel_iters_epilogue,
3334 si->kind, stmt_info, si->misalign,
3335 vect_epilogue);
3338 return retval;
3341 /* Function vect_estimate_min_profitable_iters
3343 Return the number of iterations required for the vector version of the
3344 loop to be profitable relative to the cost of the scalar version of the
3345 loop.
3347 *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
3348 of iterations for vectorization. -1 value means loop vectorization
3349 is not profitable. This returned value may be used for dynamic
3350 profitability check.
3352 *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
3353 for static check against estimated number of iterations. */
3355 static void
3356 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
3357 int *ret_min_profitable_niters,
3358 int *ret_min_profitable_estimate)
3360 int min_profitable_iters;
3361 int min_profitable_estimate;
3362 int peel_iters_prologue;
3363 int peel_iters_epilogue;
3364 unsigned vec_inside_cost = 0;
3365 int vec_outside_cost = 0;
3366 unsigned vec_prologue_cost = 0;
3367 unsigned vec_epilogue_cost = 0;
3368 int scalar_single_iter_cost = 0;
3369 int scalar_outside_cost = 0;
3370 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3371 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
3372 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3374 /* Cost model disabled. */
3375 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
3377 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
3378 *ret_min_profitable_niters = 0;
3379 *ret_min_profitable_estimate = 0;
3380 return;
3383 /* Requires loop versioning tests to handle misalignment. */
3384 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
3386 /* FIXME: Make cost depend on complexity of individual check. */
3387 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
3388 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3389 vect_prologue);
3390 dump_printf (MSG_NOTE,
3391 "cost model: Adding cost of checks for loop "
3392 "versioning to treat misalignment.\n");
3395 /* Requires loop versioning with alias checks. */
3396 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
3398 /* FIXME: Make cost depend on complexity of individual check. */
3399 unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
3400 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3401 vect_prologue);
3402 len = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).length ();
3403 if (len)
3404 /* Count LEN - 1 ANDs and LEN comparisons. */
3405 (void) add_stmt_cost (target_cost_data, len * 2 - 1, scalar_stmt,
3406 NULL, 0, vect_prologue);
3407 dump_printf (MSG_NOTE,
3408 "cost model: Adding cost of checks for loop "
3409 "versioning aliasing.\n");
3412 /* Requires loop versioning with niter checks. */
3413 if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
3415 /* FIXME: Make cost depend on complexity of individual check. */
3416 (void) add_stmt_cost (target_cost_data, 1, vector_stmt, NULL, 0,
3417 vect_prologue);
3418 dump_printf (MSG_NOTE,
3419 "cost model: Adding cost of checks for loop "
3420 "versioning niters.\n");
3423 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3424 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken, NULL, 0,
3425 vect_prologue);
3427 /* Count statements in scalar loop. Using this as scalar cost for a single
3428 iteration for now.
3430 TODO: Add outer loop support.
3432 TODO: Consider assigning different costs to different scalar
3433 statements. */
3435 scalar_single_iter_cost
3436 = LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo);
3438 /* Add additional cost for the peeled instructions in prologue and epilogue
3439 loop.
3441 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
3442 at compile-time - we assume it's vf/2 (the worst would be vf-1).
3444 TODO: Build an expression that represents peel_iters for prologue and
3445 epilogue to be used in a run-time test. */
3447 if (npeel < 0)
3449 peel_iters_prologue = vf/2;
3450 dump_printf (MSG_NOTE, "cost model: "
3451 "prologue peel iters set to vf/2.\n");
3453 /* If peeling for alignment is unknown, loop bound of main loop becomes
3454 unknown. */
3455 peel_iters_epilogue = vf/2;
3456 dump_printf (MSG_NOTE, "cost model: "
3457 "epilogue peel iters set to vf/2 because "
3458 "peeling for alignment is unknown.\n");
3460 /* If peeled iterations are unknown, count a taken branch and a not taken
3461 branch per peeled loop. Even if scalar loop iterations are known,
3462 vector iterations are not known since peeled prologue iterations are
3463 not known. Hence guards remain the same. */
3464 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3465 NULL, 0, vect_prologue);
3466 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3467 NULL, 0, vect_prologue);
3468 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3469 NULL, 0, vect_epilogue);
3470 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3471 NULL, 0, vect_epilogue);
3472 stmt_info_for_cost *si;
3473 int j;
3474 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
3476 struct _stmt_vec_info *stmt_info
3477 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3478 (void) add_stmt_cost (target_cost_data,
3479 si->count * peel_iters_prologue,
3480 si->kind, stmt_info, si->misalign,
3481 vect_prologue);
3482 (void) add_stmt_cost (target_cost_data,
3483 si->count * peel_iters_epilogue,
3484 si->kind, stmt_info, si->misalign,
3485 vect_epilogue);
3488 else
3490 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
3491 stmt_info_for_cost *si;
3492 int j;
3493 void *data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3495 prologue_cost_vec.create (2);
3496 epilogue_cost_vec.create (2);
3497 peel_iters_prologue = npeel;
3499 (void) vect_get_known_peeling_cost (loop_vinfo, peel_iters_prologue,
3500 &peel_iters_epilogue,
3501 &LOOP_VINFO_SCALAR_ITERATION_COST
3502 (loop_vinfo),
3503 &prologue_cost_vec,
3504 &epilogue_cost_vec);
3506 FOR_EACH_VEC_ELT (prologue_cost_vec, j, si)
3508 struct _stmt_vec_info *stmt_info
3509 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3510 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3511 si->misalign, vect_prologue);
3514 FOR_EACH_VEC_ELT (epilogue_cost_vec, j, si)
3516 struct _stmt_vec_info *stmt_info
3517 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3518 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3519 si->misalign, vect_epilogue);
3522 prologue_cost_vec.release ();
3523 epilogue_cost_vec.release ();
3526 /* FORNOW: The scalar outside cost is incremented in one of the
3527 following ways:
3529 1. The vectorizer checks for alignment and aliasing and generates
3530 a condition that allows dynamic vectorization. A cost model
3531 check is ANDED with the versioning condition. Hence scalar code
3532 path now has the added cost of the versioning check.
3534 if (cost > th & versioning_check)
3535 jmp to vector code
3537 Hence run-time scalar is incremented by not-taken branch cost.
3539 2. The vectorizer then checks if a prologue is required. If the
3540 cost model check was not done before during versioning, it has to
3541 be done before the prologue check.
3543 if (cost <= th)
3544 prologue = scalar_iters
3545 if (prologue == 0)
3546 jmp to vector code
3547 else
3548 execute prologue
3549 if (prologue == num_iters)
3550 go to exit
3552 Hence the run-time scalar cost is incremented by a taken branch,
3553 plus a not-taken branch, plus a taken branch cost.
3555 3. The vectorizer then checks if an epilogue is required. If the
3556 cost model check was not done before during prologue check, it
3557 has to be done with the epilogue check.
3559 if (prologue == 0)
3560 jmp to vector code
3561 else
3562 execute prologue
3563 if (prologue == num_iters)
3564 go to exit
3565 vector code:
3566 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
3567 jmp to epilogue
3569 Hence the run-time scalar cost should be incremented by 2 taken
3570 branches.
3572 TODO: The back end may reorder the BBS's differently and reverse
3573 conditions/branch directions. Change the estimates below to
3574 something more reasonable. */
3576 /* If the number of iterations is known and we do not do versioning, we can
3577 decide whether to vectorize at compile time. Hence the scalar version
3578 do not carry cost model guard costs. */
3579 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3580 || LOOP_REQUIRES_VERSIONING (loop_vinfo))
3582 /* Cost model check occurs at versioning. */
3583 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3584 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
3585 else
3587 /* Cost model check occurs at prologue generation. */
3588 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
3589 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
3590 + vect_get_stmt_cost (cond_branch_not_taken);
3591 /* Cost model check occurs at epilogue generation. */
3592 else
3593 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
3597 /* Complete the target-specific cost calculations. */
3598 finish_cost (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo), &vec_prologue_cost,
3599 &vec_inside_cost, &vec_epilogue_cost);
3601 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
3603 if (dump_enabled_p ())
3605 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
3606 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
3607 vec_inside_cost);
3608 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
3609 vec_prologue_cost);
3610 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
3611 vec_epilogue_cost);
3612 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
3613 scalar_single_iter_cost);
3614 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
3615 scalar_outside_cost);
3616 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
3617 vec_outside_cost);
3618 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
3619 peel_iters_prologue);
3620 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
3621 peel_iters_epilogue);
3624 /* Calculate number of iterations required to make the vector version
3625 profitable, relative to the loop bodies only. The following condition
3626 must hold true:
3627 SIC * niters + SOC > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC
3628 where
3629 SIC = scalar iteration cost, VIC = vector iteration cost,
3630 VOC = vector outside cost, VF = vectorization factor,
3631 PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations
3632 SOC = scalar outside cost for run time cost model check. */
3634 if ((scalar_single_iter_cost * vf) > (int) vec_inside_cost)
3636 if (vec_outside_cost <= 0)
3637 min_profitable_iters = 0;
3638 else
3640 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost) * vf
3641 - vec_inside_cost * peel_iters_prologue
3642 - vec_inside_cost * peel_iters_epilogue)
3643 / ((scalar_single_iter_cost * vf)
3644 - vec_inside_cost);
3646 if ((scalar_single_iter_cost * vf * min_profitable_iters)
3647 <= (((int) vec_inside_cost * min_profitable_iters)
3648 + (((int) vec_outside_cost - scalar_outside_cost) * vf)))
3649 min_profitable_iters++;
3652 /* vector version will never be profitable. */
3653 else
3655 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
3656 warning_at (vect_location, OPT_Wopenmp_simd, "vectorization "
3657 "did not happen for a simd loop");
3659 if (dump_enabled_p ())
3660 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3661 "cost model: the vector iteration cost = %d "
3662 "divided by the scalar iteration cost = %d "
3663 "is greater or equal to the vectorization factor = %d"
3664 ".\n",
3665 vec_inside_cost, scalar_single_iter_cost, vf);
3666 *ret_min_profitable_niters = -1;
3667 *ret_min_profitable_estimate = -1;
3668 return;
3671 dump_printf (MSG_NOTE,
3672 " Calculated minimum iters for profitability: %d\n",
3673 min_profitable_iters);
3675 /* We want the vectorized loop to execute at least once. */
3676 if (min_profitable_iters < (vf + peel_iters_prologue))
3677 min_profitable_iters = vf + peel_iters_prologue;
3679 if (dump_enabled_p ())
3680 dump_printf_loc (MSG_NOTE, vect_location,
3681 " Runtime profitability threshold = %d\n",
3682 min_profitable_iters);
3684 *ret_min_profitable_niters = min_profitable_iters;
3686 /* Calculate number of iterations required to make the vector version
3687 profitable, relative to the loop bodies only.
3689 Non-vectorized variant is SIC * niters and it must win over vector
3690 variant on the expected loop trip count. The following condition must hold true:
3691 SIC * niters > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC + SOC */
3693 if (vec_outside_cost <= 0)
3694 min_profitable_estimate = 0;
3695 else
3697 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost) * vf
3698 - vec_inside_cost * peel_iters_prologue
3699 - vec_inside_cost * peel_iters_epilogue)
3700 / ((scalar_single_iter_cost * vf)
3701 - vec_inside_cost);
3703 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
3704 if (dump_enabled_p ())
3705 dump_printf_loc (MSG_NOTE, vect_location,
3706 " Static estimate profitability threshold = %d\n",
3707 min_profitable_estimate);
3709 *ret_min_profitable_estimate = min_profitable_estimate;
3712 /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
3713 vector elements (not bits) for a vector with NELT elements. */
3714 static void
3715 calc_vec_perm_mask_for_shift (unsigned int offset, unsigned int nelt,
3716 vec_perm_indices *sel)
3718 unsigned int i;
3720 for (i = 0; i < nelt; i++)
3721 sel->quick_push ((i + offset) & (2 * nelt - 1));
3724 /* Checks whether the target supports whole-vector shifts for vectors of mode
3725 MODE. This is the case if _either_ the platform handles vec_shr_optab, _or_
3726 it supports vec_perm_const with masks for all necessary shift amounts. */
3727 static bool
3728 have_whole_vector_shift (machine_mode mode)
3730 if (optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
3731 return true;
3733 if (direct_optab_handler (vec_perm_const_optab, mode) == CODE_FOR_nothing)
3734 return false;
3736 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3737 auto_vec_perm_indices sel (nelt);
3739 for (i = nelt/2; i >= 1; i/=2)
3741 sel.truncate (0);
3742 calc_vec_perm_mask_for_shift (i, nelt, &sel);
3743 if (!can_vec_perm_p (mode, false, &sel))
3744 return false;
3746 return true;
3749 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
3750 functions. Design better to avoid maintenance issues. */
3752 /* Function vect_model_reduction_cost.
3754 Models cost for a reduction operation, including the vector ops
3755 generated within the strip-mine loop, the initial definition before
3756 the loop, and the epilogue code that must be generated. */
3758 static void
3759 vect_model_reduction_cost (stmt_vec_info stmt_info, internal_fn reduc_fn,
3760 int ncopies)
3762 int prologue_cost = 0, epilogue_cost = 0;
3763 enum tree_code code;
3764 optab optab;
3765 tree vectype;
3766 gimple *orig_stmt;
3767 machine_mode mode;
3768 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3769 struct loop *loop = NULL;
3770 void *target_cost_data;
3772 if (loop_vinfo)
3774 loop = LOOP_VINFO_LOOP (loop_vinfo);
3775 target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3777 else
3778 target_cost_data = BB_VINFO_TARGET_COST_DATA (STMT_VINFO_BB_VINFO (stmt_info));
3780 /* Condition reductions generate two reductions in the loop. */
3781 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3782 ncopies *= 2;
3784 /* Cost of reduction op inside loop. */
3785 unsigned inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3786 stmt_info, 0, vect_body);
3788 vectype = STMT_VINFO_VECTYPE (stmt_info);
3789 mode = TYPE_MODE (vectype);
3790 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
3792 if (!orig_stmt)
3793 orig_stmt = STMT_VINFO_STMT (stmt_info);
3795 code = gimple_assign_rhs_code (orig_stmt);
3797 /* Add in cost for initial definition.
3798 For cond reduction we have four vectors: initial index, step, initial
3799 result of the data reduction, initial value of the index reduction. */
3800 int prologue_stmts = STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
3801 == COND_REDUCTION ? 4 : 1;
3802 prologue_cost += add_stmt_cost (target_cost_data, prologue_stmts,
3803 scalar_to_vec, stmt_info, 0,
3804 vect_prologue);
3806 /* Determine cost of epilogue code.
3808 We have a reduction operator that will reduce the vector in one statement.
3809 Also requires scalar extract. */
3811 if (!loop || !nested_in_vect_loop_p (loop, orig_stmt))
3813 if (reduc_fn != IFN_LAST)
3815 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3817 /* An EQ stmt and an COND_EXPR stmt. */
3818 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3819 vector_stmt, stmt_info, 0,
3820 vect_epilogue);
3821 /* Reduction of the max index and a reduction of the found
3822 values. */
3823 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3824 vec_to_scalar, stmt_info, 0,
3825 vect_epilogue);
3826 /* A broadcast of the max value. */
3827 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3828 scalar_to_vec, stmt_info, 0,
3829 vect_epilogue);
3831 else
3833 epilogue_cost += add_stmt_cost (target_cost_data, 1, vector_stmt,
3834 stmt_info, 0, vect_epilogue);
3835 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3836 vec_to_scalar, stmt_info, 0,
3837 vect_epilogue);
3840 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3842 unsigned nunits = TYPE_VECTOR_SUBPARTS (vectype);
3843 /* Extraction of scalar elements. */
3844 epilogue_cost += add_stmt_cost (target_cost_data, 2 * nunits,
3845 vec_to_scalar, stmt_info, 0,
3846 vect_epilogue);
3847 /* Scalar max reductions via COND_EXPR / MAX_EXPR. */
3848 epilogue_cost += add_stmt_cost (target_cost_data, 2 * nunits - 3,
3849 scalar_stmt, stmt_info, 0,
3850 vect_epilogue);
3852 else
3854 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
3855 tree bitsize =
3856 TYPE_SIZE (TREE_TYPE (gimple_assign_lhs (orig_stmt)));
3857 int element_bitsize = tree_to_uhwi (bitsize);
3858 int nelements = vec_size_in_bits / element_bitsize;
3860 if (code == COND_EXPR)
3861 code = MAX_EXPR;
3863 optab = optab_for_tree_code (code, vectype, optab_default);
3865 /* We have a whole vector shift available. */
3866 if (optab != unknown_optab
3867 && VECTOR_MODE_P (mode)
3868 && optab_handler (optab, mode) != CODE_FOR_nothing
3869 && have_whole_vector_shift (mode))
3871 /* Final reduction via vector shifts and the reduction operator.
3872 Also requires scalar extract. */
3873 epilogue_cost += add_stmt_cost (target_cost_data,
3874 exact_log2 (nelements) * 2,
3875 vector_stmt, stmt_info, 0,
3876 vect_epilogue);
3877 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3878 vec_to_scalar, stmt_info, 0,
3879 vect_epilogue);
3881 else
3882 /* Use extracts and reduction op for final reduction. For N
3883 elements, we have N extracts and N-1 reduction ops. */
3884 epilogue_cost += add_stmt_cost (target_cost_data,
3885 nelements + nelements - 1,
3886 vector_stmt, stmt_info, 0,
3887 vect_epilogue);
3891 if (dump_enabled_p ())
3892 dump_printf (MSG_NOTE,
3893 "vect_model_reduction_cost: inside_cost = %d, "
3894 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
3895 prologue_cost, epilogue_cost);
3899 /* Function vect_model_induction_cost.
3901 Models cost for induction operations. */
3903 static void
3904 vect_model_induction_cost (stmt_vec_info stmt_info, int ncopies)
3906 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3907 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3908 unsigned inside_cost, prologue_cost;
3910 if (PURE_SLP_STMT (stmt_info))
3911 return;
3913 /* loop cost for vec_loop. */
3914 inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3915 stmt_info, 0, vect_body);
3917 /* prologue cost for vec_init and vec_step. */
3918 prologue_cost = add_stmt_cost (target_cost_data, 2, scalar_to_vec,
3919 stmt_info, 0, vect_prologue);
3921 if (dump_enabled_p ())
3922 dump_printf_loc (MSG_NOTE, vect_location,
3923 "vect_model_induction_cost: inside_cost = %d, "
3924 "prologue_cost = %d .\n", inside_cost, prologue_cost);
3929 /* Function get_initial_def_for_reduction
3931 Input:
3932 STMT - a stmt that performs a reduction operation in the loop.
3933 INIT_VAL - the initial value of the reduction variable
3935 Output:
3936 ADJUSTMENT_DEF - a tree that holds a value to be added to the final result
3937 of the reduction (used for adjusting the epilog - see below).
3938 Return a vector variable, initialized according to the operation that STMT
3939 performs. This vector will be used as the initial value of the
3940 vector of partial results.
3942 Option1 (adjust in epilog): Initialize the vector as follows:
3943 add/bit or/xor: [0,0,...,0,0]
3944 mult/bit and: [1,1,...,1,1]
3945 min/max/cond_expr: [init_val,init_val,..,init_val,init_val]
3946 and when necessary (e.g. add/mult case) let the caller know
3947 that it needs to adjust the result by init_val.
3949 Option2: Initialize the vector as follows:
3950 add/bit or/xor: [init_val,0,0,...,0]
3951 mult/bit and: [init_val,1,1,...,1]
3952 min/max/cond_expr: [init_val,init_val,...,init_val]
3953 and no adjustments are needed.
3955 For example, for the following code:
3957 s = init_val;
3958 for (i=0;i<n;i++)
3959 s = s + a[i];
3961 STMT is 's = s + a[i]', and the reduction variable is 's'.
3962 For a vector of 4 units, we want to return either [0,0,0,init_val],
3963 or [0,0,0,0] and let the caller know that it needs to adjust
3964 the result at the end by 'init_val'.
3966 FORNOW, we are using the 'adjust in epilog' scheme, because this way the
3967 initialization vector is simpler (same element in all entries), if
3968 ADJUSTMENT_DEF is not NULL, and Option2 otherwise.
3970 A cost model should help decide between these two schemes. */
3972 tree
3973 get_initial_def_for_reduction (gimple *stmt, tree init_val,
3974 tree *adjustment_def)
3976 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
3977 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3978 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3979 tree scalar_type = TREE_TYPE (init_val);
3980 tree vectype = get_vectype_for_scalar_type (scalar_type);
3981 enum tree_code code = gimple_assign_rhs_code (stmt);
3982 tree def_for_init;
3983 tree init_def;
3984 bool nested_in_vect_loop = false;
3985 REAL_VALUE_TYPE real_init_val = dconst0;
3986 int int_init_val = 0;
3987 gimple *def_stmt = NULL;
3988 gimple_seq stmts = NULL;
3990 gcc_assert (vectype);
3992 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
3993 || SCALAR_FLOAT_TYPE_P (scalar_type));
3995 if (nested_in_vect_loop_p (loop, stmt))
3996 nested_in_vect_loop = true;
3997 else
3998 gcc_assert (loop == (gimple_bb (stmt))->loop_father);
4000 /* In case of double reduction we only create a vector variable to be put
4001 in the reduction phi node. The actual statement creation is done in
4002 vect_create_epilog_for_reduction. */
4003 if (adjustment_def && nested_in_vect_loop
4004 && TREE_CODE (init_val) == SSA_NAME
4005 && (def_stmt = SSA_NAME_DEF_STMT (init_val))
4006 && gimple_code (def_stmt) == GIMPLE_PHI
4007 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
4008 && vinfo_for_stmt (def_stmt)
4009 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
4010 == vect_double_reduction_def)
4012 *adjustment_def = NULL;
4013 return vect_create_destination_var (init_val, vectype);
4016 /* In case of a nested reduction do not use an adjustment def as
4017 that case is not supported by the epilogue generation correctly
4018 if ncopies is not one. */
4019 if (adjustment_def && nested_in_vect_loop)
4021 *adjustment_def = NULL;
4022 return vect_get_vec_def_for_operand (init_val, stmt);
4025 switch (code)
4027 case WIDEN_SUM_EXPR:
4028 case DOT_PROD_EXPR:
4029 case SAD_EXPR:
4030 case PLUS_EXPR:
4031 case MINUS_EXPR:
4032 case BIT_IOR_EXPR:
4033 case BIT_XOR_EXPR:
4034 case MULT_EXPR:
4035 case BIT_AND_EXPR:
4037 /* ADJUSMENT_DEF is NULL when called from
4038 vect_create_epilog_for_reduction to vectorize double reduction. */
4039 if (adjustment_def)
4040 *adjustment_def = init_val;
4042 if (code == MULT_EXPR)
4044 real_init_val = dconst1;
4045 int_init_val = 1;
4048 if (code == BIT_AND_EXPR)
4049 int_init_val = -1;
4051 if (SCALAR_FLOAT_TYPE_P (scalar_type))
4052 def_for_init = build_real (scalar_type, real_init_val);
4053 else
4054 def_for_init = build_int_cst (scalar_type, int_init_val);
4056 if (adjustment_def)
4057 /* Option1: the first element is '0' or '1' as well. */
4058 init_def = gimple_build_vector_from_val (&stmts, vectype,
4059 def_for_init);
4060 else
4062 /* Option2: the first element is INIT_VAL. */
4063 tree_vector_builder elts (vectype, 1, 2);
4064 elts.quick_push (init_val);
4065 elts.quick_push (def_for_init);
4066 init_def = gimple_build_vector (&stmts, &elts);
4069 break;
4071 case MIN_EXPR:
4072 case MAX_EXPR:
4073 case COND_EXPR:
4075 if (adjustment_def)
4077 *adjustment_def = NULL_TREE;
4078 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_vinfo) != COND_REDUCTION)
4080 init_def = vect_get_vec_def_for_operand (init_val, stmt);
4081 break;
4084 init_val = gimple_convert (&stmts, TREE_TYPE (vectype), init_val);
4085 init_def = gimple_build_vector_from_val (&stmts, vectype, init_val);
4087 break;
4089 default:
4090 gcc_unreachable ();
4093 if (stmts)
4094 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4095 return init_def;
4098 /* Get at the initial defs for the reduction PHIs in SLP_NODE.
4099 NUMBER_OF_VECTORS is the number of vector defs to create. */
4101 static void
4102 get_initial_defs_for_reduction (slp_tree slp_node,
4103 vec<tree> *vec_oprnds,
4104 unsigned int number_of_vectors,
4105 enum tree_code code, bool reduc_chain)
4107 vec<gimple *> stmts = SLP_TREE_SCALAR_STMTS (slp_node);
4108 gimple *stmt = stmts[0];
4109 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
4110 unsigned nunits;
4111 unsigned j, number_of_places_left_in_vector;
4112 tree vector_type, scalar_type;
4113 tree vop;
4114 int group_size = stmts.length ();
4115 unsigned int vec_num, i;
4116 unsigned number_of_copies = 1;
4117 vec<tree> voprnds;
4118 voprnds.create (number_of_vectors);
4119 tree neutral_op = NULL;
4120 struct loop *loop;
4122 vector_type = STMT_VINFO_VECTYPE (stmt_vinfo);
4123 scalar_type = TREE_TYPE (vector_type);
4124 nunits = TYPE_VECTOR_SUBPARTS (vector_type);
4126 gcc_assert (STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_reduction_def);
4128 loop = (gimple_bb (stmt))->loop_father;
4129 gcc_assert (loop);
4130 edge pe = loop_preheader_edge (loop);
4132 /* op is the reduction operand of the first stmt already. */
4133 /* For additional copies (see the explanation of NUMBER_OF_COPIES below)
4134 we need either neutral operands or the original operands. See
4135 get_initial_def_for_reduction() for details. */
4136 switch (code)
4138 case WIDEN_SUM_EXPR:
4139 case DOT_PROD_EXPR:
4140 case SAD_EXPR:
4141 case PLUS_EXPR:
4142 case MINUS_EXPR:
4143 case BIT_IOR_EXPR:
4144 case BIT_XOR_EXPR:
4145 neutral_op = build_zero_cst (scalar_type);
4146 break;
4148 case MULT_EXPR:
4149 neutral_op = build_one_cst (scalar_type);
4150 break;
4152 case BIT_AND_EXPR:
4153 neutral_op = build_all_ones_cst (scalar_type);
4154 break;
4156 /* For MIN/MAX we don't have an easy neutral operand but
4157 the initial values can be used fine here. Only for
4158 a reduction chain we have to force a neutral element. */
4159 case MAX_EXPR:
4160 case MIN_EXPR:
4161 if (! reduc_chain)
4162 neutral_op = NULL;
4163 else
4164 neutral_op = PHI_ARG_DEF_FROM_EDGE (stmt, pe);
4165 break;
4167 default:
4168 gcc_assert (! reduc_chain);
4169 neutral_op = NULL;
4172 /* NUMBER_OF_COPIES is the number of times we need to use the same values in
4173 created vectors. It is greater than 1 if unrolling is performed.
4175 For example, we have two scalar operands, s1 and s2 (e.g., group of
4176 strided accesses of size two), while NUNITS is four (i.e., four scalars
4177 of this type can be packed in a vector). The output vector will contain
4178 two copies of each scalar operand: {s1, s2, s1, s2}. (NUMBER_OF_COPIES
4179 will be 2).
4181 If GROUP_SIZE > NUNITS, the scalars will be split into several vectors
4182 containing the operands.
4184 For example, NUNITS is four as before, and the group size is 8
4185 (s1, s2, ..., s8). We will create two vectors {s1, s2, s3, s4} and
4186 {s5, s6, s7, s8}. */
4188 number_of_copies = nunits * number_of_vectors / group_size;
4190 number_of_places_left_in_vector = nunits;
4191 tree_vector_builder elts (vector_type, nunits, 1);
4192 elts.quick_grow (nunits);
4193 for (j = 0; j < number_of_copies; j++)
4195 for (i = group_size - 1; stmts.iterate (i, &stmt); i--)
4197 tree op;
4198 /* Get the def before the loop. In reduction chain we have only
4199 one initial value. */
4200 if ((j != (number_of_copies - 1)
4201 || (reduc_chain && i != 0))
4202 && neutral_op)
4203 op = neutral_op;
4204 else
4205 op = PHI_ARG_DEF_FROM_EDGE (stmt, pe);
4207 /* Create 'vect_ = {op0,op1,...,opn}'. */
4208 number_of_places_left_in_vector--;
4209 elts[number_of_places_left_in_vector] = op;
4211 if (number_of_places_left_in_vector == 0)
4213 gimple_seq ctor_seq = NULL;
4214 tree init = gimple_build_vector (&ctor_seq, &elts);
4215 if (ctor_seq != NULL)
4216 gsi_insert_seq_on_edge_immediate (pe, ctor_seq);
4217 voprnds.quick_push (init);
4219 number_of_places_left_in_vector = nunits;
4220 elts.new_vector (vector_type, nunits, 1);
4221 elts.quick_grow (nunits);
4226 /* Since the vectors are created in the reverse order, we should invert
4227 them. */
4228 vec_num = voprnds.length ();
4229 for (j = vec_num; j != 0; j--)
4231 vop = voprnds[j - 1];
4232 vec_oprnds->quick_push (vop);
4235 voprnds.release ();
4237 /* In case that VF is greater than the unrolling factor needed for the SLP
4238 group of stmts, NUMBER_OF_VECTORS to be created is greater than
4239 NUMBER_OF_SCALARS/NUNITS or NUNITS/NUMBER_OF_SCALARS, and hence we have
4240 to replicate the vectors. */
4241 tree neutral_vec = NULL;
4242 while (number_of_vectors > vec_oprnds->length ())
4244 if (neutral_op)
4246 if (!neutral_vec)
4248 gimple_seq ctor_seq = NULL;
4249 neutral_vec = gimple_build_vector_from_val
4250 (&ctor_seq, vector_type, neutral_op);
4251 if (ctor_seq != NULL)
4252 gsi_insert_seq_on_edge_immediate (pe, ctor_seq);
4254 vec_oprnds->quick_push (neutral_vec);
4256 else
4258 for (i = 0; vec_oprnds->iterate (i, &vop) && i < vec_num; i++)
4259 vec_oprnds->quick_push (vop);
4265 /* Function vect_create_epilog_for_reduction
4267 Create code at the loop-epilog to finalize the result of a reduction
4268 computation.
4270 VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector
4271 reduction statements.
4272 STMT is the scalar reduction stmt that is being vectorized.
4273 NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the
4274 number of elements that we can fit in a vectype (nunits). In this case
4275 we have to generate more than one vector stmt - i.e - we need to "unroll"
4276 the vector stmt by a factor VF/nunits. For more details see documentation
4277 in vectorizable_operation.
4278 REDUC_FN is the internal function for the epilog reduction.
4279 REDUCTION_PHIS is a list of the phi-nodes that carry the reduction
4280 computation.
4281 REDUC_INDEX is the index of the operand in the right hand side of the
4282 statement that is defined by REDUCTION_PHI.
4283 DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled.
4284 SLP_NODE is an SLP node containing a group of reduction statements. The
4285 first one in this group is STMT.
4287 This function:
4288 1. Creates the reduction def-use cycles: sets the arguments for
4289 REDUCTION_PHIS:
4290 The loop-entry argument is the vectorized initial-value of the reduction.
4291 The loop-latch argument is taken from VECT_DEFS - the vector of partial
4292 sums.
4293 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
4294 by calling the function specified by REDUC_FN if available, or by
4295 other means (whole-vector shifts or a scalar loop).
4296 The function also creates a new phi node at the loop exit to preserve
4297 loop-closed form, as illustrated below.
4299 The flow at the entry to this function:
4301 loop:
4302 vec_def = phi <null, null> # REDUCTION_PHI
4303 VECT_DEF = vector_stmt # vectorized form of STMT
4304 s_loop = scalar_stmt # (scalar) STMT
4305 loop_exit:
4306 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4307 use <s_out0>
4308 use <s_out0>
4310 The above is transformed by this function into:
4312 loop:
4313 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4314 VECT_DEF = vector_stmt # vectorized form of STMT
4315 s_loop = scalar_stmt # (scalar) STMT
4316 loop_exit:
4317 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4318 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4319 v_out2 = reduce <v_out1>
4320 s_out3 = extract_field <v_out2, 0>
4321 s_out4 = adjust_result <s_out3>
4322 use <s_out4>
4323 use <s_out4>
4326 static void
4327 vect_create_epilog_for_reduction (vec<tree> vect_defs, gimple *stmt,
4328 gimple *reduc_def_stmt,
4329 int ncopies, internal_fn reduc_fn,
4330 vec<gimple *> reduction_phis,
4331 bool double_reduc,
4332 slp_tree slp_node,
4333 slp_instance slp_node_instance)
4335 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
4336 stmt_vec_info prev_phi_info;
4337 tree vectype;
4338 machine_mode mode;
4339 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
4340 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
4341 basic_block exit_bb;
4342 tree scalar_dest;
4343 tree scalar_type;
4344 gimple *new_phi = NULL, *phi;
4345 gimple_stmt_iterator exit_gsi;
4346 tree vec_dest;
4347 tree new_temp = NULL_TREE, new_dest, new_name, new_scalar_dest;
4348 gimple *epilog_stmt = NULL;
4349 enum tree_code code = gimple_assign_rhs_code (stmt);
4350 gimple *exit_phi;
4351 tree bitsize;
4352 tree adjustment_def = NULL;
4353 tree vec_initial_def = NULL;
4354 tree expr, def, initial_def = NULL;
4355 tree orig_name, scalar_result;
4356 imm_use_iterator imm_iter, phi_imm_iter;
4357 use_operand_p use_p, phi_use_p;
4358 gimple *use_stmt, *orig_stmt, *reduction_phi = NULL;
4359 bool nested_in_vect_loop = false;
4360 auto_vec<gimple *> new_phis;
4361 auto_vec<gimple *> inner_phis;
4362 enum vect_def_type dt = vect_unknown_def_type;
4363 int j, i;
4364 auto_vec<tree> scalar_results;
4365 unsigned int group_size = 1, k, ratio;
4366 auto_vec<tree> vec_initial_defs;
4367 auto_vec<gimple *> phis;
4368 bool slp_reduc = false;
4369 tree new_phi_result;
4370 gimple *inner_phi = NULL;
4371 tree induction_index = NULL_TREE;
4373 if (slp_node)
4374 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
4376 if (nested_in_vect_loop_p (loop, stmt))
4378 outer_loop = loop;
4379 loop = loop->inner;
4380 nested_in_vect_loop = true;
4381 gcc_assert (!slp_node);
4384 vectype = STMT_VINFO_VECTYPE (stmt_info);
4385 gcc_assert (vectype);
4386 mode = TYPE_MODE (vectype);
4388 /* 1. Create the reduction def-use cycle:
4389 Set the arguments of REDUCTION_PHIS, i.e., transform
4391 loop:
4392 vec_def = phi <null, null> # REDUCTION_PHI
4393 VECT_DEF = vector_stmt # vectorized form of STMT
4396 into:
4398 loop:
4399 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4400 VECT_DEF = vector_stmt # vectorized form of STMT
4403 (in case of SLP, do it for all the phis). */
4405 /* Get the loop-entry arguments. */
4406 enum vect_def_type initial_def_dt = vect_unknown_def_type;
4407 if (slp_node)
4409 unsigned vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
4410 vec_initial_defs.reserve (vec_num);
4411 get_initial_defs_for_reduction (slp_node_instance->reduc_phis,
4412 &vec_initial_defs, vec_num, code,
4413 GROUP_FIRST_ELEMENT (stmt_info));
4415 else
4417 /* Get at the scalar def before the loop, that defines the initial value
4418 of the reduction variable. */
4419 gimple *def_stmt;
4420 initial_def = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
4421 loop_preheader_edge (loop));
4422 vect_is_simple_use (initial_def, loop_vinfo, &def_stmt, &initial_def_dt);
4423 vec_initial_def = get_initial_def_for_reduction (stmt, initial_def,
4424 &adjustment_def);
4425 vec_initial_defs.create (1);
4426 vec_initial_defs.quick_push (vec_initial_def);
4429 /* Set phi nodes arguments. */
4430 FOR_EACH_VEC_ELT (reduction_phis, i, phi)
4432 tree vec_init_def = vec_initial_defs[i];
4433 tree def = vect_defs[i];
4434 for (j = 0; j < ncopies; j++)
4436 if (j != 0)
4438 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4439 if (nested_in_vect_loop)
4440 vec_init_def
4441 = vect_get_vec_def_for_stmt_copy (initial_def_dt,
4442 vec_init_def);
4445 /* Set the loop-entry arg of the reduction-phi. */
4447 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4448 == INTEGER_INDUC_COND_REDUCTION)
4450 /* Initialise the reduction phi to zero. This prevents initial
4451 values of non-zero interferring with the reduction op. */
4452 gcc_assert (ncopies == 1);
4453 gcc_assert (i == 0);
4455 tree vec_init_def_type = TREE_TYPE (vec_init_def);
4456 tree zero_vec = build_zero_cst (vec_init_def_type);
4458 add_phi_arg (as_a <gphi *> (phi), zero_vec,
4459 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4461 else
4462 add_phi_arg (as_a <gphi *> (phi), vec_init_def,
4463 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4465 /* Set the loop-latch arg for the reduction-phi. */
4466 if (j > 0)
4467 def = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type, def);
4469 add_phi_arg (as_a <gphi *> (phi), def, loop_latch_edge (loop),
4470 UNKNOWN_LOCATION);
4472 if (dump_enabled_p ())
4474 dump_printf_loc (MSG_NOTE, vect_location,
4475 "transform reduction: created def-use cycle: ");
4476 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
4477 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (def), 0);
4482 /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
4483 which is updated with the current index of the loop for every match of
4484 the original loop's cond_expr (VEC_STMT). This results in a vector
4485 containing the last time the condition passed for that vector lane.
4486 The first match will be a 1 to allow 0 to be used for non-matching
4487 indexes. If there are no matches at all then the vector will be all
4488 zeroes. */
4489 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
4491 tree indx_before_incr, indx_after_incr;
4492 int nunits_out = TYPE_VECTOR_SUBPARTS (vectype);
4493 int k;
4495 gimple *vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
4496 gcc_assert (gimple_assign_rhs_code (vec_stmt) == VEC_COND_EXPR);
4498 int scalar_precision
4499 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (TREE_TYPE (vectype)));
4500 tree cr_index_scalar_type = make_unsigned_type (scalar_precision);
4501 tree cr_index_vector_type = build_vector_type
4502 (cr_index_scalar_type, TYPE_VECTOR_SUBPARTS (vectype));
4504 /* First we create a simple vector induction variable which starts
4505 with the values {1,2,3,...} (SERIES_VECT) and increments by the
4506 vector size (STEP). */
4508 /* Create a {1,2,3,...} vector. */
4509 tree_vector_builder vtemp (cr_index_vector_type, 1, 3);
4510 for (k = 0; k < 3; ++k)
4511 vtemp.quick_push (build_int_cst (cr_index_scalar_type, k + 1));
4512 tree series_vect = vtemp.build ();
4514 /* Create a vector of the step value. */
4515 tree step = build_int_cst (cr_index_scalar_type, nunits_out);
4516 tree vec_step = build_vector_from_val (cr_index_vector_type, step);
4518 /* Create an induction variable. */
4519 gimple_stmt_iterator incr_gsi;
4520 bool insert_after;
4521 standard_iv_increment_position (loop, &incr_gsi, &insert_after);
4522 create_iv (series_vect, vec_step, NULL_TREE, loop, &incr_gsi,
4523 insert_after, &indx_before_incr, &indx_after_incr);
4525 /* Next create a new phi node vector (NEW_PHI_TREE) which starts
4526 filled with zeros (VEC_ZERO). */
4528 /* Create a vector of 0s. */
4529 tree zero = build_zero_cst (cr_index_scalar_type);
4530 tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
4532 /* Create a vector phi node. */
4533 tree new_phi_tree = make_ssa_name (cr_index_vector_type);
4534 new_phi = create_phi_node (new_phi_tree, loop->header);
4535 set_vinfo_for_stmt (new_phi,
4536 new_stmt_vec_info (new_phi, loop_vinfo));
4537 add_phi_arg (as_a <gphi *> (new_phi), vec_zero,
4538 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4540 /* Now take the condition from the loops original cond_expr
4541 (VEC_STMT) and produce a new cond_expr (INDEX_COND_EXPR) which for
4542 every match uses values from the induction variable
4543 (INDEX_BEFORE_INCR) otherwise uses values from the phi node
4544 (NEW_PHI_TREE).
4545 Finally, we update the phi (NEW_PHI_TREE) to take the value of
4546 the new cond_expr (INDEX_COND_EXPR). */
4548 /* Duplicate the condition from vec_stmt. */
4549 tree ccompare = unshare_expr (gimple_assign_rhs1 (vec_stmt));
4551 /* Create a conditional, where the condition is taken from vec_stmt
4552 (CCOMPARE), then is the induction index (INDEX_BEFORE_INCR) and
4553 else is the phi (NEW_PHI_TREE). */
4554 tree index_cond_expr = build3 (VEC_COND_EXPR, cr_index_vector_type,
4555 ccompare, indx_before_incr,
4556 new_phi_tree);
4557 induction_index = make_ssa_name (cr_index_vector_type);
4558 gimple *index_condition = gimple_build_assign (induction_index,
4559 index_cond_expr);
4560 gsi_insert_before (&incr_gsi, index_condition, GSI_SAME_STMT);
4561 stmt_vec_info index_vec_info = new_stmt_vec_info (index_condition,
4562 loop_vinfo);
4563 STMT_VINFO_VECTYPE (index_vec_info) = cr_index_vector_type;
4564 set_vinfo_for_stmt (index_condition, index_vec_info);
4566 /* Update the phi with the vec cond. */
4567 add_phi_arg (as_a <gphi *> (new_phi), induction_index,
4568 loop_latch_edge (loop), UNKNOWN_LOCATION);
4571 /* 2. Create epilog code.
4572 The reduction epilog code operates across the elements of the vector
4573 of partial results computed by the vectorized loop.
4574 The reduction epilog code consists of:
4576 step 1: compute the scalar result in a vector (v_out2)
4577 step 2: extract the scalar result (s_out3) from the vector (v_out2)
4578 step 3: adjust the scalar result (s_out3) if needed.
4580 Step 1 can be accomplished using one the following three schemes:
4581 (scheme 1) using reduc_fn, if available.
4582 (scheme 2) using whole-vector shifts, if available.
4583 (scheme 3) using a scalar loop. In this case steps 1+2 above are
4584 combined.
4586 The overall epilog code looks like this:
4588 s_out0 = phi <s_loop> # original EXIT_PHI
4589 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4590 v_out2 = reduce <v_out1> # step 1
4591 s_out3 = extract_field <v_out2, 0> # step 2
4592 s_out4 = adjust_result <s_out3> # step 3
4594 (step 3 is optional, and steps 1 and 2 may be combined).
4595 Lastly, the uses of s_out0 are replaced by s_out4. */
4598 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
4599 v_out1 = phi <VECT_DEF>
4600 Store them in NEW_PHIS. */
4602 exit_bb = single_exit (loop)->dest;
4603 prev_phi_info = NULL;
4604 new_phis.create (vect_defs.length ());
4605 FOR_EACH_VEC_ELT (vect_defs, i, def)
4607 for (j = 0; j < ncopies; j++)
4609 tree new_def = copy_ssa_name (def);
4610 phi = create_phi_node (new_def, exit_bb);
4611 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, loop_vinfo));
4612 if (j == 0)
4613 new_phis.quick_push (phi);
4614 else
4616 def = vect_get_vec_def_for_stmt_copy (dt, def);
4617 STMT_VINFO_RELATED_STMT (prev_phi_info) = phi;
4620 SET_PHI_ARG_DEF (phi, single_exit (loop)->dest_idx, def);
4621 prev_phi_info = vinfo_for_stmt (phi);
4625 /* The epilogue is created for the outer-loop, i.e., for the loop being
4626 vectorized. Create exit phis for the outer loop. */
4627 if (double_reduc)
4629 loop = outer_loop;
4630 exit_bb = single_exit (loop)->dest;
4631 inner_phis.create (vect_defs.length ());
4632 FOR_EACH_VEC_ELT (new_phis, i, phi)
4634 tree new_result = copy_ssa_name (PHI_RESULT (phi));
4635 gphi *outer_phi = create_phi_node (new_result, exit_bb);
4636 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4637 PHI_RESULT (phi));
4638 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4639 loop_vinfo));
4640 inner_phis.quick_push (phi);
4641 new_phis[i] = outer_phi;
4642 prev_phi_info = vinfo_for_stmt (outer_phi);
4643 while (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi)))
4645 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4646 new_result = copy_ssa_name (PHI_RESULT (phi));
4647 outer_phi = create_phi_node (new_result, exit_bb);
4648 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4649 PHI_RESULT (phi));
4650 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4651 loop_vinfo));
4652 STMT_VINFO_RELATED_STMT (prev_phi_info) = outer_phi;
4653 prev_phi_info = vinfo_for_stmt (outer_phi);
4658 exit_gsi = gsi_after_labels (exit_bb);
4660 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
4661 (i.e. when reduc_fn is not available) and in the final adjustment
4662 code (if needed). Also get the original scalar reduction variable as
4663 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
4664 represents a reduction pattern), the tree-code and scalar-def are
4665 taken from the original stmt that the pattern-stmt (STMT) replaces.
4666 Otherwise (it is a regular reduction) - the tree-code and scalar-def
4667 are taken from STMT. */
4669 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4670 if (!orig_stmt)
4672 /* Regular reduction */
4673 orig_stmt = stmt;
4675 else
4677 /* Reduction pattern */
4678 stmt_vec_info stmt_vinfo = vinfo_for_stmt (orig_stmt);
4679 gcc_assert (STMT_VINFO_IN_PATTERN_P (stmt_vinfo));
4680 gcc_assert (STMT_VINFO_RELATED_STMT (stmt_vinfo) == stmt);
4683 code = gimple_assign_rhs_code (orig_stmt);
4684 /* For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore,
4685 partial results are added and not subtracted. */
4686 if (code == MINUS_EXPR)
4687 code = PLUS_EXPR;
4689 scalar_dest = gimple_assign_lhs (orig_stmt);
4690 scalar_type = TREE_TYPE (scalar_dest);
4691 scalar_results.create (group_size);
4692 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
4693 bitsize = TYPE_SIZE (scalar_type);
4695 /* In case this is a reduction in an inner-loop while vectorizing an outer
4696 loop - we don't need to extract a single scalar result at the end of the
4697 inner-loop (unless it is double reduction, i.e., the use of reduction is
4698 outside the outer-loop). The final vector of partial results will be used
4699 in the vectorized outer-loop, or reduced to a scalar result at the end of
4700 the outer-loop. */
4701 if (nested_in_vect_loop && !double_reduc)
4702 goto vect_finalize_reduction;
4704 /* SLP reduction without reduction chain, e.g.,
4705 # a1 = phi <a2, a0>
4706 # b1 = phi <b2, b0>
4707 a2 = operation (a1)
4708 b2 = operation (b1) */
4709 slp_reduc = (slp_node && !GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
4711 /* In case of reduction chain, e.g.,
4712 # a1 = phi <a3, a0>
4713 a2 = operation (a1)
4714 a3 = operation (a2),
4716 we may end up with more than one vector result. Here we reduce them to
4717 one vector. */
4718 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4720 tree first_vect = PHI_RESULT (new_phis[0]);
4721 gassign *new_vec_stmt = NULL;
4722 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4723 for (k = 1; k < new_phis.length (); k++)
4725 gimple *next_phi = new_phis[k];
4726 tree second_vect = PHI_RESULT (next_phi);
4727 tree tem = make_ssa_name (vec_dest, new_vec_stmt);
4728 new_vec_stmt = gimple_build_assign (tem, code,
4729 first_vect, second_vect);
4730 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4731 first_vect = tem;
4734 new_phi_result = first_vect;
4735 if (new_vec_stmt)
4737 new_phis.truncate (0);
4738 new_phis.safe_push (new_vec_stmt);
4741 /* Likewise if we couldn't use a single defuse cycle. */
4742 else if (ncopies > 1)
4744 gcc_assert (new_phis.length () == 1);
4745 tree first_vect = PHI_RESULT (new_phis[0]);
4746 gassign *new_vec_stmt = NULL;
4747 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4748 gimple *next_phi = new_phis[0];
4749 for (int k = 1; k < ncopies; ++k)
4751 next_phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (next_phi));
4752 tree second_vect = PHI_RESULT (next_phi);
4753 tree tem = make_ssa_name (vec_dest, new_vec_stmt);
4754 new_vec_stmt = gimple_build_assign (tem, code,
4755 first_vect, second_vect);
4756 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4757 first_vect = tem;
4759 new_phi_result = first_vect;
4760 new_phis.truncate (0);
4761 new_phis.safe_push (new_vec_stmt);
4763 else
4764 new_phi_result = PHI_RESULT (new_phis[0]);
4766 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION
4767 && reduc_fn != IFN_LAST)
4769 /* For condition reductions, we have a vector (NEW_PHI_RESULT) containing
4770 various data values where the condition matched and another vector
4771 (INDUCTION_INDEX) containing all the indexes of those matches. We
4772 need to extract the last matching index (which will be the index with
4773 highest value) and use this to index into the data vector.
4774 For the case where there were no matches, the data vector will contain
4775 all default values and the index vector will be all zeros. */
4777 /* Get various versions of the type of the vector of indexes. */
4778 tree index_vec_type = TREE_TYPE (induction_index);
4779 gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
4780 tree index_scalar_type = TREE_TYPE (index_vec_type);
4781 tree index_vec_cmp_type = build_same_sized_truth_vector_type
4782 (index_vec_type);
4784 /* Get an unsigned integer version of the type of the data vector. */
4785 int scalar_precision
4786 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (scalar_type));
4787 tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
4788 tree vectype_unsigned = build_vector_type
4789 (scalar_type_unsigned, TYPE_VECTOR_SUBPARTS (vectype));
4791 /* First we need to create a vector (ZERO_VEC) of zeros and another
4792 vector (MAX_INDEX_VEC) filled with the last matching index, which we
4793 can create using a MAX reduction and then expanding.
4794 In the case where the loop never made any matches, the max index will
4795 be zero. */
4797 /* Vector of {0, 0, 0,...}. */
4798 tree zero_vec = make_ssa_name (vectype);
4799 tree zero_vec_rhs = build_zero_cst (vectype);
4800 gimple *zero_vec_stmt = gimple_build_assign (zero_vec, zero_vec_rhs);
4801 gsi_insert_before (&exit_gsi, zero_vec_stmt, GSI_SAME_STMT);
4803 /* Find maximum value from the vector of found indexes. */
4804 tree max_index = make_ssa_name (index_scalar_type);
4805 gcall *max_index_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
4806 1, induction_index);
4807 gimple_call_set_lhs (max_index_stmt, max_index);
4808 gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
4810 /* Vector of {max_index, max_index, max_index,...}. */
4811 tree max_index_vec = make_ssa_name (index_vec_type);
4812 tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
4813 max_index);
4814 gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
4815 max_index_vec_rhs);
4816 gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
4818 /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
4819 with the vector (INDUCTION_INDEX) of found indexes, choosing values
4820 from the data vector (NEW_PHI_RESULT) for matches, 0 (ZERO_VEC)
4821 otherwise. Only one value should match, resulting in a vector
4822 (VEC_COND) with one data value and the rest zeros.
4823 In the case where the loop never made any matches, every index will
4824 match, resulting in a vector with all data values (which will all be
4825 the default value). */
4827 /* Compare the max index vector to the vector of found indexes to find
4828 the position of the max value. */
4829 tree vec_compare = make_ssa_name (index_vec_cmp_type);
4830 gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
4831 induction_index,
4832 max_index_vec);
4833 gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
4835 /* Use the compare to choose either values from the data vector or
4836 zero. */
4837 tree vec_cond = make_ssa_name (vectype);
4838 gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
4839 vec_compare, new_phi_result,
4840 zero_vec);
4841 gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
4843 /* Finally we need to extract the data value from the vector (VEC_COND)
4844 into a scalar (MATCHED_DATA_REDUC). Logically we want to do a OR
4845 reduction, but because this doesn't exist, we can use a MAX reduction
4846 instead. The data value might be signed or a float so we need to cast
4847 it first.
4848 In the case where the loop never made any matches, the data values are
4849 all identical, and so will reduce down correctly. */
4851 /* Make the matched data values unsigned. */
4852 tree vec_cond_cast = make_ssa_name (vectype_unsigned);
4853 tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
4854 vec_cond);
4855 gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
4856 VIEW_CONVERT_EXPR,
4857 vec_cond_cast_rhs);
4858 gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
4860 /* Reduce down to a scalar value. */
4861 tree data_reduc = make_ssa_name (scalar_type_unsigned);
4862 gcall *data_reduc_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
4863 1, vec_cond_cast);
4864 gimple_call_set_lhs (data_reduc_stmt, data_reduc);
4865 gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
4867 /* Convert the reduced value back to the result type and set as the
4868 result. */
4869 gimple_seq stmts = NULL;
4870 new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR, scalar_type,
4871 data_reduc);
4872 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
4873 scalar_results.safe_push (new_temp);
4875 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION
4876 && reduc_fn == IFN_LAST)
4878 /* Condition reduction without supported IFN_REDUC_MAX. Generate
4879 idx = 0;
4880 idx_val = induction_index[0];
4881 val = data_reduc[0];
4882 for (idx = 0, val = init, i = 0; i < nelts; ++i)
4883 if (induction_index[i] > idx_val)
4884 val = data_reduc[i], idx_val = induction_index[i];
4885 return val; */
4887 tree data_eltype = TREE_TYPE (TREE_TYPE (new_phi_result));
4888 tree idx_eltype = TREE_TYPE (TREE_TYPE (induction_index));
4889 unsigned HOST_WIDE_INT el_size = tree_to_uhwi (TYPE_SIZE (idx_eltype));
4890 unsigned HOST_WIDE_INT v_size
4891 = el_size * TYPE_VECTOR_SUBPARTS (TREE_TYPE (induction_index));
4892 tree idx_val = NULL_TREE, val = NULL_TREE;
4893 for (unsigned HOST_WIDE_INT off = 0; off < v_size; off += el_size)
4895 tree old_idx_val = idx_val;
4896 tree old_val = val;
4897 idx_val = make_ssa_name (idx_eltype);
4898 epilog_stmt = gimple_build_assign (idx_val, BIT_FIELD_REF,
4899 build3 (BIT_FIELD_REF, idx_eltype,
4900 induction_index,
4901 bitsize_int (el_size),
4902 bitsize_int (off)));
4903 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4904 val = make_ssa_name (data_eltype);
4905 epilog_stmt = gimple_build_assign (val, BIT_FIELD_REF,
4906 build3 (BIT_FIELD_REF,
4907 data_eltype,
4908 new_phi_result,
4909 bitsize_int (el_size),
4910 bitsize_int (off)));
4911 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4912 if (off != 0)
4914 tree new_idx_val = idx_val;
4915 tree new_val = val;
4916 if (off != v_size - el_size)
4918 new_idx_val = make_ssa_name (idx_eltype);
4919 epilog_stmt = gimple_build_assign (new_idx_val,
4920 MAX_EXPR, idx_val,
4921 old_idx_val);
4922 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4924 new_val = make_ssa_name (data_eltype);
4925 epilog_stmt = gimple_build_assign (new_val,
4926 COND_EXPR,
4927 build2 (GT_EXPR,
4928 boolean_type_node,
4929 idx_val,
4930 old_idx_val),
4931 val, old_val);
4932 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4933 idx_val = new_idx_val;
4934 val = new_val;
4937 /* Convert the reduced value back to the result type and set as the
4938 result. */
4939 gimple_seq stmts = NULL;
4940 val = gimple_convert (&stmts, scalar_type, val);
4941 gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
4942 scalar_results.safe_push (val);
4945 /* 2.3 Create the reduction code, using one of the three schemes described
4946 above. In SLP we simply need to extract all the elements from the
4947 vector (without reducing them), so we use scalar shifts. */
4948 else if (reduc_fn != IFN_LAST && !slp_reduc)
4950 tree tmp;
4951 tree vec_elem_type;
4953 /* Case 1: Create:
4954 v_out2 = reduc_expr <v_out1> */
4956 if (dump_enabled_p ())
4957 dump_printf_loc (MSG_NOTE, vect_location,
4958 "Reduce using direct vector reduction.\n");
4960 vec_elem_type = TREE_TYPE (TREE_TYPE (new_phi_result));
4961 if (!useless_type_conversion_p (scalar_type, vec_elem_type))
4963 tree tmp_dest
4964 = vect_create_destination_var (scalar_dest, vec_elem_type);
4965 epilog_stmt = gimple_build_call_internal (reduc_fn, 1,
4966 new_phi_result);
4967 gimple_set_lhs (epilog_stmt, tmp_dest);
4968 new_temp = make_ssa_name (tmp_dest, epilog_stmt);
4969 gimple_set_lhs (epilog_stmt, new_temp);
4970 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4972 epilog_stmt = gimple_build_assign (new_scalar_dest, NOP_EXPR,
4973 new_temp);
4975 else
4977 epilog_stmt = gimple_build_call_internal (reduc_fn, 1,
4978 new_phi_result);
4979 gimple_set_lhs (epilog_stmt, new_scalar_dest);
4982 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4983 gimple_set_lhs (epilog_stmt, new_temp);
4984 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4986 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4987 == INTEGER_INDUC_COND_REDUCTION)
4989 /* Earlier we set the initial value to be zero. Check the result
4990 and if it is zero then replace with the original initial
4991 value. */
4992 tree zero = build_zero_cst (scalar_type);
4993 tree zcompare = build2 (EQ_EXPR, boolean_type_node, new_temp, zero);
4995 tmp = make_ssa_name (new_scalar_dest);
4996 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
4997 initial_def, new_temp);
4998 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4999 new_temp = tmp;
5002 scalar_results.safe_push (new_temp);
5004 else
5006 bool reduce_with_shift = have_whole_vector_shift (mode);
5007 int element_bitsize = tree_to_uhwi (bitsize);
5008 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
5009 tree vec_temp;
5011 /* COND reductions all do the final reduction with MAX_EXPR. */
5012 if (code == COND_EXPR)
5013 code = MAX_EXPR;
5015 /* Regardless of whether we have a whole vector shift, if we're
5016 emulating the operation via tree-vect-generic, we don't want
5017 to use it. Only the first round of the reduction is likely
5018 to still be profitable via emulation. */
5019 /* ??? It might be better to emit a reduction tree code here, so that
5020 tree-vect-generic can expand the first round via bit tricks. */
5021 if (!VECTOR_MODE_P (mode))
5022 reduce_with_shift = false;
5023 else
5025 optab optab = optab_for_tree_code (code, vectype, optab_default);
5026 if (optab_handler (optab, mode) == CODE_FOR_nothing)
5027 reduce_with_shift = false;
5030 if (reduce_with_shift && !slp_reduc)
5032 int nelements = vec_size_in_bits / element_bitsize;
5033 auto_vec_perm_indices sel (nelements);
5035 int elt_offset;
5037 tree zero_vec = build_zero_cst (vectype);
5038 /* Case 2: Create:
5039 for (offset = nelements/2; offset >= 1; offset/=2)
5041 Create: va' = vec_shift <va, offset>
5042 Create: va = vop <va, va'>
5043 } */
5045 tree rhs;
5047 if (dump_enabled_p ())
5048 dump_printf_loc (MSG_NOTE, vect_location,
5049 "Reduce using vector shifts\n");
5051 vec_dest = vect_create_destination_var (scalar_dest, vectype);
5052 new_temp = new_phi_result;
5053 for (elt_offset = nelements / 2;
5054 elt_offset >= 1;
5055 elt_offset /= 2)
5057 sel.truncate (0);
5058 calc_vec_perm_mask_for_shift (elt_offset, nelements, &sel);
5059 tree mask = vect_gen_perm_mask_any (vectype, sel);
5060 epilog_stmt = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
5061 new_temp, zero_vec, mask);
5062 new_name = make_ssa_name (vec_dest, epilog_stmt);
5063 gimple_assign_set_lhs (epilog_stmt, new_name);
5064 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5066 epilog_stmt = gimple_build_assign (vec_dest, code, new_name,
5067 new_temp);
5068 new_temp = make_ssa_name (vec_dest, epilog_stmt);
5069 gimple_assign_set_lhs (epilog_stmt, new_temp);
5070 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5073 /* 2.4 Extract the final scalar result. Create:
5074 s_out3 = extract_field <v_out2, bitpos> */
5076 if (dump_enabled_p ())
5077 dump_printf_loc (MSG_NOTE, vect_location,
5078 "extract scalar result\n");
5080 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp,
5081 bitsize, bitsize_zero_node);
5082 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
5083 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
5084 gimple_assign_set_lhs (epilog_stmt, new_temp);
5085 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5086 scalar_results.safe_push (new_temp);
5088 else
5090 /* Case 3: Create:
5091 s = extract_field <v_out2, 0>
5092 for (offset = element_size;
5093 offset < vector_size;
5094 offset += element_size;)
5096 Create: s' = extract_field <v_out2, offset>
5097 Create: s = op <s, s'> // For non SLP cases
5098 } */
5100 if (dump_enabled_p ())
5101 dump_printf_loc (MSG_NOTE, vect_location,
5102 "Reduce using scalar code.\n");
5104 vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
5105 FOR_EACH_VEC_ELT (new_phis, i, new_phi)
5107 int bit_offset;
5108 if (gimple_code (new_phi) == GIMPLE_PHI)
5109 vec_temp = PHI_RESULT (new_phi);
5110 else
5111 vec_temp = gimple_assign_lhs (new_phi);
5112 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp, bitsize,
5113 bitsize_zero_node);
5114 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
5115 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
5116 gimple_assign_set_lhs (epilog_stmt, new_temp);
5117 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5119 /* In SLP we don't need to apply reduction operation, so we just
5120 collect s' values in SCALAR_RESULTS. */
5121 if (slp_reduc)
5122 scalar_results.safe_push (new_temp);
5124 for (bit_offset = element_bitsize;
5125 bit_offset < vec_size_in_bits;
5126 bit_offset += element_bitsize)
5128 tree bitpos = bitsize_int (bit_offset);
5129 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp,
5130 bitsize, bitpos);
5132 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
5133 new_name = make_ssa_name (new_scalar_dest, epilog_stmt);
5134 gimple_assign_set_lhs (epilog_stmt, new_name);
5135 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5137 if (slp_reduc)
5139 /* In SLP we don't need to apply reduction operation, so
5140 we just collect s' values in SCALAR_RESULTS. */
5141 new_temp = new_name;
5142 scalar_results.safe_push (new_name);
5144 else
5146 epilog_stmt = gimple_build_assign (new_scalar_dest, code,
5147 new_name, new_temp);
5148 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
5149 gimple_assign_set_lhs (epilog_stmt, new_temp);
5150 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5155 /* The only case where we need to reduce scalar results in SLP, is
5156 unrolling. If the size of SCALAR_RESULTS is greater than
5157 GROUP_SIZE, we reduce them combining elements modulo
5158 GROUP_SIZE. */
5159 if (slp_reduc)
5161 tree res, first_res, new_res;
5162 gimple *new_stmt;
5164 /* Reduce multiple scalar results in case of SLP unrolling. */
5165 for (j = group_size; scalar_results.iterate (j, &res);
5166 j++)
5168 first_res = scalar_results[j % group_size];
5169 new_stmt = gimple_build_assign (new_scalar_dest, code,
5170 first_res, res);
5171 new_res = make_ssa_name (new_scalar_dest, new_stmt);
5172 gimple_assign_set_lhs (new_stmt, new_res);
5173 gsi_insert_before (&exit_gsi, new_stmt, GSI_SAME_STMT);
5174 scalar_results[j % group_size] = new_res;
5177 else
5178 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
5179 scalar_results.safe_push (new_temp);
5182 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5183 == INTEGER_INDUC_COND_REDUCTION)
5185 /* Earlier we set the initial value to be zero. Check the result
5186 and if it is zero then replace with the original initial
5187 value. */
5188 tree zero = build_zero_cst (scalar_type);
5189 tree zcompare = build2 (EQ_EXPR, boolean_type_node, new_temp, zero);
5191 tree tmp = make_ssa_name (new_scalar_dest);
5192 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
5193 initial_def, new_temp);
5194 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5195 scalar_results[0] = tmp;
5199 vect_finalize_reduction:
5201 if (double_reduc)
5202 loop = loop->inner;
5204 /* 2.5 Adjust the final result by the initial value of the reduction
5205 variable. (When such adjustment is not needed, then
5206 'adjustment_def' is zero). For example, if code is PLUS we create:
5207 new_temp = loop_exit_def + adjustment_def */
5209 if (adjustment_def)
5211 gcc_assert (!slp_reduc);
5212 if (nested_in_vect_loop)
5214 new_phi = new_phis[0];
5215 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) == VECTOR_TYPE);
5216 expr = build2 (code, vectype, PHI_RESULT (new_phi), adjustment_def);
5217 new_dest = vect_create_destination_var (scalar_dest, vectype);
5219 else
5221 new_temp = scalar_results[0];
5222 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
5223 expr = build2 (code, scalar_type, new_temp, adjustment_def);
5224 new_dest = vect_create_destination_var (scalar_dest, scalar_type);
5227 epilog_stmt = gimple_build_assign (new_dest, expr);
5228 new_temp = make_ssa_name (new_dest, epilog_stmt);
5229 gimple_assign_set_lhs (epilog_stmt, new_temp);
5230 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5231 if (nested_in_vect_loop)
5233 set_vinfo_for_stmt (epilog_stmt,
5234 new_stmt_vec_info (epilog_stmt, loop_vinfo));
5235 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (epilog_stmt)) =
5236 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_phi));
5238 if (!double_reduc)
5239 scalar_results.quick_push (new_temp);
5240 else
5241 scalar_results[0] = new_temp;
5243 else
5244 scalar_results[0] = new_temp;
5246 new_phis[0] = epilog_stmt;
5249 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
5250 phis with new adjusted scalar results, i.e., replace use <s_out0>
5251 with use <s_out4>.
5253 Transform:
5254 loop_exit:
5255 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5256 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5257 v_out2 = reduce <v_out1>
5258 s_out3 = extract_field <v_out2, 0>
5259 s_out4 = adjust_result <s_out3>
5260 use <s_out0>
5261 use <s_out0>
5263 into:
5265 loop_exit:
5266 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5267 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5268 v_out2 = reduce <v_out1>
5269 s_out3 = extract_field <v_out2, 0>
5270 s_out4 = adjust_result <s_out3>
5271 use <s_out4>
5272 use <s_out4> */
5275 /* In SLP reduction chain we reduce vector results into one vector if
5276 necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of
5277 the last stmt in the reduction chain, since we are looking for the loop
5278 exit phi node. */
5279 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
5281 gimple *dest_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1];
5282 /* Handle reduction patterns. */
5283 if (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt)))
5284 dest_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt));
5286 scalar_dest = gimple_assign_lhs (dest_stmt);
5287 group_size = 1;
5290 /* In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in
5291 case that GROUP_SIZE is greater than vectorization factor). Therefore, we
5292 need to match SCALAR_RESULTS with corresponding statements. The first
5293 (GROUP_SIZE / number of new vector stmts) scalar results correspond to
5294 the first vector stmt, etc.
5295 (RATIO is equal to (GROUP_SIZE / number of new vector stmts)). */
5296 if (group_size > new_phis.length ())
5298 ratio = group_size / new_phis.length ();
5299 gcc_assert (!(group_size % new_phis.length ()));
5301 else
5302 ratio = 1;
5304 for (k = 0; k < group_size; k++)
5306 if (k % ratio == 0)
5308 epilog_stmt = new_phis[k / ratio];
5309 reduction_phi = reduction_phis[k / ratio];
5310 if (double_reduc)
5311 inner_phi = inner_phis[k / ratio];
5314 if (slp_reduc)
5316 gimple *current_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[k];
5318 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (current_stmt));
5319 /* SLP statements can't participate in patterns. */
5320 gcc_assert (!orig_stmt);
5321 scalar_dest = gimple_assign_lhs (current_stmt);
5324 phis.create (3);
5325 /* Find the loop-closed-use at the loop exit of the original scalar
5326 result. (The reduction result is expected to have two immediate uses -
5327 one at the latch block, and one at the loop exit). */
5328 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5329 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))
5330 && !is_gimple_debug (USE_STMT (use_p)))
5331 phis.safe_push (USE_STMT (use_p));
5333 /* While we expect to have found an exit_phi because of loop-closed-ssa
5334 form we can end up without one if the scalar cycle is dead. */
5336 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5338 if (outer_loop)
5340 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
5341 gphi *vect_phi;
5343 /* FORNOW. Currently not supporting the case that an inner-loop
5344 reduction is not used in the outer-loop (but only outside the
5345 outer-loop), unless it is double reduction. */
5346 gcc_assert ((STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
5347 && !STMT_VINFO_LIVE_P (exit_phi_vinfo))
5348 || double_reduc);
5350 if (double_reduc)
5351 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = inner_phi;
5352 else
5353 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = epilog_stmt;
5354 if (!double_reduc
5355 || STMT_VINFO_DEF_TYPE (exit_phi_vinfo)
5356 != vect_double_reduction_def)
5357 continue;
5359 /* Handle double reduction:
5361 stmt1: s1 = phi <s0, s2> - double reduction phi (outer loop)
5362 stmt2: s3 = phi <s1, s4> - (regular) reduc phi (inner loop)
5363 stmt3: s4 = use (s3) - (regular) reduc stmt (inner loop)
5364 stmt4: s2 = phi <s4> - double reduction stmt (outer loop)
5366 At that point the regular reduction (stmt2 and stmt3) is
5367 already vectorized, as well as the exit phi node, stmt4.
5368 Here we vectorize the phi node of double reduction, stmt1, and
5369 update all relevant statements. */
5371 /* Go through all the uses of s2 to find double reduction phi
5372 node, i.e., stmt1 above. */
5373 orig_name = PHI_RESULT (exit_phi);
5374 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5376 stmt_vec_info use_stmt_vinfo;
5377 stmt_vec_info new_phi_vinfo;
5378 tree vect_phi_init, preheader_arg, vect_phi_res;
5379 basic_block bb = gimple_bb (use_stmt);
5380 gimple *use;
5382 /* Check that USE_STMT is really double reduction phi
5383 node. */
5384 if (gimple_code (use_stmt) != GIMPLE_PHI
5385 || gimple_phi_num_args (use_stmt) != 2
5386 || bb->loop_father != outer_loop)
5387 continue;
5388 use_stmt_vinfo = vinfo_for_stmt (use_stmt);
5389 if (!use_stmt_vinfo
5390 || STMT_VINFO_DEF_TYPE (use_stmt_vinfo)
5391 != vect_double_reduction_def)
5392 continue;
5394 /* Create vector phi node for double reduction:
5395 vs1 = phi <vs0, vs2>
5396 vs1 was created previously in this function by a call to
5397 vect_get_vec_def_for_operand and is stored in
5398 vec_initial_def;
5399 vs2 is defined by INNER_PHI, the vectorized EXIT_PHI;
5400 vs0 is created here. */
5402 /* Create vector phi node. */
5403 vect_phi = create_phi_node (vec_initial_def, bb);
5404 new_phi_vinfo = new_stmt_vec_info (vect_phi,
5405 loop_vec_info_for_loop (outer_loop));
5406 set_vinfo_for_stmt (vect_phi, new_phi_vinfo);
5408 /* Create vs0 - initial def of the double reduction phi. */
5409 preheader_arg = PHI_ARG_DEF_FROM_EDGE (use_stmt,
5410 loop_preheader_edge (outer_loop));
5411 vect_phi_init = get_initial_def_for_reduction
5412 (stmt, preheader_arg, NULL);
5414 /* Update phi node arguments with vs0 and vs2. */
5415 add_phi_arg (vect_phi, vect_phi_init,
5416 loop_preheader_edge (outer_loop),
5417 UNKNOWN_LOCATION);
5418 add_phi_arg (vect_phi, PHI_RESULT (inner_phi),
5419 loop_latch_edge (outer_loop), UNKNOWN_LOCATION);
5420 if (dump_enabled_p ())
5422 dump_printf_loc (MSG_NOTE, vect_location,
5423 "created double reduction phi node: ");
5424 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, vect_phi, 0);
5427 vect_phi_res = PHI_RESULT (vect_phi);
5429 /* Replace the use, i.e., set the correct vs1 in the regular
5430 reduction phi node. FORNOW, NCOPIES is always 1, so the
5431 loop is redundant. */
5432 use = reduction_phi;
5433 for (j = 0; j < ncopies; j++)
5435 edge pr_edge = loop_preheader_edge (loop);
5436 SET_PHI_ARG_DEF (use, pr_edge->dest_idx, vect_phi_res);
5437 use = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use));
5443 phis.release ();
5444 if (nested_in_vect_loop)
5446 if (double_reduc)
5447 loop = outer_loop;
5448 else
5449 continue;
5452 phis.create (3);
5453 /* Find the loop-closed-use at the loop exit of the original scalar
5454 result. (The reduction result is expected to have two immediate uses,
5455 one at the latch block, and one at the loop exit). For double
5456 reductions we are looking for exit phis of the outer loop. */
5457 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5459 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
5461 if (!is_gimple_debug (USE_STMT (use_p)))
5462 phis.safe_push (USE_STMT (use_p));
5464 else
5466 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
5468 tree phi_res = PHI_RESULT (USE_STMT (use_p));
5470 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
5472 if (!flow_bb_inside_loop_p (loop,
5473 gimple_bb (USE_STMT (phi_use_p)))
5474 && !is_gimple_debug (USE_STMT (phi_use_p)))
5475 phis.safe_push (USE_STMT (phi_use_p));
5481 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5483 /* Replace the uses: */
5484 orig_name = PHI_RESULT (exit_phi);
5485 scalar_result = scalar_results[k];
5486 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5487 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
5488 SET_USE (use_p, scalar_result);
5491 phis.release ();
5496 /* Function is_nonwrapping_integer_induction.
5498 Check if STMT (which is part of loop LOOP) both increments and
5499 does not cause overflow. */
5501 static bool
5502 is_nonwrapping_integer_induction (gimple *stmt, struct loop *loop)
5504 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
5505 tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
5506 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
5507 tree lhs_type = TREE_TYPE (gimple_phi_result (stmt));
5508 widest_int ni, max_loop_value, lhs_max;
5509 bool overflow = false;
5511 /* Make sure the loop is integer based. */
5512 if (TREE_CODE (base) != INTEGER_CST
5513 || TREE_CODE (step) != INTEGER_CST)
5514 return false;
5516 /* Check that the induction increments. */
5517 if (tree_int_cst_sgn (step) == -1)
5518 return false;
5520 /* Check that the max size of the loop will not wrap. */
5522 if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
5523 return true;
5525 if (! max_stmt_executions (loop, &ni))
5526 return false;
5528 max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
5529 &overflow);
5530 if (overflow)
5531 return false;
5533 max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
5534 TYPE_SIGN (lhs_type), &overflow);
5535 if (overflow)
5536 return false;
5538 return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
5539 <= TYPE_PRECISION (lhs_type));
5542 /* Function vectorizable_reduction.
5544 Check if STMT performs a reduction operation that can be vectorized.
5545 If VEC_STMT is also passed, vectorize the STMT: create a vectorized
5546 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
5547 Return FALSE if not a vectorizable STMT, TRUE otherwise.
5549 This function also handles reduction idioms (patterns) that have been
5550 recognized in advance during vect_pattern_recog. In this case, STMT may be
5551 of this form:
5552 X = pattern_expr (arg0, arg1, ..., X)
5553 and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original
5554 sequence that had been detected and replaced by the pattern-stmt (STMT).
5556 This function also handles reduction of condition expressions, for example:
5557 for (int i = 0; i < N; i++)
5558 if (a[i] < value)
5559 last = a[i];
5560 This is handled by vectorising the loop and creating an additional vector
5561 containing the loop indexes for which "a[i] < value" was true. In the
5562 function epilogue this is reduced to a single max value and then used to
5563 index into the vector of results.
5565 In some cases of reduction patterns, the type of the reduction variable X is
5566 different than the type of the other arguments of STMT.
5567 In such cases, the vectype that is used when transforming STMT into a vector
5568 stmt is different than the vectype that is used to determine the
5569 vectorization factor, because it consists of a different number of elements
5570 than the actual number of elements that are being operated upon in parallel.
5572 For example, consider an accumulation of shorts into an int accumulator.
5573 On some targets it's possible to vectorize this pattern operating on 8
5574 shorts at a time (hence, the vectype for purposes of determining the
5575 vectorization factor should be V8HI); on the other hand, the vectype that
5576 is used to create the vector form is actually V4SI (the type of the result).
5578 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
5579 indicates what is the actual level of parallelism (V8HI in the example), so
5580 that the right vectorization factor would be derived. This vectype
5581 corresponds to the type of arguments to the reduction stmt, and should *NOT*
5582 be used to create the vectorized stmt. The right vectype for the vectorized
5583 stmt is obtained from the type of the result X:
5584 get_vectype_for_scalar_type (TREE_TYPE (X))
5586 This means that, contrary to "regular" reductions (or "regular" stmts in
5587 general), the following equation:
5588 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X))
5589 does *NOT* necessarily hold for reduction patterns. */
5591 bool
5592 vectorizable_reduction (gimple *stmt, gimple_stmt_iterator *gsi,
5593 gimple **vec_stmt, slp_tree slp_node,
5594 slp_instance slp_node_instance)
5596 tree vec_dest;
5597 tree scalar_dest;
5598 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5599 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
5600 tree vectype_in = NULL_TREE;
5601 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5602 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5603 enum tree_code code, orig_code;
5604 internal_fn reduc_fn;
5605 machine_mode vec_mode;
5606 int op_type;
5607 optab optab;
5608 tree new_temp = NULL_TREE;
5609 gimple *def_stmt;
5610 enum vect_def_type dt, cond_reduc_dt = vect_unknown_def_type;
5611 tree scalar_type;
5612 bool is_simple_use;
5613 gimple *orig_stmt;
5614 stmt_vec_info orig_stmt_info = NULL;
5615 int i;
5616 int ncopies;
5617 int epilog_copies;
5618 stmt_vec_info prev_stmt_info, prev_phi_info;
5619 bool single_defuse_cycle = false;
5620 gimple *new_stmt = NULL;
5621 int j;
5622 tree ops[3];
5623 enum vect_def_type dts[3];
5624 bool nested_cycle = false, found_nested_cycle_def = false;
5625 bool double_reduc = false;
5626 basic_block def_bb;
5627 struct loop * def_stmt_loop, *outer_loop = NULL;
5628 tree def_arg;
5629 gimple *def_arg_stmt;
5630 auto_vec<tree> vec_oprnds0;
5631 auto_vec<tree> vec_oprnds1;
5632 auto_vec<tree> vec_oprnds2;
5633 auto_vec<tree> vect_defs;
5634 auto_vec<gimple *> phis;
5635 int vec_num;
5636 tree def0, tem;
5637 bool first_p = true;
5638 tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
5639 tree cond_reduc_val = NULL_TREE;
5641 /* Make sure it was already recognized as a reduction computation. */
5642 if (STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_reduction_def
5643 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_nested_cycle)
5644 return false;
5646 if (nested_in_vect_loop_p (loop, stmt))
5648 outer_loop = loop;
5649 loop = loop->inner;
5650 nested_cycle = true;
5653 /* In case of reduction chain we switch to the first stmt in the chain, but
5654 we don't update STMT_INFO, since only the last stmt is marked as reduction
5655 and has reduction properties. */
5656 if (GROUP_FIRST_ELEMENT (stmt_info)
5657 && GROUP_FIRST_ELEMENT (stmt_info) != stmt)
5659 stmt = GROUP_FIRST_ELEMENT (stmt_info);
5660 first_p = false;
5663 if (gimple_code (stmt) == GIMPLE_PHI)
5665 /* Analysis is fully done on the reduction stmt invocation. */
5666 if (! vec_stmt)
5668 if (slp_node)
5669 slp_node_instance->reduc_phis = slp_node;
5671 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
5672 return true;
5675 gimple *reduc_stmt = STMT_VINFO_REDUC_DEF (stmt_info);
5676 if (STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (reduc_stmt)))
5677 reduc_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (reduc_stmt));
5679 gcc_assert (is_gimple_assign (reduc_stmt));
5680 for (unsigned k = 1; k < gimple_num_ops (reduc_stmt); ++k)
5682 tree op = gimple_op (reduc_stmt, k);
5683 if (op == gimple_phi_result (stmt))
5684 continue;
5685 if (k == 1
5686 && gimple_assign_rhs_code (reduc_stmt) == COND_EXPR)
5687 continue;
5688 tem = get_vectype_for_scalar_type (TREE_TYPE (op));
5689 if (! vectype_in
5690 || TYPE_VECTOR_SUBPARTS (tem) < TYPE_VECTOR_SUBPARTS (vectype_in))
5691 vectype_in = tem;
5692 break;
5694 gcc_assert (vectype_in);
5696 if (slp_node)
5697 ncopies = 1;
5698 else
5699 ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
5701 use_operand_p use_p;
5702 gimple *use_stmt;
5703 if (ncopies > 1
5704 && (STMT_VINFO_RELEVANT (vinfo_for_stmt (reduc_stmt))
5705 <= vect_used_only_live)
5706 && single_imm_use (gimple_phi_result (stmt), &use_p, &use_stmt)
5707 && (use_stmt == reduc_stmt
5708 || (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use_stmt))
5709 == reduc_stmt)))
5710 single_defuse_cycle = true;
5712 /* Create the destination vector */
5713 scalar_dest = gimple_assign_lhs (reduc_stmt);
5714 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
5716 if (slp_node)
5717 /* The size vect_schedule_slp_instance computes is off for us. */
5718 vec_num = ((LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5719 * SLP_TREE_SCALAR_STMTS (slp_node).length ())
5720 / TYPE_VECTOR_SUBPARTS (vectype_in));
5721 else
5722 vec_num = 1;
5724 /* Generate the reduction PHIs upfront. */
5725 prev_phi_info = NULL;
5726 for (j = 0; j < ncopies; j++)
5728 if (j == 0 || !single_defuse_cycle)
5730 for (i = 0; i < vec_num; i++)
5732 /* Create the reduction-phi that defines the reduction
5733 operand. */
5734 gimple *new_phi = create_phi_node (vec_dest, loop->header);
5735 set_vinfo_for_stmt (new_phi,
5736 new_stmt_vec_info (new_phi, loop_vinfo));
5738 if (slp_node)
5739 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_phi);
5740 else
5742 if (j == 0)
5743 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_phi;
5744 else
5745 STMT_VINFO_RELATED_STMT (prev_phi_info) = new_phi;
5746 prev_phi_info = vinfo_for_stmt (new_phi);
5752 return true;
5755 /* 1. Is vectorizable reduction? */
5756 /* Not supportable if the reduction variable is used in the loop, unless
5757 it's a reduction chain. */
5758 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
5759 && !GROUP_FIRST_ELEMENT (stmt_info))
5760 return false;
5762 /* Reductions that are not used even in an enclosing outer-loop,
5763 are expected to be "live" (used out of the loop). */
5764 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
5765 && !STMT_VINFO_LIVE_P (stmt_info))
5766 return false;
5768 /* 2. Has this been recognized as a reduction pattern?
5770 Check if STMT represents a pattern that has been recognized
5771 in earlier analysis stages. For stmts that represent a pattern,
5772 the STMT_VINFO_RELATED_STMT field records the last stmt in
5773 the original sequence that constitutes the pattern. */
5775 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
5776 if (orig_stmt)
5778 orig_stmt_info = vinfo_for_stmt (orig_stmt);
5779 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
5780 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
5783 /* 3. Check the operands of the operation. The first operands are defined
5784 inside the loop body. The last operand is the reduction variable,
5785 which is defined by the loop-header-phi. */
5787 gcc_assert (is_gimple_assign (stmt));
5789 /* Flatten RHS. */
5790 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
5792 case GIMPLE_BINARY_RHS:
5793 code = gimple_assign_rhs_code (stmt);
5794 op_type = TREE_CODE_LENGTH (code);
5795 gcc_assert (op_type == binary_op);
5796 ops[0] = gimple_assign_rhs1 (stmt);
5797 ops[1] = gimple_assign_rhs2 (stmt);
5798 break;
5800 case GIMPLE_TERNARY_RHS:
5801 code = gimple_assign_rhs_code (stmt);
5802 op_type = TREE_CODE_LENGTH (code);
5803 gcc_assert (op_type == ternary_op);
5804 ops[0] = gimple_assign_rhs1 (stmt);
5805 ops[1] = gimple_assign_rhs2 (stmt);
5806 ops[2] = gimple_assign_rhs3 (stmt);
5807 break;
5809 case GIMPLE_UNARY_RHS:
5810 return false;
5812 default:
5813 gcc_unreachable ();
5816 if (code == COND_EXPR && slp_node)
5817 return false;
5819 scalar_dest = gimple_assign_lhs (stmt);
5820 scalar_type = TREE_TYPE (scalar_dest);
5821 if (!POINTER_TYPE_P (scalar_type) && !INTEGRAL_TYPE_P (scalar_type)
5822 && !SCALAR_FLOAT_TYPE_P (scalar_type))
5823 return false;
5825 /* Do not try to vectorize bit-precision reductions. */
5826 if (!type_has_mode_precision_p (scalar_type))
5827 return false;
5829 /* All uses but the last are expected to be defined in the loop.
5830 The last use is the reduction variable. In case of nested cycle this
5831 assumption is not true: we use reduc_index to record the index of the
5832 reduction variable. */
5833 gimple *reduc_def_stmt = NULL;
5834 int reduc_index = -1;
5835 for (i = 0; i < op_type; i++)
5837 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
5838 if (i == 0 && code == COND_EXPR)
5839 continue;
5841 is_simple_use = vect_is_simple_use (ops[i], loop_vinfo,
5842 &def_stmt, &dts[i], &tem);
5843 dt = dts[i];
5844 gcc_assert (is_simple_use);
5845 if (dt == vect_reduction_def)
5847 reduc_def_stmt = def_stmt;
5848 reduc_index = i;
5849 continue;
5851 else if (tem)
5853 /* To properly compute ncopies we are interested in the widest
5854 input type in case we're looking at a widening accumulation. */
5855 if (!vectype_in
5856 || TYPE_VECTOR_SUBPARTS (vectype_in) > TYPE_VECTOR_SUBPARTS (tem))
5857 vectype_in = tem;
5860 if (dt != vect_internal_def
5861 && dt != vect_external_def
5862 && dt != vect_constant_def
5863 && dt != vect_induction_def
5864 && !(dt == vect_nested_cycle && nested_cycle))
5865 return false;
5867 if (dt == vect_nested_cycle)
5869 found_nested_cycle_def = true;
5870 reduc_def_stmt = def_stmt;
5871 reduc_index = i;
5874 if (i == 1 && code == COND_EXPR)
5876 /* Record how value of COND_EXPR is defined. */
5877 if (dt == vect_constant_def)
5879 cond_reduc_dt = dt;
5880 cond_reduc_val = ops[i];
5882 if (dt == vect_induction_def && def_stmt != NULL
5883 && is_nonwrapping_integer_induction (def_stmt, loop))
5884 cond_reduc_dt = dt;
5888 if (!vectype_in)
5889 vectype_in = vectype_out;
5891 /* When vectorizing a reduction chain w/o SLP the reduction PHI is not
5892 directy used in stmt. */
5893 if (reduc_index == -1)
5895 if (orig_stmt)
5896 reduc_def_stmt = STMT_VINFO_REDUC_DEF (orig_stmt_info);
5897 else
5898 reduc_def_stmt = STMT_VINFO_REDUC_DEF (stmt_info);
5901 if (! reduc_def_stmt || gimple_code (reduc_def_stmt) != GIMPLE_PHI)
5902 return false;
5904 if (!(reduc_index == -1
5905 || dts[reduc_index] == vect_reduction_def
5906 || dts[reduc_index] == vect_nested_cycle
5907 || ((dts[reduc_index] == vect_internal_def
5908 || dts[reduc_index] == vect_external_def
5909 || dts[reduc_index] == vect_constant_def
5910 || dts[reduc_index] == vect_induction_def)
5911 && nested_cycle && found_nested_cycle_def)))
5913 /* For pattern recognized stmts, orig_stmt might be a reduction,
5914 but some helper statements for the pattern might not, or
5915 might be COND_EXPRs with reduction uses in the condition. */
5916 gcc_assert (orig_stmt);
5917 return false;
5920 stmt_vec_info reduc_def_info = vinfo_for_stmt (reduc_def_stmt);
5921 enum vect_reduction_type v_reduc_type
5922 = STMT_VINFO_REDUC_TYPE (reduc_def_info);
5923 gimple *tmp = STMT_VINFO_REDUC_DEF (reduc_def_info);
5925 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = v_reduc_type;
5926 /* If we have a condition reduction, see if we can simplify it further. */
5927 if (v_reduc_type == COND_REDUCTION)
5929 if (cond_reduc_dt == vect_induction_def)
5931 if (dump_enabled_p ())
5932 dump_printf_loc (MSG_NOTE, vect_location,
5933 "condition expression based on "
5934 "integer induction.\n");
5935 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5936 = INTEGER_INDUC_COND_REDUCTION;
5939 /* Loop peeling modifies initial value of reduction PHI, which
5940 makes the reduction stmt to be transformed different to the
5941 original stmt analyzed. We need to record reduction code for
5942 CONST_COND_REDUCTION type reduction at analyzing stage, thus
5943 it can be used directly at transform stage. */
5944 if (STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MAX_EXPR
5945 || STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MIN_EXPR)
5947 /* Also set the reduction type to CONST_COND_REDUCTION. */
5948 gcc_assert (cond_reduc_dt == vect_constant_def);
5949 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = CONST_COND_REDUCTION;
5951 else if (cond_reduc_dt == vect_constant_def)
5953 enum vect_def_type cond_initial_dt;
5954 gimple *def_stmt = SSA_NAME_DEF_STMT (ops[reduc_index]);
5955 tree cond_initial_val
5956 = PHI_ARG_DEF_FROM_EDGE (def_stmt, loop_preheader_edge (loop));
5958 gcc_assert (cond_reduc_val != NULL_TREE);
5959 vect_is_simple_use (cond_initial_val, loop_vinfo,
5960 &def_stmt, &cond_initial_dt);
5961 if (cond_initial_dt == vect_constant_def
5962 && types_compatible_p (TREE_TYPE (cond_initial_val),
5963 TREE_TYPE (cond_reduc_val)))
5965 tree e = fold_binary (LE_EXPR, boolean_type_node,
5966 cond_initial_val, cond_reduc_val);
5967 if (e && (integer_onep (e) || integer_zerop (e)))
5969 if (dump_enabled_p ())
5970 dump_printf_loc (MSG_NOTE, vect_location,
5971 "condition expression based on "
5972 "compile time constant.\n");
5973 /* Record reduction code at analysis stage. */
5974 STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info)
5975 = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
5976 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5977 = CONST_COND_REDUCTION;
5983 if (orig_stmt)
5984 gcc_assert (tmp == orig_stmt
5985 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == orig_stmt);
5986 else
5987 /* We changed STMT to be the first stmt in reduction chain, hence we
5988 check that in this case the first element in the chain is STMT. */
5989 gcc_assert (stmt == tmp
5990 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == stmt);
5992 if (STMT_VINFO_LIVE_P (vinfo_for_stmt (reduc_def_stmt)))
5993 return false;
5995 if (slp_node)
5996 ncopies = 1;
5997 else
5998 ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
6000 gcc_assert (ncopies >= 1);
6002 vec_mode = TYPE_MODE (vectype_in);
6004 if (code == COND_EXPR)
6006 /* Only call during the analysis stage, otherwise we'll lose
6007 STMT_VINFO_TYPE. */
6008 if (!vec_stmt && !vectorizable_condition (stmt, gsi, NULL,
6009 ops[reduc_index], 0, NULL))
6011 if (dump_enabled_p ())
6012 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6013 "unsupported condition in reduction\n");
6014 return false;
6017 else
6019 /* 4. Supportable by target? */
6021 if (code == LSHIFT_EXPR || code == RSHIFT_EXPR
6022 || code == LROTATE_EXPR || code == RROTATE_EXPR)
6024 /* Shifts and rotates are only supported by vectorizable_shifts,
6025 not vectorizable_reduction. */
6026 if (dump_enabled_p ())
6027 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6028 "unsupported shift or rotation.\n");
6029 return false;
6032 /* 4.1. check support for the operation in the loop */
6033 optab = optab_for_tree_code (code, vectype_in, optab_default);
6034 if (!optab)
6036 if (dump_enabled_p ())
6037 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6038 "no optab.\n");
6040 return false;
6043 if (optab_handler (optab, vec_mode) == CODE_FOR_nothing)
6045 if (dump_enabled_p ())
6046 dump_printf (MSG_NOTE, "op not supported by target.\n");
6048 if (GET_MODE_SIZE (vec_mode) != UNITS_PER_WORD
6049 || !vect_worthwhile_without_simd_p (loop_vinfo, code))
6050 return false;
6052 if (dump_enabled_p ())
6053 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
6056 /* Worthwhile without SIMD support? */
6057 if (!VECTOR_MODE_P (TYPE_MODE (vectype_in))
6058 && !vect_worthwhile_without_simd_p (loop_vinfo, code))
6060 if (dump_enabled_p ())
6061 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6062 "not worthwhile without SIMD support.\n");
6064 return false;
6068 /* 4.2. Check support for the epilog operation.
6070 If STMT represents a reduction pattern, then the type of the
6071 reduction variable may be different than the type of the rest
6072 of the arguments. For example, consider the case of accumulation
6073 of shorts into an int accumulator; The original code:
6074 S1: int_a = (int) short_a;
6075 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
6077 was replaced with:
6078 STMT: int_acc = widen_sum <short_a, int_acc>
6080 This means that:
6081 1. The tree-code that is used to create the vector operation in the
6082 epilog code (that reduces the partial results) is not the
6083 tree-code of STMT, but is rather the tree-code of the original
6084 stmt from the pattern that STMT is replacing. I.e, in the example
6085 above we want to use 'widen_sum' in the loop, but 'plus' in the
6086 epilog.
6087 2. The type (mode) we use to check available target support
6088 for the vector operation to be created in the *epilog*, is
6089 determined by the type of the reduction variable (in the example
6090 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
6091 However the type (mode) we use to check available target support
6092 for the vector operation to be created *inside the loop*, is
6093 determined by the type of the other arguments to STMT (in the
6094 example we'd check this: optab_handler (widen_sum_optab,
6095 vect_short_mode)).
6097 This is contrary to "regular" reductions, in which the types of all
6098 the arguments are the same as the type of the reduction variable.
6099 For "regular" reductions we can therefore use the same vector type
6100 (and also the same tree-code) when generating the epilog code and
6101 when generating the code inside the loop. */
6103 if (orig_stmt)
6105 /* This is a reduction pattern: get the vectype from the type of the
6106 reduction variable, and get the tree-code from orig_stmt. */
6107 gcc_assert (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
6108 == TREE_CODE_REDUCTION);
6109 orig_code = gimple_assign_rhs_code (orig_stmt);
6110 gcc_assert (vectype_out);
6111 vec_mode = TYPE_MODE (vectype_out);
6113 else
6115 /* Regular reduction: use the same vectype and tree-code as used for
6116 the vector code inside the loop can be used for the epilog code. */
6117 orig_code = code;
6119 if (code == MINUS_EXPR)
6120 orig_code = PLUS_EXPR;
6122 /* For simple condition reductions, replace with the actual expression
6123 we want to base our reduction around. */
6124 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == CONST_COND_REDUCTION)
6126 orig_code = STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info);
6127 gcc_assert (orig_code == MAX_EXPR || orig_code == MIN_EXPR);
6129 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
6130 == INTEGER_INDUC_COND_REDUCTION)
6131 orig_code = MAX_EXPR;
6134 if (nested_cycle)
6136 def_bb = gimple_bb (reduc_def_stmt);
6137 def_stmt_loop = def_bb->loop_father;
6138 def_arg = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
6139 loop_preheader_edge (def_stmt_loop));
6140 if (TREE_CODE (def_arg) == SSA_NAME
6141 && (def_arg_stmt = SSA_NAME_DEF_STMT (def_arg))
6142 && gimple_code (def_arg_stmt) == GIMPLE_PHI
6143 && flow_bb_inside_loop_p (outer_loop, gimple_bb (def_arg_stmt))
6144 && vinfo_for_stmt (def_arg_stmt)
6145 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_arg_stmt))
6146 == vect_double_reduction_def)
6147 double_reduc = true;
6150 reduc_fn = IFN_LAST;
6152 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != COND_REDUCTION)
6154 if (reduction_fn_for_scalar_code (orig_code, &reduc_fn))
6156 if (reduc_fn != IFN_LAST
6157 && !direct_internal_fn_supported_p (reduc_fn, vectype_out,
6158 OPTIMIZE_FOR_SPEED))
6160 if (dump_enabled_p ())
6161 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6162 "reduc op not supported by target.\n");
6164 reduc_fn = IFN_LAST;
6167 else
6169 if (!nested_cycle || double_reduc)
6171 if (dump_enabled_p ())
6172 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6173 "no reduc code for scalar code.\n");
6175 return false;
6179 else
6181 int scalar_precision
6182 = GET_MODE_PRECISION (SCALAR_TYPE_MODE (scalar_type));
6183 cr_index_scalar_type = make_unsigned_type (scalar_precision);
6184 cr_index_vector_type = build_vector_type
6185 (cr_index_scalar_type, TYPE_VECTOR_SUBPARTS (vectype_out));
6187 if (direct_internal_fn_supported_p (IFN_REDUC_MAX, cr_index_vector_type,
6188 OPTIMIZE_FOR_SPEED))
6189 reduc_fn = IFN_REDUC_MAX;
6192 if ((double_reduc
6193 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != TREE_CODE_REDUCTION)
6194 && ncopies > 1)
6196 if (dump_enabled_p ())
6197 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6198 "multiple types in double reduction or condition "
6199 "reduction.\n");
6200 return false;
6203 /* In case of widenning multiplication by a constant, we update the type
6204 of the constant to be the type of the other operand. We check that the
6205 constant fits the type in the pattern recognition pass. */
6206 if (code == DOT_PROD_EXPR
6207 && !types_compatible_p (TREE_TYPE (ops[0]), TREE_TYPE (ops[1])))
6209 if (TREE_CODE (ops[0]) == INTEGER_CST)
6210 ops[0] = fold_convert (TREE_TYPE (ops[1]), ops[0]);
6211 else if (TREE_CODE (ops[1]) == INTEGER_CST)
6212 ops[1] = fold_convert (TREE_TYPE (ops[0]), ops[1]);
6213 else
6215 if (dump_enabled_p ())
6216 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6217 "invalid types in dot-prod\n");
6219 return false;
6223 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
6225 widest_int ni;
6227 if (! max_loop_iterations (loop, &ni))
6229 if (dump_enabled_p ())
6230 dump_printf_loc (MSG_NOTE, vect_location,
6231 "loop count not known, cannot create cond "
6232 "reduction.\n");
6233 return false;
6235 /* Convert backedges to iterations. */
6236 ni += 1;
6238 /* The additional index will be the same type as the condition. Check
6239 that the loop can fit into this less one (because we'll use up the
6240 zero slot for when there are no matches). */
6241 tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
6242 if (wi::geu_p (ni, wi::to_widest (max_index)))
6244 if (dump_enabled_p ())
6245 dump_printf_loc (MSG_NOTE, vect_location,
6246 "loop size is greater than data size.\n");
6247 return false;
6251 /* In case the vectorization factor (VF) is bigger than the number
6252 of elements that we can fit in a vectype (nunits), we have to generate
6253 more than one vector stmt - i.e - we need to "unroll" the
6254 vector stmt by a factor VF/nunits. For more details see documentation
6255 in vectorizable_operation. */
6257 /* If the reduction is used in an outer loop we need to generate
6258 VF intermediate results, like so (e.g. for ncopies=2):
6259 r0 = phi (init, r0)
6260 r1 = phi (init, r1)
6261 r0 = x0 + r0;
6262 r1 = x1 + r1;
6263 (i.e. we generate VF results in 2 registers).
6264 In this case we have a separate def-use cycle for each copy, and therefore
6265 for each copy we get the vector def for the reduction variable from the
6266 respective phi node created for this copy.
6268 Otherwise (the reduction is unused in the loop nest), we can combine
6269 together intermediate results, like so (e.g. for ncopies=2):
6270 r = phi (init, r)
6271 r = x0 + r;
6272 r = x1 + r;
6273 (i.e. we generate VF/2 results in a single register).
6274 In this case for each copy we get the vector def for the reduction variable
6275 from the vectorized reduction operation generated in the previous iteration.
6277 This only works when we see both the reduction PHI and its only consumer
6278 in vectorizable_reduction and there are no intermediate stmts
6279 participating. */
6280 use_operand_p use_p;
6281 gimple *use_stmt;
6282 if (ncopies > 1
6283 && (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
6284 && single_imm_use (gimple_phi_result (reduc_def_stmt), &use_p, &use_stmt)
6285 && (use_stmt == stmt
6286 || STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use_stmt)) == stmt))
6288 single_defuse_cycle = true;
6289 epilog_copies = 1;
6291 else
6292 epilog_copies = ncopies;
6294 /* If the reduction stmt is one of the patterns that have lane
6295 reduction embedded we cannot handle the case of ! single_defuse_cycle. */
6296 if ((ncopies > 1
6297 && ! single_defuse_cycle)
6298 && (code == DOT_PROD_EXPR
6299 || code == WIDEN_SUM_EXPR
6300 || code == SAD_EXPR))
6302 if (dump_enabled_p ())
6303 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6304 "multi def-use cycle not possible for lane-reducing "
6305 "reduction operation\n");
6306 return false;
6309 if (!vec_stmt) /* transformation not required. */
6311 if (first_p)
6312 vect_model_reduction_cost (stmt_info, reduc_fn, ncopies);
6313 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
6314 return true;
6317 /* Transform. */
6319 if (dump_enabled_p ())
6320 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
6322 /* FORNOW: Multiple types are not supported for condition. */
6323 if (code == COND_EXPR)
6324 gcc_assert (ncopies == 1);
6326 /* Create the destination vector */
6327 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
6329 prev_stmt_info = NULL;
6330 prev_phi_info = NULL;
6331 if (slp_node)
6332 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6333 else
6335 vec_num = 1;
6336 vec_oprnds0.create (1);
6337 vec_oprnds1.create (1);
6338 if (op_type == ternary_op)
6339 vec_oprnds2.create (1);
6342 phis.create (vec_num);
6343 vect_defs.create (vec_num);
6344 if (!slp_node)
6345 vect_defs.quick_push (NULL_TREE);
6347 if (slp_node)
6348 phis.splice (SLP_TREE_VEC_STMTS (slp_node_instance->reduc_phis));
6349 else
6350 phis.quick_push (STMT_VINFO_VEC_STMT (vinfo_for_stmt (reduc_def_stmt)));
6352 for (j = 0; j < ncopies; j++)
6354 if (code == COND_EXPR)
6356 gcc_assert (!slp_node);
6357 vectorizable_condition (stmt, gsi, vec_stmt,
6358 PHI_RESULT (phis[0]),
6359 reduc_index, NULL);
6360 /* Multiple types are not supported for condition. */
6361 break;
6364 /* Handle uses. */
6365 if (j == 0)
6367 if (slp_node)
6369 /* Get vec defs for all the operands except the reduction index,
6370 ensuring the ordering of the ops in the vector is kept. */
6371 auto_vec<tree, 3> slp_ops;
6372 auto_vec<vec<tree>, 3> vec_defs;
6374 slp_ops.quick_push (ops[0]);
6375 slp_ops.quick_push (ops[1]);
6376 if (op_type == ternary_op)
6377 slp_ops.quick_push (ops[2]);
6379 vect_get_slp_defs (slp_ops, slp_node, &vec_defs);
6381 vec_oprnds0.safe_splice (vec_defs[0]);
6382 vec_defs[0].release ();
6383 vec_oprnds1.safe_splice (vec_defs[1]);
6384 vec_defs[1].release ();
6385 if (op_type == ternary_op)
6387 vec_oprnds2.safe_splice (vec_defs[2]);
6388 vec_defs[2].release ();
6391 else
6393 vec_oprnds0.quick_push
6394 (vect_get_vec_def_for_operand (ops[0], stmt));
6395 vec_oprnds1.quick_push
6396 (vect_get_vec_def_for_operand (ops[1], stmt));
6397 if (op_type == ternary_op)
6398 vec_oprnds2.quick_push
6399 (vect_get_vec_def_for_operand (ops[2], stmt));
6402 else
6404 if (!slp_node)
6406 gcc_assert (reduc_index != -1 || ! single_defuse_cycle);
6408 if (single_defuse_cycle && reduc_index == 0)
6409 vec_oprnds0[0] = gimple_assign_lhs (new_stmt);
6410 else
6411 vec_oprnds0[0]
6412 = vect_get_vec_def_for_stmt_copy (dts[0], vec_oprnds0[0]);
6413 if (single_defuse_cycle && reduc_index == 1)
6414 vec_oprnds1[0] = gimple_assign_lhs (new_stmt);
6415 else
6416 vec_oprnds1[0]
6417 = vect_get_vec_def_for_stmt_copy (dts[1], vec_oprnds1[0]);
6418 if (op_type == ternary_op)
6420 if (single_defuse_cycle && reduc_index == 2)
6421 vec_oprnds2[0] = gimple_assign_lhs (new_stmt);
6422 else
6423 vec_oprnds2[0]
6424 = vect_get_vec_def_for_stmt_copy (dts[2], vec_oprnds2[0]);
6429 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
6431 tree vop[3] = { def0, vec_oprnds1[i], NULL_TREE };
6432 if (op_type == ternary_op)
6433 vop[2] = vec_oprnds2[i];
6435 new_temp = make_ssa_name (vec_dest, new_stmt);
6436 new_stmt = gimple_build_assign (new_temp, code,
6437 vop[0], vop[1], vop[2]);
6438 vect_finish_stmt_generation (stmt, new_stmt, gsi);
6440 if (slp_node)
6442 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
6443 vect_defs.quick_push (new_temp);
6445 else
6446 vect_defs[0] = new_temp;
6449 if (slp_node)
6450 continue;
6452 if (j == 0)
6453 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt;
6454 else
6455 STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt;
6457 prev_stmt_info = vinfo_for_stmt (new_stmt);
6460 /* Finalize the reduction-phi (set its arguments) and create the
6461 epilog reduction code. */
6462 if ((!single_defuse_cycle || code == COND_EXPR) && !slp_node)
6463 vect_defs[0] = gimple_assign_lhs (*vec_stmt);
6465 vect_create_epilog_for_reduction (vect_defs, stmt, reduc_def_stmt,
6466 epilog_copies, reduc_fn, phis,
6467 double_reduc, slp_node, slp_node_instance);
6469 return true;
6472 /* Function vect_min_worthwhile_factor.
6474 For a loop where we could vectorize the operation indicated by CODE,
6475 return the minimum vectorization factor that makes it worthwhile
6476 to use generic vectors. */
6478 vect_min_worthwhile_factor (enum tree_code code)
6480 switch (code)
6482 case PLUS_EXPR:
6483 case MINUS_EXPR:
6484 case NEGATE_EXPR:
6485 return 4;
6487 case BIT_AND_EXPR:
6488 case BIT_IOR_EXPR:
6489 case BIT_XOR_EXPR:
6490 case BIT_NOT_EXPR:
6491 return 2;
6493 default:
6494 return INT_MAX;
6498 /* Return true if VINFO indicates we are doing loop vectorization and if
6499 it is worth decomposing CODE operations into scalar operations for
6500 that loop's vectorization factor. */
6502 bool
6503 vect_worthwhile_without_simd_p (vec_info *vinfo, tree_code code)
6505 loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
6506 return (loop_vinfo
6507 && (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
6508 >= vect_min_worthwhile_factor (code)));
6511 /* Function vectorizable_induction
6513 Check if PHI performs an induction computation that can be vectorized.
6514 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
6515 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
6516 Return FALSE if not a vectorizable STMT, TRUE otherwise. */
6518 bool
6519 vectorizable_induction (gimple *phi,
6520 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6521 gimple **vec_stmt, slp_tree slp_node)
6523 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
6524 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6525 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6526 unsigned ncopies;
6527 bool nested_in_vect_loop = false;
6528 struct loop *iv_loop;
6529 tree vec_def;
6530 edge pe = loop_preheader_edge (loop);
6531 basic_block new_bb;
6532 tree new_vec, vec_init, vec_step, t;
6533 tree new_name;
6534 gimple *new_stmt;
6535 gphi *induction_phi;
6536 tree induc_def, vec_dest;
6537 tree init_expr, step_expr;
6538 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6539 unsigned i;
6540 tree expr;
6541 gimple_seq stmts;
6542 imm_use_iterator imm_iter;
6543 use_operand_p use_p;
6544 gimple *exit_phi;
6545 edge latch_e;
6546 tree loop_arg;
6547 gimple_stmt_iterator si;
6548 basic_block bb = gimple_bb (phi);
6550 if (gimple_code (phi) != GIMPLE_PHI)
6551 return false;
6553 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6554 return false;
6556 /* Make sure it was recognized as induction computation. */
6557 if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
6558 return false;
6560 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6561 unsigned nunits = TYPE_VECTOR_SUBPARTS (vectype);
6563 if (slp_node)
6564 ncopies = 1;
6565 else
6566 ncopies = vect_get_num_copies (loop_vinfo, vectype);
6567 gcc_assert (ncopies >= 1);
6569 /* FORNOW. These restrictions should be relaxed. */
6570 if (nested_in_vect_loop_p (loop, phi))
6572 imm_use_iterator imm_iter;
6573 use_operand_p use_p;
6574 gimple *exit_phi;
6575 edge latch_e;
6576 tree loop_arg;
6578 if (ncopies > 1)
6580 if (dump_enabled_p ())
6581 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6582 "multiple types in nested loop.\n");
6583 return false;
6586 /* FORNOW: outer loop induction with SLP not supported. */
6587 if (STMT_SLP_TYPE (stmt_info))
6588 return false;
6590 exit_phi = NULL;
6591 latch_e = loop_latch_edge (loop->inner);
6592 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
6593 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
6595 gimple *use_stmt = USE_STMT (use_p);
6596 if (is_gimple_debug (use_stmt))
6597 continue;
6599 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
6601 exit_phi = use_stmt;
6602 break;
6605 if (exit_phi)
6607 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
6608 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
6609 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
6611 if (dump_enabled_p ())
6612 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6613 "inner-loop induction only used outside "
6614 "of the outer vectorized loop.\n");
6615 return false;
6619 nested_in_vect_loop = true;
6620 iv_loop = loop->inner;
6622 else
6623 iv_loop = loop;
6624 gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
6626 if (!vec_stmt) /* transformation not required. */
6628 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
6629 if (dump_enabled_p ())
6630 dump_printf_loc (MSG_NOTE, vect_location,
6631 "=== vectorizable_induction ===\n");
6632 vect_model_induction_cost (stmt_info, ncopies);
6633 return true;
6636 /* Transform. */
6638 /* Compute a vector variable, initialized with the first VF values of
6639 the induction variable. E.g., for an iv with IV_PHI='X' and
6640 evolution S, for a vector of 4 units, we want to compute:
6641 [X, X + S, X + 2*S, X + 3*S]. */
6643 if (dump_enabled_p ())
6644 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
6646 latch_e = loop_latch_edge (iv_loop);
6647 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
6649 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
6650 gcc_assert (step_expr != NULL_TREE);
6652 pe = loop_preheader_edge (iv_loop);
6653 init_expr = PHI_ARG_DEF_FROM_EDGE (phi,
6654 loop_preheader_edge (iv_loop));
6656 /* Convert the step to the desired type. */
6657 stmts = NULL;
6658 step_expr = gimple_convert (&stmts, TREE_TYPE (vectype), step_expr);
6659 if (stmts)
6661 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
6662 gcc_assert (!new_bb);
6665 /* Find the first insertion point in the BB. */
6666 si = gsi_after_labels (bb);
6668 /* For SLP induction we have to generate several IVs as for example
6669 with group size 3 we need [i, i, i, i + S] [i + S, i + S, i + 2*S, i + 2*S]
6670 [i + 2*S, i + 3*S, i + 3*S, i + 3*S]. The step is the same uniform
6671 [VF*S, VF*S, VF*S, VF*S] for all. */
6672 if (slp_node)
6674 /* Convert the init to the desired type. */
6675 stmts = NULL;
6676 init_expr = gimple_convert (&stmts, TREE_TYPE (vectype), init_expr);
6677 if (stmts)
6679 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
6680 gcc_assert (!new_bb);
6683 /* Generate [VF*S, VF*S, ... ]. */
6684 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
6686 expr = build_int_cst (integer_type_node, vf);
6687 expr = fold_convert (TREE_TYPE (step_expr), expr);
6689 else
6690 expr = build_int_cst (TREE_TYPE (step_expr), vf);
6691 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
6692 expr, step_expr);
6693 if (! CONSTANT_CLASS_P (new_name))
6694 new_name = vect_init_vector (phi, new_name,
6695 TREE_TYPE (step_expr), NULL);
6696 new_vec = build_vector_from_val (vectype, new_name);
6697 vec_step = vect_init_vector (phi, new_vec, vectype, NULL);
6699 /* Now generate the IVs. */
6700 unsigned group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
6701 unsigned nvects = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6702 unsigned elts = nunits * nvects;
6703 unsigned nivs = least_common_multiple (group_size, nunits) / nunits;
6704 gcc_assert (elts % group_size == 0);
6705 tree elt = init_expr;
6706 unsigned ivn;
6707 for (ivn = 0; ivn < nivs; ++ivn)
6709 tree_vector_builder elts (vectype, nunits, 1);
6710 stmts = NULL;
6711 for (unsigned eltn = 0; eltn < nunits; ++eltn)
6713 if (ivn*nunits + eltn >= group_size
6714 && (ivn*nunits + eltn) % group_size == 0)
6715 elt = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (elt),
6716 elt, step_expr);
6717 elts.quick_push (elt);
6719 vec_init = gimple_build_vector (&stmts, &elts);
6720 if (stmts)
6722 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
6723 gcc_assert (!new_bb);
6726 /* Create the induction-phi that defines the induction-operand. */
6727 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
6728 induction_phi = create_phi_node (vec_dest, iv_loop->header);
6729 set_vinfo_for_stmt (induction_phi,
6730 new_stmt_vec_info (induction_phi, loop_vinfo));
6731 induc_def = PHI_RESULT (induction_phi);
6733 /* Create the iv update inside the loop */
6734 vec_def = make_ssa_name (vec_dest);
6735 new_stmt = gimple_build_assign (vec_def, PLUS_EXPR, induc_def, vec_step);
6736 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
6737 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo));
6739 /* Set the arguments of the phi node: */
6740 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
6741 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
6742 UNKNOWN_LOCATION);
6744 SLP_TREE_VEC_STMTS (slp_node).quick_push (induction_phi);
6747 /* Re-use IVs when we can. */
6748 if (ivn < nvects)
6750 unsigned vfp
6751 = least_common_multiple (group_size, nunits) / group_size;
6752 /* Generate [VF'*S, VF'*S, ... ]. */
6753 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
6755 expr = build_int_cst (integer_type_node, vfp);
6756 expr = fold_convert (TREE_TYPE (step_expr), expr);
6758 else
6759 expr = build_int_cst (TREE_TYPE (step_expr), vfp);
6760 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
6761 expr, step_expr);
6762 if (! CONSTANT_CLASS_P (new_name))
6763 new_name = vect_init_vector (phi, new_name,
6764 TREE_TYPE (step_expr), NULL);
6765 new_vec = build_vector_from_val (vectype, new_name);
6766 vec_step = vect_init_vector (phi, new_vec, vectype, NULL);
6767 for (; ivn < nvects; ++ivn)
6769 gimple *iv = SLP_TREE_VEC_STMTS (slp_node)[ivn - nivs];
6770 tree def;
6771 if (gimple_code (iv) == GIMPLE_PHI)
6772 def = gimple_phi_result (iv);
6773 else
6774 def = gimple_assign_lhs (iv);
6775 new_stmt = gimple_build_assign (make_ssa_name (vectype),
6776 PLUS_EXPR,
6777 def, vec_step);
6778 if (gimple_code (iv) == GIMPLE_PHI)
6779 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
6780 else
6782 gimple_stmt_iterator tgsi = gsi_for_stmt (iv);
6783 gsi_insert_after (&tgsi, new_stmt, GSI_CONTINUE_LINKING);
6785 set_vinfo_for_stmt (new_stmt,
6786 new_stmt_vec_info (new_stmt, loop_vinfo));
6787 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
6791 return true;
6794 /* Create the vector that holds the initial_value of the induction. */
6795 if (nested_in_vect_loop)
6797 /* iv_loop is nested in the loop to be vectorized. init_expr had already
6798 been created during vectorization of previous stmts. We obtain it
6799 from the STMT_VINFO_VEC_STMT of the defining stmt. */
6800 vec_init = vect_get_vec_def_for_operand (init_expr, phi);
6801 /* If the initial value is not of proper type, convert it. */
6802 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
6804 new_stmt
6805 = gimple_build_assign (vect_get_new_ssa_name (vectype,
6806 vect_simple_var,
6807 "vec_iv_"),
6808 VIEW_CONVERT_EXPR,
6809 build1 (VIEW_CONVERT_EXPR, vectype,
6810 vec_init));
6811 vec_init = gimple_assign_lhs (new_stmt);
6812 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
6813 new_stmt);
6814 gcc_assert (!new_bb);
6815 set_vinfo_for_stmt (new_stmt,
6816 new_stmt_vec_info (new_stmt, loop_vinfo));
6819 else
6821 /* iv_loop is the loop to be vectorized. Create:
6822 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
6823 stmts = NULL;
6824 new_name = gimple_convert (&stmts, TREE_TYPE (vectype), init_expr);
6826 tree_vector_builder elts (vectype, nunits, 1);
6827 elts.quick_push (new_name);
6828 for (i = 1; i < nunits; i++)
6830 /* Create: new_name_i = new_name + step_expr */
6831 new_name = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (new_name),
6832 new_name, step_expr);
6833 elts.quick_push (new_name);
6835 /* Create a vector from [new_name_0, new_name_1, ...,
6836 new_name_nunits-1] */
6837 vec_init = gimple_build_vector (&stmts, &elts);
6838 if (stmts)
6840 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
6841 gcc_assert (!new_bb);
6846 /* Create the vector that holds the step of the induction. */
6847 if (nested_in_vect_loop)
6848 /* iv_loop is nested in the loop to be vectorized. Generate:
6849 vec_step = [S, S, S, S] */
6850 new_name = step_expr;
6851 else
6853 /* iv_loop is the loop to be vectorized. Generate:
6854 vec_step = [VF*S, VF*S, VF*S, VF*S] */
6855 gimple_seq seq = NULL;
6856 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
6858 expr = build_int_cst (integer_type_node, vf);
6859 expr = gimple_build (&seq, FLOAT_EXPR, TREE_TYPE (step_expr), expr);
6861 else
6862 expr = build_int_cst (TREE_TYPE (step_expr), vf);
6863 new_name = gimple_build (&seq, MULT_EXPR, TREE_TYPE (step_expr),
6864 expr, step_expr);
6865 if (seq)
6867 new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
6868 gcc_assert (!new_bb);
6872 t = unshare_expr (new_name);
6873 gcc_assert (CONSTANT_CLASS_P (new_name)
6874 || TREE_CODE (new_name) == SSA_NAME);
6875 new_vec = build_vector_from_val (vectype, t);
6876 vec_step = vect_init_vector (phi, new_vec, vectype, NULL);
6879 /* Create the following def-use cycle:
6880 loop prolog:
6881 vec_init = ...
6882 vec_step = ...
6883 loop:
6884 vec_iv = PHI <vec_init, vec_loop>
6886 STMT
6888 vec_loop = vec_iv + vec_step; */
6890 /* Create the induction-phi that defines the induction-operand. */
6891 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
6892 induction_phi = create_phi_node (vec_dest, iv_loop->header);
6893 set_vinfo_for_stmt (induction_phi,
6894 new_stmt_vec_info (induction_phi, loop_vinfo));
6895 induc_def = PHI_RESULT (induction_phi);
6897 /* Create the iv update inside the loop */
6898 vec_def = make_ssa_name (vec_dest);
6899 new_stmt = gimple_build_assign (vec_def, PLUS_EXPR, induc_def, vec_step);
6900 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
6901 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo));
6903 /* Set the arguments of the phi node: */
6904 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
6905 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
6906 UNKNOWN_LOCATION);
6908 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = induction_phi;
6910 /* In case that vectorization factor (VF) is bigger than the number
6911 of elements that we can fit in a vectype (nunits), we have to generate
6912 more than one vector stmt - i.e - we need to "unroll" the
6913 vector stmt by a factor VF/nunits. For more details see documentation
6914 in vectorizable_operation. */
6916 if (ncopies > 1)
6918 gimple_seq seq = NULL;
6919 stmt_vec_info prev_stmt_vinfo;
6920 /* FORNOW. This restriction should be relaxed. */
6921 gcc_assert (!nested_in_vect_loop);
6923 /* Create the vector that holds the step of the induction. */
6924 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
6926 expr = build_int_cst (integer_type_node, nunits);
6927 expr = gimple_build (&seq, FLOAT_EXPR, TREE_TYPE (step_expr), expr);
6929 else
6930 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
6931 new_name = gimple_build (&seq, MULT_EXPR, TREE_TYPE (step_expr),
6932 expr, step_expr);
6933 if (seq)
6935 new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
6936 gcc_assert (!new_bb);
6939 t = unshare_expr (new_name);
6940 gcc_assert (CONSTANT_CLASS_P (new_name)
6941 || TREE_CODE (new_name) == SSA_NAME);
6942 new_vec = build_vector_from_val (vectype, t);
6943 vec_step = vect_init_vector (phi, new_vec, vectype, NULL);
6945 vec_def = induc_def;
6946 prev_stmt_vinfo = vinfo_for_stmt (induction_phi);
6947 for (i = 1; i < ncopies; i++)
6949 /* vec_i = vec_prev + vec_step */
6950 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR,
6951 vec_def, vec_step);
6952 vec_def = make_ssa_name (vec_dest, new_stmt);
6953 gimple_assign_set_lhs (new_stmt, vec_def);
6955 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
6956 set_vinfo_for_stmt (new_stmt,
6957 new_stmt_vec_info (new_stmt, loop_vinfo));
6958 STMT_VINFO_RELATED_STMT (prev_stmt_vinfo) = new_stmt;
6959 prev_stmt_vinfo = vinfo_for_stmt (new_stmt);
6963 if (nested_in_vect_loop)
6965 /* Find the loop-closed exit-phi of the induction, and record
6966 the final vector of induction results: */
6967 exit_phi = NULL;
6968 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
6970 gimple *use_stmt = USE_STMT (use_p);
6971 if (is_gimple_debug (use_stmt))
6972 continue;
6974 if (!flow_bb_inside_loop_p (iv_loop, gimple_bb (use_stmt)))
6976 exit_phi = use_stmt;
6977 break;
6980 if (exit_phi)
6982 stmt_vec_info stmt_vinfo = vinfo_for_stmt (exit_phi);
6983 /* FORNOW. Currently not supporting the case that an inner-loop induction
6984 is not used in the outer-loop (i.e. only outside the outer-loop). */
6985 gcc_assert (STMT_VINFO_RELEVANT_P (stmt_vinfo)
6986 && !STMT_VINFO_LIVE_P (stmt_vinfo));
6988 STMT_VINFO_VEC_STMT (stmt_vinfo) = new_stmt;
6989 if (dump_enabled_p ())
6991 dump_printf_loc (MSG_NOTE, vect_location,
6992 "vector of inductions after inner-loop:");
6993 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, new_stmt, 0);
6999 if (dump_enabled_p ())
7001 dump_printf_loc (MSG_NOTE, vect_location,
7002 "transform induction: created def-use cycle: ");
7003 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, induction_phi, 0);
7004 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
7005 SSA_NAME_DEF_STMT (vec_def), 0);
7008 return true;
7011 /* Function vectorizable_live_operation.
7013 STMT computes a value that is used outside the loop. Check if
7014 it can be supported. */
7016 bool
7017 vectorizable_live_operation (gimple *stmt,
7018 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
7019 slp_tree slp_node, int slp_index,
7020 gimple **vec_stmt)
7022 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
7023 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
7024 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
7025 imm_use_iterator imm_iter;
7026 tree lhs, lhs_type, bitsize, vec_bitsize;
7027 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
7028 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
7029 int ncopies;
7030 gimple *use_stmt;
7031 auto_vec<tree> vec_oprnds;
7033 gcc_assert (STMT_VINFO_LIVE_P (stmt_info));
7035 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def)
7036 return false;
7038 /* FORNOW. CHECKME. */
7039 if (nested_in_vect_loop_p (loop, stmt))
7040 return false;
7042 /* If STMT is not relevant and it is a simple assignment and its inputs are
7043 invariant then it can remain in place, unvectorized. The original last
7044 scalar value that it computes will be used. */
7045 if (!STMT_VINFO_RELEVANT_P (stmt_info))
7047 gcc_assert (is_simple_and_all_uses_invariant (stmt, loop_vinfo));
7048 if (dump_enabled_p ())
7049 dump_printf_loc (MSG_NOTE, vect_location,
7050 "statement is simple and uses invariant. Leaving in "
7051 "place.\n");
7052 return true;
7055 if (slp_node)
7056 ncopies = 1;
7057 else
7058 ncopies = vect_get_num_copies (loop_vinfo, vectype);
7060 if (!vec_stmt)
7061 /* No transformation required. */
7062 return true;
7064 /* If stmt has a related stmt, then use that for getting the lhs. */
7065 if (is_pattern_stmt_p (stmt_info))
7066 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
7068 lhs = (is_a <gphi *> (stmt)) ? gimple_phi_result (stmt)
7069 : gimple_get_lhs (stmt);
7070 lhs_type = TREE_TYPE (lhs);
7072 bitsize = (VECTOR_BOOLEAN_TYPE_P (vectype)
7073 ? bitsize_int (TYPE_PRECISION (TREE_TYPE (vectype)))
7074 : TYPE_SIZE (TREE_TYPE (vectype)));
7075 vec_bitsize = TYPE_SIZE (vectype);
7077 /* Get the vectorized lhs of STMT and the lane to use (counted in bits). */
7078 tree vec_lhs, bitstart;
7079 if (slp_node)
7081 gcc_assert (slp_index >= 0);
7083 int num_scalar = SLP_TREE_SCALAR_STMTS (slp_node).length ();
7084 int num_vec = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
7086 /* Get the last occurrence of the scalar index from the concatenation of
7087 all the slp vectors. Calculate which slp vector it is and the index
7088 within. */
7089 int pos = (num_vec * nunits) - num_scalar + slp_index;
7090 int vec_entry = pos / nunits;
7091 int vec_index = pos % nunits;
7093 /* Get the correct slp vectorized stmt. */
7094 vec_lhs = gimple_get_lhs (SLP_TREE_VEC_STMTS (slp_node)[vec_entry]);
7096 /* Get entry to use. */
7097 bitstart = bitsize_int (vec_index);
7098 bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
7100 else
7102 enum vect_def_type dt = STMT_VINFO_DEF_TYPE (stmt_info);
7103 vec_lhs = vect_get_vec_def_for_operand_1 (stmt, dt);
7105 /* For multiple copies, get the last copy. */
7106 for (int i = 1; i < ncopies; ++i)
7107 vec_lhs = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type,
7108 vec_lhs);
7110 /* Get the last lane in the vector. */
7111 bitstart = int_const_binop (MINUS_EXPR, vec_bitsize, bitsize);
7114 /* Create a new vectorized stmt for the uses of STMT and insert outside the
7115 loop. */
7116 gimple_seq stmts = NULL;
7117 tree bftype = TREE_TYPE (vectype);
7118 if (VECTOR_BOOLEAN_TYPE_P (vectype))
7119 bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
7120 tree new_tree = build3 (BIT_FIELD_REF, bftype, vec_lhs, bitsize, bitstart);
7121 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree), &stmts,
7122 true, NULL_TREE);
7123 if (stmts)
7124 gsi_insert_seq_on_edge_immediate (single_exit (loop), stmts);
7126 /* Replace use of lhs with newly computed result. If the use stmt is a
7127 single arg PHI, just replace all uses of PHI result. It's necessary
7128 because lcssa PHI defining lhs may be before newly inserted stmt. */
7129 use_operand_p use_p;
7130 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
7131 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt))
7132 && !is_gimple_debug (use_stmt))
7134 if (gimple_code (use_stmt) == GIMPLE_PHI
7135 && gimple_phi_num_args (use_stmt) == 1)
7137 replace_uses_by (gimple_phi_result (use_stmt), new_tree);
7139 else
7141 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
7142 SET_USE (use_p, new_tree);
7144 update_stmt (use_stmt);
7147 return true;
7150 /* Kill any debug uses outside LOOP of SSA names defined in STMT. */
7152 static void
7153 vect_loop_kill_debug_uses (struct loop *loop, gimple *stmt)
7155 ssa_op_iter op_iter;
7156 imm_use_iterator imm_iter;
7157 def_operand_p def_p;
7158 gimple *ustmt;
7160 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt, op_iter, SSA_OP_DEF)
7162 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
7164 basic_block bb;
7166 if (!is_gimple_debug (ustmt))
7167 continue;
7169 bb = gimple_bb (ustmt);
7171 if (!flow_bb_inside_loop_p (loop, bb))
7173 if (gimple_debug_bind_p (ustmt))
7175 if (dump_enabled_p ())
7176 dump_printf_loc (MSG_NOTE, vect_location,
7177 "killing debug use\n");
7179 gimple_debug_bind_reset_value (ustmt);
7180 update_stmt (ustmt);
7182 else
7183 gcc_unreachable ();
7189 /* Given loop represented by LOOP_VINFO, return true if computation of
7190 LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
7191 otherwise. */
7193 static bool
7194 loop_niters_no_overflow (loop_vec_info loop_vinfo)
7196 /* Constant case. */
7197 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
7199 tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
7200 tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
7202 gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
7203 gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
7204 if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
7205 return true;
7208 widest_int max;
7209 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
7210 /* Check the upper bound of loop niters. */
7211 if (get_max_loop_iterations (loop, &max))
7213 tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
7214 signop sgn = TYPE_SIGN (type);
7215 widest_int type_max = widest_int::from (wi::max_value (type), sgn);
7216 if (max < type_max)
7217 return true;
7219 return false;
7222 /* Scale profiling counters by estimation for LOOP which is vectorized
7223 by factor VF. */
7225 static void
7226 scale_profile_for_vect_loop (struct loop *loop, unsigned vf)
7228 edge preheader = loop_preheader_edge (loop);
7229 /* Reduce loop iterations by the vectorization factor. */
7230 gcov_type new_est_niter = niter_for_unrolled_loop (loop, vf);
7231 profile_count freq_h = loop->header->count, freq_e = preheader->count ();
7233 if (freq_h.nonzero_p ())
7235 profile_probability p;
7237 /* Avoid dropping loop body profile counter to 0 because of zero count
7238 in loop's preheader. */
7239 if (!(freq_e == profile_count::zero ()))
7240 freq_e = freq_e.force_nonzero ();
7241 p = freq_e.apply_scale (new_est_niter + 1, 1).probability_in (freq_h);
7242 scale_loop_frequencies (loop, p);
7245 edge exit_e = single_exit (loop);
7246 exit_e->probability = profile_probability::always ()
7247 .apply_scale (1, new_est_niter + 1);
7249 edge exit_l = single_pred_edge (loop->latch);
7250 profile_probability prob = exit_l->probability;
7251 exit_l->probability = exit_e->probability.invert ();
7252 if (prob.initialized_p () && exit_l->probability.initialized_p ())
7253 scale_bbs_frequencies (&loop->latch, 1, exit_l->probability / prob);
7256 /* Function vect_transform_loop.
7258 The analysis phase has determined that the loop is vectorizable.
7259 Vectorize the loop - created vectorized stmts to replace the scalar
7260 stmts in the loop, and update the loop exit condition.
7261 Returns scalar epilogue loop if any. */
7263 struct loop *
7264 vect_transform_loop (loop_vec_info loop_vinfo)
7266 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
7267 struct loop *epilogue = NULL;
7268 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
7269 int nbbs = loop->num_nodes;
7270 int i;
7271 tree niters_vector = NULL;
7272 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
7273 bool grouped_store;
7274 bool slp_scheduled = false;
7275 gimple *stmt, *pattern_stmt;
7276 gimple_seq pattern_def_seq = NULL;
7277 gimple_stmt_iterator pattern_def_si = gsi_none ();
7278 bool transform_pattern_stmt = false;
7279 bool check_profitability = false;
7280 int th;
7282 if (dump_enabled_p ())
7283 dump_printf_loc (MSG_NOTE, vect_location, "=== vec_transform_loop ===\n");
7285 /* Use the more conservative vectorization threshold. If the number
7286 of iterations is constant assume the cost check has been performed
7287 by our caller. If the threshold makes all loops profitable that
7288 run at least the vectorization factor number of times checking
7289 is pointless, too. */
7290 th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
7291 if (th >= LOOP_VINFO_VECT_FACTOR (loop_vinfo)
7292 && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
7294 if (dump_enabled_p ())
7295 dump_printf_loc (MSG_NOTE, vect_location,
7296 "Profitability threshold is %d loop iterations.\n",
7297 th);
7298 check_profitability = true;
7301 /* Make sure there exists a single-predecessor exit bb. Do this before
7302 versioning. */
7303 edge e = single_exit (loop);
7304 if (! single_pred_p (e->dest))
7306 split_loop_exit_edge (e);
7307 if (dump_enabled_p ())
7308 dump_printf (MSG_NOTE, "split exit edge\n");
7311 /* Version the loop first, if required, so the profitability check
7312 comes first. */
7314 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
7316 vect_loop_versioning (loop_vinfo, th, check_profitability);
7317 check_profitability = false;
7320 /* Make sure there exists a single-predecessor exit bb also on the
7321 scalar loop copy. Do this after versioning but before peeling
7322 so CFG structure is fine for both scalar and if-converted loop
7323 to make slpeel_duplicate_current_defs_from_edges face matched
7324 loop closed PHI nodes on the exit. */
7325 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
7327 e = single_exit (LOOP_VINFO_SCALAR_LOOP (loop_vinfo));
7328 if (! single_pred_p (e->dest))
7330 split_loop_exit_edge (e);
7331 if (dump_enabled_p ())
7332 dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
7336 tree niters = vect_build_loop_niters (loop_vinfo);
7337 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
7338 tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
7339 bool niters_no_overflow = loop_niters_no_overflow (loop_vinfo);
7340 epilogue = vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector, th,
7341 check_profitability, niters_no_overflow);
7342 if (niters_vector == NULL_TREE)
7344 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
7345 niters_vector
7346 = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
7347 LOOP_VINFO_INT_NITERS (loop_vinfo) / vf);
7348 else
7349 vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
7350 niters_no_overflow);
7353 /* 1) Make sure the loop header has exactly two entries
7354 2) Make sure we have a preheader basic block. */
7356 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
7358 split_edge (loop_preheader_edge (loop));
7360 /* FORNOW: the vectorizer supports only loops which body consist
7361 of one basic block (header + empty latch). When the vectorizer will
7362 support more involved loop forms, the order by which the BBs are
7363 traversed need to be reconsidered. */
7365 for (i = 0; i < nbbs; i++)
7367 basic_block bb = bbs[i];
7368 stmt_vec_info stmt_info;
7370 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
7371 gsi_next (&si))
7373 gphi *phi = si.phi ();
7374 if (dump_enabled_p ())
7376 dump_printf_loc (MSG_NOTE, vect_location,
7377 "------>vectorizing phi: ");
7378 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
7380 stmt_info = vinfo_for_stmt (phi);
7381 if (!stmt_info)
7382 continue;
7384 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
7385 vect_loop_kill_debug_uses (loop, phi);
7387 if (!STMT_VINFO_RELEVANT_P (stmt_info)
7388 && !STMT_VINFO_LIVE_P (stmt_info))
7389 continue;
7391 if (STMT_VINFO_VECTYPE (stmt_info)
7392 && (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info))
7393 != (unsigned HOST_WIDE_INT) vf)
7394 && dump_enabled_p ())
7395 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
7397 if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def
7398 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
7399 || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
7400 && ! PURE_SLP_STMT (stmt_info))
7402 if (dump_enabled_p ())
7403 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
7404 vect_transform_stmt (phi, NULL, NULL, NULL, NULL);
7408 pattern_stmt = NULL;
7409 for (gimple_stmt_iterator si = gsi_start_bb (bb);
7410 !gsi_end_p (si) || transform_pattern_stmt;)
7412 bool is_store;
7414 if (transform_pattern_stmt)
7415 stmt = pattern_stmt;
7416 else
7418 stmt = gsi_stmt (si);
7419 /* During vectorization remove existing clobber stmts. */
7420 if (gimple_clobber_p (stmt))
7422 unlink_stmt_vdef (stmt);
7423 gsi_remove (&si, true);
7424 release_defs (stmt);
7425 continue;
7429 if (dump_enabled_p ())
7431 dump_printf_loc (MSG_NOTE, vect_location,
7432 "------>vectorizing statement: ");
7433 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
7436 stmt_info = vinfo_for_stmt (stmt);
7438 /* vector stmts created in the outer-loop during vectorization of
7439 stmts in an inner-loop may not have a stmt_info, and do not
7440 need to be vectorized. */
7441 if (!stmt_info)
7443 gsi_next (&si);
7444 continue;
7447 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
7448 vect_loop_kill_debug_uses (loop, stmt);
7450 if (!STMT_VINFO_RELEVANT_P (stmt_info)
7451 && !STMT_VINFO_LIVE_P (stmt_info))
7453 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
7454 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
7455 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
7456 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
7458 stmt = pattern_stmt;
7459 stmt_info = vinfo_for_stmt (stmt);
7461 else
7463 gsi_next (&si);
7464 continue;
7467 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
7468 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
7469 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
7470 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
7471 transform_pattern_stmt = true;
7473 /* If pattern statement has def stmts, vectorize them too. */
7474 if (is_pattern_stmt_p (stmt_info))
7476 if (pattern_def_seq == NULL)
7478 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
7479 pattern_def_si = gsi_start (pattern_def_seq);
7481 else if (!gsi_end_p (pattern_def_si))
7482 gsi_next (&pattern_def_si);
7483 if (pattern_def_seq != NULL)
7485 gimple *pattern_def_stmt = NULL;
7486 stmt_vec_info pattern_def_stmt_info = NULL;
7488 while (!gsi_end_p (pattern_def_si))
7490 pattern_def_stmt = gsi_stmt (pattern_def_si);
7491 pattern_def_stmt_info
7492 = vinfo_for_stmt (pattern_def_stmt);
7493 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
7494 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
7495 break;
7496 gsi_next (&pattern_def_si);
7499 if (!gsi_end_p (pattern_def_si))
7501 if (dump_enabled_p ())
7503 dump_printf_loc (MSG_NOTE, vect_location,
7504 "==> vectorizing pattern def "
7505 "stmt: ");
7506 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
7507 pattern_def_stmt, 0);
7510 stmt = pattern_def_stmt;
7511 stmt_info = pattern_def_stmt_info;
7513 else
7515 pattern_def_si = gsi_none ();
7516 transform_pattern_stmt = false;
7519 else
7520 transform_pattern_stmt = false;
7523 if (STMT_VINFO_VECTYPE (stmt_info))
7525 unsigned int nunits
7526 = (unsigned int)
7527 TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
7528 if (!STMT_SLP_TYPE (stmt_info)
7529 && nunits != (unsigned int) vf
7530 && dump_enabled_p ())
7531 /* For SLP VF is set according to unrolling factor, and not
7532 to vector size, hence for SLP this print is not valid. */
7533 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
7536 /* SLP. Schedule all the SLP instances when the first SLP stmt is
7537 reached. */
7538 if (STMT_SLP_TYPE (stmt_info))
7540 if (!slp_scheduled)
7542 slp_scheduled = true;
7544 if (dump_enabled_p ())
7545 dump_printf_loc (MSG_NOTE, vect_location,
7546 "=== scheduling SLP instances ===\n");
7548 vect_schedule_slp (loop_vinfo);
7551 /* Hybrid SLP stmts must be vectorized in addition to SLP. */
7552 if (!vinfo_for_stmt (stmt) || PURE_SLP_STMT (stmt_info))
7554 if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7556 pattern_def_seq = NULL;
7557 gsi_next (&si);
7559 continue;
7563 /* -------- vectorize statement ------------ */
7564 if (dump_enabled_p ())
7565 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
7567 grouped_store = false;
7568 is_store = vect_transform_stmt (stmt, &si, &grouped_store, NULL, NULL);
7569 if (is_store)
7571 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
7573 /* Interleaving. If IS_STORE is TRUE, the vectorization of the
7574 interleaving chain was completed - free all the stores in
7575 the chain. */
7576 gsi_next (&si);
7577 vect_remove_stores (GROUP_FIRST_ELEMENT (stmt_info));
7579 else
7581 /* Free the attached stmt_vec_info and remove the stmt. */
7582 gimple *store = gsi_stmt (si);
7583 free_stmt_vec_info (store);
7584 unlink_stmt_vdef (store);
7585 gsi_remove (&si, true);
7586 release_defs (store);
7589 /* Stores can only appear at the end of pattern statements. */
7590 gcc_assert (!transform_pattern_stmt);
7591 pattern_def_seq = NULL;
7593 else if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7595 pattern_def_seq = NULL;
7596 gsi_next (&si);
7598 } /* stmts in BB */
7599 } /* BBs in loop */
7601 slpeel_make_loop_iterate_ntimes (loop, niters_vector);
7603 scale_profile_for_vect_loop (loop, vf);
7605 /* The minimum number of iterations performed by the epilogue. This
7606 is 1 when peeling for gaps because we always need a final scalar
7607 iteration. */
7608 int min_epilogue_iters = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
7609 /* +1 to convert latch counts to loop iteration counts,
7610 -min_epilogue_iters to remove iterations that cannot be performed
7611 by the vector code. */
7612 int bias = 1 - min_epilogue_iters;
7613 /* In these calculations the "- 1" converts loop iteration counts
7614 back to latch counts. */
7615 if (loop->any_upper_bound)
7616 loop->nb_iterations_upper_bound
7617 = wi::udiv_floor (loop->nb_iterations_upper_bound + bias, vf) - 1;
7618 if (loop->any_likely_upper_bound)
7619 loop->nb_iterations_likely_upper_bound
7620 = wi::udiv_floor (loop->nb_iterations_likely_upper_bound + bias, vf) - 1;
7621 if (loop->any_estimate)
7622 loop->nb_iterations_estimate
7623 = wi::udiv_floor (loop->nb_iterations_estimate + bias, vf) - 1;
7625 if (dump_enabled_p ())
7627 if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
7629 dump_printf_loc (MSG_NOTE, vect_location,
7630 "LOOP VECTORIZED\n");
7631 if (loop->inner)
7632 dump_printf_loc (MSG_NOTE, vect_location,
7633 "OUTER LOOP VECTORIZED\n");
7634 dump_printf (MSG_NOTE, "\n");
7636 else
7637 dump_printf_loc (MSG_NOTE, vect_location,
7638 "LOOP EPILOGUE VECTORIZED (VS=%d)\n",
7639 current_vector_size);
7642 /* Free SLP instances here because otherwise stmt reference counting
7643 won't work. */
7644 slp_instance instance;
7645 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
7646 vect_free_slp_instance (instance);
7647 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
7648 /* Clear-up safelen field since its value is invalid after vectorization
7649 since vectorized loop can have loop-carried dependencies. */
7650 loop->safelen = 0;
7652 /* Don't vectorize epilogue for epilogue. */
7653 if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
7654 epilogue = NULL;
7656 if (epilogue)
7658 unsigned int vector_sizes
7659 = targetm.vectorize.autovectorize_vector_sizes ();
7660 vector_sizes &= current_vector_size - 1;
7662 if (!PARAM_VALUE (PARAM_VECT_EPILOGUES_NOMASK))
7663 epilogue = NULL;
7664 else if (!vector_sizes)
7665 epilogue = NULL;
7666 else if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
7667 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) >= 0)
7669 int smallest_vec_size = 1 << ctz_hwi (vector_sizes);
7670 int ratio = current_vector_size / smallest_vec_size;
7671 int eiters = LOOP_VINFO_INT_NITERS (loop_vinfo)
7672 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
7673 eiters = eiters % vf;
7675 epilogue->nb_iterations_upper_bound = eiters - 1;
7677 if (eiters < vf / ratio)
7678 epilogue = NULL;
7682 if (epilogue)
7684 epilogue->force_vectorize = loop->force_vectorize;
7685 epilogue->safelen = loop->safelen;
7686 epilogue->dont_vectorize = false;
7688 /* We may need to if-convert epilogue to vectorize it. */
7689 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
7690 tree_if_conversion (epilogue);
7693 return epilogue;
7696 /* The code below is trying to perform simple optimization - revert
7697 if-conversion for masked stores, i.e. if the mask of a store is zero
7698 do not perform it and all stored value producers also if possible.
7699 For example,
7700 for (i=0; i<n; i++)
7701 if (c[i])
7703 p1[i] += 1;
7704 p2[i] = p3[i] +2;
7706 this transformation will produce the following semi-hammock:
7708 if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
7710 vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
7711 vect__12.22_172 = vect__11.19_170 + vect_cst__171;
7712 MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
7713 vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
7714 vect__19.28_184 = vect__18.25_182 + vect_cst__183;
7715 MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
7719 void
7720 optimize_mask_stores (struct loop *loop)
7722 basic_block *bbs = get_loop_body (loop);
7723 unsigned nbbs = loop->num_nodes;
7724 unsigned i;
7725 basic_block bb;
7726 struct loop *bb_loop;
7727 gimple_stmt_iterator gsi;
7728 gimple *stmt;
7729 auto_vec<gimple *> worklist;
7731 vect_location = find_loop_location (loop);
7732 /* Pick up all masked stores in loop if any. */
7733 for (i = 0; i < nbbs; i++)
7735 bb = bbs[i];
7736 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7737 gsi_next (&gsi))
7739 stmt = gsi_stmt (gsi);
7740 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
7741 worklist.safe_push (stmt);
7745 free (bbs);
7746 if (worklist.is_empty ())
7747 return;
7749 /* Loop has masked stores. */
7750 while (!worklist.is_empty ())
7752 gimple *last, *last_store;
7753 edge e, efalse;
7754 tree mask;
7755 basic_block store_bb, join_bb;
7756 gimple_stmt_iterator gsi_to;
7757 tree vdef, new_vdef;
7758 gphi *phi;
7759 tree vectype;
7760 tree zero;
7762 last = worklist.pop ();
7763 mask = gimple_call_arg (last, 2);
7764 bb = gimple_bb (last);
7765 /* Create then_bb and if-then structure in CFG, then_bb belongs to
7766 the same loop as if_bb. It could be different to LOOP when two
7767 level loop-nest is vectorized and mask_store belongs to the inner
7768 one. */
7769 e = split_block (bb, last);
7770 bb_loop = bb->loop_father;
7771 gcc_assert (loop == bb_loop || flow_loop_nested_p (loop, bb_loop));
7772 join_bb = e->dest;
7773 store_bb = create_empty_bb (bb);
7774 add_bb_to_loop (store_bb, bb_loop);
7775 e->flags = EDGE_TRUE_VALUE;
7776 efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
7777 /* Put STORE_BB to likely part. */
7778 efalse->probability = profile_probability::unlikely ();
7779 store_bb->count = efalse->count ();
7780 make_single_succ_edge (store_bb, join_bb, EDGE_FALLTHRU);
7781 if (dom_info_available_p (CDI_DOMINATORS))
7782 set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
7783 if (dump_enabled_p ())
7784 dump_printf_loc (MSG_NOTE, vect_location,
7785 "Create new block %d to sink mask stores.",
7786 store_bb->index);
7787 /* Create vector comparison with boolean result. */
7788 vectype = TREE_TYPE (mask);
7789 zero = build_zero_cst (vectype);
7790 stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
7791 gsi = gsi_last_bb (bb);
7792 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
7793 /* Create new PHI node for vdef of the last masked store:
7794 .MEM_2 = VDEF <.MEM_1>
7795 will be converted to
7796 .MEM.3 = VDEF <.MEM_1>
7797 and new PHI node will be created in join bb
7798 .MEM_2 = PHI <.MEM_1, .MEM_3>
7800 vdef = gimple_vdef (last);
7801 new_vdef = make_ssa_name (gimple_vop (cfun), last);
7802 gimple_set_vdef (last, new_vdef);
7803 phi = create_phi_node (vdef, join_bb);
7804 add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
7806 /* Put all masked stores with the same mask to STORE_BB if possible. */
7807 while (true)
7809 gimple_stmt_iterator gsi_from;
7810 gimple *stmt1 = NULL;
7812 /* Move masked store to STORE_BB. */
7813 last_store = last;
7814 gsi = gsi_for_stmt (last);
7815 gsi_from = gsi;
7816 /* Shift GSI to the previous stmt for further traversal. */
7817 gsi_prev (&gsi);
7818 gsi_to = gsi_start_bb (store_bb);
7819 gsi_move_before (&gsi_from, &gsi_to);
7820 /* Setup GSI_TO to the non-empty block start. */
7821 gsi_to = gsi_start_bb (store_bb);
7822 if (dump_enabled_p ())
7824 dump_printf_loc (MSG_NOTE, vect_location,
7825 "Move stmt to created bb\n");
7826 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, last, 0);
7828 /* Move all stored value producers if possible. */
7829 while (!gsi_end_p (gsi))
7831 tree lhs;
7832 imm_use_iterator imm_iter;
7833 use_operand_p use_p;
7834 bool res;
7836 /* Skip debug statements. */
7837 if (is_gimple_debug (gsi_stmt (gsi)))
7839 gsi_prev (&gsi);
7840 continue;
7842 stmt1 = gsi_stmt (gsi);
7843 /* Do not consider statements writing to memory or having
7844 volatile operand. */
7845 if (gimple_vdef (stmt1)
7846 || gimple_has_volatile_ops (stmt1))
7847 break;
7848 gsi_from = gsi;
7849 gsi_prev (&gsi);
7850 lhs = gimple_get_lhs (stmt1);
7851 if (!lhs)
7852 break;
7854 /* LHS of vectorized stmt must be SSA_NAME. */
7855 if (TREE_CODE (lhs) != SSA_NAME)
7856 break;
7858 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
7860 /* Remove dead scalar statement. */
7861 if (has_zero_uses (lhs))
7863 gsi_remove (&gsi_from, true);
7864 continue;
7868 /* Check that LHS does not have uses outside of STORE_BB. */
7869 res = true;
7870 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
7872 gimple *use_stmt;
7873 use_stmt = USE_STMT (use_p);
7874 if (is_gimple_debug (use_stmt))
7875 continue;
7876 if (gimple_bb (use_stmt) != store_bb)
7878 res = false;
7879 break;
7882 if (!res)
7883 break;
7885 if (gimple_vuse (stmt1)
7886 && gimple_vuse (stmt1) != gimple_vuse (last_store))
7887 break;
7889 /* Can move STMT1 to STORE_BB. */
7890 if (dump_enabled_p ())
7892 dump_printf_loc (MSG_NOTE, vect_location,
7893 "Move stmt to created bb\n");
7894 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt1, 0);
7896 gsi_move_before (&gsi_from, &gsi_to);
7897 /* Shift GSI_TO for further insertion. */
7898 gsi_prev (&gsi_to);
7900 /* Put other masked stores with the same mask to STORE_BB. */
7901 if (worklist.is_empty ()
7902 || gimple_call_arg (worklist.last (), 2) != mask
7903 || worklist.last () != stmt1)
7904 break;
7905 last = worklist.pop ();
7907 add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);