2016-09-26 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / gcc / tree-vect-loop.c
bloba84ca3f2f348aa76207e8bb08a83915dbd9f496d
1 /* Loop Vectorization
2 Copyright (C) 2003-2016 Free Software Foundation, Inc.
3 Contributed by Dorit Naishlos <dorit@il.ibm.com> and
4 Ira Rosen <irar@il.ibm.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "target.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "cfghooks.h"
31 #include "tree-pass.h"
32 #include "ssa.h"
33 #include "optabs-tree.h"
34 #include "diagnostic-core.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "cfganal.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "tree-ssa-loop-ivopts.h"
42 #include "tree-ssa-loop-manip.h"
43 #include "tree-ssa-loop-niter.h"
44 #include "tree-ssa-loop.h"
45 #include "cfgloop.h"
46 #include "params.h"
47 #include "tree-scalar-evolution.h"
48 #include "tree-vectorizer.h"
49 #include "gimple-fold.h"
50 #include "cgraph.h"
51 #include "tree-cfg.h"
53 /* Loop Vectorization Pass.
55 This pass tries to vectorize loops.
57 For example, the vectorizer transforms the following simple loop:
59 short a[N]; short b[N]; short c[N]; int i;
61 for (i=0; i<N; i++){
62 a[i] = b[i] + c[i];
65 as if it was manually vectorized by rewriting the source code into:
67 typedef int __attribute__((mode(V8HI))) v8hi;
68 short a[N]; short b[N]; short c[N]; int i;
69 v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
70 v8hi va, vb, vc;
72 for (i=0; i<N/8; i++){
73 vb = pb[i];
74 vc = pc[i];
75 va = vb + vc;
76 pa[i] = va;
79 The main entry to this pass is vectorize_loops(), in which
80 the vectorizer applies a set of analyses on a given set of loops,
81 followed by the actual vectorization transformation for the loops that
82 had successfully passed the analysis phase.
83 Throughout this pass we make a distinction between two types of
84 data: scalars (which are represented by SSA_NAMES), and memory references
85 ("data-refs"). These two types of data require different handling both
86 during analysis and transformation. The types of data-refs that the
87 vectorizer currently supports are ARRAY_REFS which base is an array DECL
88 (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
89 accesses are required to have a simple (consecutive) access pattern.
91 Analysis phase:
92 ===============
93 The driver for the analysis phase is vect_analyze_loop().
94 It applies a set of analyses, some of which rely on the scalar evolution
95 analyzer (scev) developed by Sebastian Pop.
97 During the analysis phase the vectorizer records some information
98 per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
99 loop, as well as general information about the loop as a whole, which is
100 recorded in a "loop_vec_info" struct attached to each loop.
102 Transformation phase:
103 =====================
104 The loop transformation phase scans all the stmts in the loop, and
105 creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
106 the loop that needs to be vectorized. It inserts the vector code sequence
107 just before the scalar stmt S, and records a pointer to the vector code
108 in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
109 attached to S). This pointer will be used for the vectorization of following
110 stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
111 otherwise, we rely on dead code elimination for removing it.
113 For example, say stmt S1 was vectorized into stmt VS1:
115 VS1: vb = px[i];
116 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
117 S2: a = b;
119 To vectorize stmt S2, the vectorizer first finds the stmt that defines
120 the operand 'b' (S1), and gets the relevant vector def 'vb' from the
121 vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
122 resulting sequence would be:
124 VS1: vb = px[i];
125 S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
126 VS2: va = vb;
127 S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
129 Operands that are not SSA_NAMEs, are data-refs that appear in
130 load/store operations (like 'x[i]' in S1), and are handled differently.
132 Target modeling:
133 =================
134 Currently the only target specific information that is used is the
135 size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
136 Targets that can support different sizes of vectors, for now will need
137 to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More
138 flexibility will be added in the future.
140 Since we only vectorize operations which vector form can be
141 expressed using existing tree codes, to verify that an operation is
142 supported, the vectorizer checks the relevant optab at the relevant
143 machine_mode (e.g, optab_handler (add_optab, V8HImode)). If
144 the value found is CODE_FOR_nothing, then there's no target support, and
145 we can't vectorize the stmt.
147 For additional information on this project see:
148 http://gcc.gnu.org/projects/tree-ssa/vectorization.html
151 static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *);
153 /* Function vect_determine_vectorization_factor
155 Determine the vectorization factor (VF). VF is the number of data elements
156 that are operated upon in parallel in a single iteration of the vectorized
157 loop. For example, when vectorizing a loop that operates on 4byte elements,
158 on a target with vector size (VS) 16byte, the VF is set to 4, since 4
159 elements can fit in a single vector register.
161 We currently support vectorization of loops in which all types operated upon
162 are of the same size. Therefore this function currently sets VF according to
163 the size of the types operated upon, and fails if there are multiple sizes
164 in the loop.
166 VF is also the factor by which the loop iterations are strip-mined, e.g.:
167 original loop:
168 for (i=0; i<N; i++){
169 a[i] = b[i] + c[i];
172 vectorized loop:
173 for (i=0; i<N; i+=VF){
174 a[i:VF] = b[i:VF] + c[i:VF];
178 static bool
179 vect_determine_vectorization_factor (loop_vec_info loop_vinfo)
181 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
182 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
183 unsigned nbbs = loop->num_nodes;
184 unsigned int vectorization_factor = 0;
185 tree scalar_type;
186 gphi *phi;
187 tree vectype;
188 unsigned int nunits;
189 stmt_vec_info stmt_info;
190 unsigned i;
191 HOST_WIDE_INT dummy;
192 gimple *stmt, *pattern_stmt = NULL;
193 gimple_seq pattern_def_seq = NULL;
194 gimple_stmt_iterator pattern_def_si = gsi_none ();
195 bool analyze_pattern_stmt = false;
196 bool bool_result;
197 auto_vec<stmt_vec_info> mask_producers;
199 if (dump_enabled_p ())
200 dump_printf_loc (MSG_NOTE, vect_location,
201 "=== vect_determine_vectorization_factor ===\n");
203 for (i = 0; i < nbbs; i++)
205 basic_block bb = bbs[i];
207 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
208 gsi_next (&si))
210 phi = si.phi ();
211 stmt_info = vinfo_for_stmt (phi);
212 if (dump_enabled_p ())
214 dump_printf_loc (MSG_NOTE, vect_location, "==> examining phi: ");
215 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
218 gcc_assert (stmt_info);
220 if (STMT_VINFO_RELEVANT_P (stmt_info)
221 || STMT_VINFO_LIVE_P (stmt_info))
223 gcc_assert (!STMT_VINFO_VECTYPE (stmt_info));
224 scalar_type = TREE_TYPE (PHI_RESULT (phi));
226 if (dump_enabled_p ())
228 dump_printf_loc (MSG_NOTE, vect_location,
229 "get vectype for scalar type: ");
230 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
231 dump_printf (MSG_NOTE, "\n");
234 vectype = get_vectype_for_scalar_type (scalar_type);
235 if (!vectype)
237 if (dump_enabled_p ())
239 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
240 "not vectorized: unsupported "
241 "data-type ");
242 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
243 scalar_type);
244 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
246 return false;
248 STMT_VINFO_VECTYPE (stmt_info) = vectype;
250 if (dump_enabled_p ())
252 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
253 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
254 dump_printf (MSG_NOTE, "\n");
257 nunits = TYPE_VECTOR_SUBPARTS (vectype);
258 if (dump_enabled_p ())
259 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n",
260 nunits);
262 if (!vectorization_factor
263 || (nunits > vectorization_factor))
264 vectorization_factor = nunits;
268 for (gimple_stmt_iterator si = gsi_start_bb (bb);
269 !gsi_end_p (si) || analyze_pattern_stmt;)
271 tree vf_vectype;
273 if (analyze_pattern_stmt)
274 stmt = pattern_stmt;
275 else
276 stmt = gsi_stmt (si);
278 stmt_info = vinfo_for_stmt (stmt);
280 if (dump_enabled_p ())
282 dump_printf_loc (MSG_NOTE, vect_location,
283 "==> examining statement: ");
284 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
287 gcc_assert (stmt_info);
289 /* Skip stmts which do not need to be vectorized. */
290 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
291 && !STMT_VINFO_LIVE_P (stmt_info))
292 || gimple_clobber_p (stmt))
294 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
295 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
296 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
297 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
299 stmt = pattern_stmt;
300 stmt_info = vinfo_for_stmt (pattern_stmt);
301 if (dump_enabled_p ())
303 dump_printf_loc (MSG_NOTE, vect_location,
304 "==> examining pattern statement: ");
305 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
308 else
310 if (dump_enabled_p ())
311 dump_printf_loc (MSG_NOTE, vect_location, "skip.\n");
312 gsi_next (&si);
313 continue;
316 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
317 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
318 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
319 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
320 analyze_pattern_stmt = true;
322 /* If a pattern statement has def stmts, analyze them too. */
323 if (is_pattern_stmt_p (stmt_info))
325 if (pattern_def_seq == NULL)
327 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
328 pattern_def_si = gsi_start (pattern_def_seq);
330 else if (!gsi_end_p (pattern_def_si))
331 gsi_next (&pattern_def_si);
332 if (pattern_def_seq != NULL)
334 gimple *pattern_def_stmt = NULL;
335 stmt_vec_info pattern_def_stmt_info = NULL;
337 while (!gsi_end_p (pattern_def_si))
339 pattern_def_stmt = gsi_stmt (pattern_def_si);
340 pattern_def_stmt_info
341 = vinfo_for_stmt (pattern_def_stmt);
342 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
343 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
344 break;
345 gsi_next (&pattern_def_si);
348 if (!gsi_end_p (pattern_def_si))
350 if (dump_enabled_p ())
352 dump_printf_loc (MSG_NOTE, vect_location,
353 "==> examining pattern def stmt: ");
354 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
355 pattern_def_stmt, 0);
358 stmt = pattern_def_stmt;
359 stmt_info = pattern_def_stmt_info;
361 else
363 pattern_def_si = gsi_none ();
364 analyze_pattern_stmt = false;
367 else
368 analyze_pattern_stmt = false;
371 if (gimple_get_lhs (stmt) == NULL_TREE
372 /* MASK_STORE has no lhs, but is ok. */
373 && (!is_gimple_call (stmt)
374 || !gimple_call_internal_p (stmt)
375 || gimple_call_internal_fn (stmt) != IFN_MASK_STORE))
377 if (is_gimple_call (stmt))
379 /* Ignore calls with no lhs. These must be calls to
380 #pragma omp simd functions, and what vectorization factor
381 it really needs can't be determined until
382 vectorizable_simd_clone_call. */
383 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
385 pattern_def_seq = NULL;
386 gsi_next (&si);
388 continue;
390 if (dump_enabled_p ())
392 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
393 "not vectorized: irregular stmt.");
394 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
397 return false;
400 if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
402 if (dump_enabled_p ())
404 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
405 "not vectorized: vector stmt in loop:");
406 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
408 return false;
411 bool_result = false;
413 if (STMT_VINFO_VECTYPE (stmt_info))
415 /* The only case when a vectype had been already set is for stmts
416 that contain a dataref, or for "pattern-stmts" (stmts
417 generated by the vectorizer to represent/replace a certain
418 idiom). */
419 gcc_assert (STMT_VINFO_DATA_REF (stmt_info)
420 || is_pattern_stmt_p (stmt_info)
421 || !gsi_end_p (pattern_def_si));
422 vectype = STMT_VINFO_VECTYPE (stmt_info);
424 else
426 gcc_assert (!STMT_VINFO_DATA_REF (stmt_info));
427 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
428 scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
429 else
430 scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
432 /* Bool ops don't participate in vectorization factor
433 computation. For comparison use compared types to
434 compute a factor. */
435 if (TREE_CODE (scalar_type) == BOOLEAN_TYPE
436 && is_gimple_assign (stmt)
437 && gimple_assign_rhs_code (stmt) != COND_EXPR)
439 if (STMT_VINFO_RELEVANT_P (stmt_info)
440 || STMT_VINFO_LIVE_P (stmt_info))
441 mask_producers.safe_push (stmt_info);
442 bool_result = true;
444 if (gimple_code (stmt) == GIMPLE_ASSIGN
445 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
446 == tcc_comparison
447 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt)))
448 != BOOLEAN_TYPE)
449 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
450 else
452 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
454 pattern_def_seq = NULL;
455 gsi_next (&si);
457 continue;
461 if (dump_enabled_p ())
463 dump_printf_loc (MSG_NOTE, vect_location,
464 "get vectype for scalar type: ");
465 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
466 dump_printf (MSG_NOTE, "\n");
468 vectype = get_vectype_for_scalar_type (scalar_type);
469 if (!vectype)
471 if (dump_enabled_p ())
473 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
474 "not vectorized: unsupported "
475 "data-type ");
476 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
477 scalar_type);
478 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
480 return false;
483 if (!bool_result)
484 STMT_VINFO_VECTYPE (stmt_info) = vectype;
486 if (dump_enabled_p ())
488 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
489 dump_generic_expr (MSG_NOTE, TDF_SLIM, vectype);
490 dump_printf (MSG_NOTE, "\n");
494 /* Don't try to compute VF out scalar types if we stmt
495 produces boolean vector. Use result vectype instead. */
496 if (VECTOR_BOOLEAN_TYPE_P (vectype))
497 vf_vectype = vectype;
498 else
500 /* The vectorization factor is according to the smallest
501 scalar type (or the largest vector size, but we only
502 support one vector size per loop). */
503 if (!bool_result)
504 scalar_type = vect_get_smallest_scalar_type (stmt, &dummy,
505 &dummy);
506 if (dump_enabled_p ())
508 dump_printf_loc (MSG_NOTE, vect_location,
509 "get vectype for scalar type: ");
510 dump_generic_expr (MSG_NOTE, TDF_SLIM, scalar_type);
511 dump_printf (MSG_NOTE, "\n");
513 vf_vectype = get_vectype_for_scalar_type (scalar_type);
515 if (!vf_vectype)
517 if (dump_enabled_p ())
519 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
520 "not vectorized: unsupported data-type ");
521 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
522 scalar_type);
523 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
525 return false;
528 if ((GET_MODE_SIZE (TYPE_MODE (vectype))
529 != GET_MODE_SIZE (TYPE_MODE (vf_vectype))))
531 if (dump_enabled_p ())
533 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
534 "not vectorized: different sized vector "
535 "types in statement, ");
536 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
537 vectype);
538 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
539 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
540 vf_vectype);
541 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
543 return false;
546 if (dump_enabled_p ())
548 dump_printf_loc (MSG_NOTE, vect_location, "vectype: ");
549 dump_generic_expr (MSG_NOTE, TDF_SLIM, vf_vectype);
550 dump_printf (MSG_NOTE, "\n");
553 nunits = TYPE_VECTOR_SUBPARTS (vf_vectype);
554 if (dump_enabled_p ())
555 dump_printf_loc (MSG_NOTE, vect_location, "nunits = %d\n", nunits);
556 if (!vectorization_factor
557 || (nunits > vectorization_factor))
558 vectorization_factor = nunits;
560 if (!analyze_pattern_stmt && gsi_end_p (pattern_def_si))
562 pattern_def_seq = NULL;
563 gsi_next (&si);
568 /* TODO: Analyze cost. Decide if worth while to vectorize. */
569 if (dump_enabled_p ())
570 dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = %d\n",
571 vectorization_factor);
572 if (vectorization_factor <= 1)
574 if (dump_enabled_p ())
575 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
576 "not vectorized: unsupported data-type\n");
577 return false;
579 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
581 for (i = 0; i < mask_producers.length (); i++)
583 tree mask_type = NULL;
585 stmt = STMT_VINFO_STMT (mask_producers[i]);
587 if (gimple_code (stmt) == GIMPLE_ASSIGN
588 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison
589 && TREE_CODE (TREE_TYPE (gimple_assign_rhs1 (stmt))) != BOOLEAN_TYPE)
591 scalar_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
592 mask_type = get_mask_type_for_scalar_type (scalar_type);
594 if (!mask_type)
596 if (dump_enabled_p ())
597 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
598 "not vectorized: unsupported mask\n");
599 return false;
602 else
604 tree rhs;
605 ssa_op_iter iter;
606 gimple *def_stmt;
607 enum vect_def_type dt;
609 FOR_EACH_SSA_TREE_OPERAND (rhs, stmt, iter, SSA_OP_USE)
611 if (!vect_is_simple_use (rhs, mask_producers[i]->vinfo,
612 &def_stmt, &dt, &vectype))
614 if (dump_enabled_p ())
616 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
617 "not vectorized: can't compute mask type "
618 "for statement, ");
619 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
622 return false;
625 /* No vectype probably means external definition.
626 Allow it in case there is another operand which
627 allows to determine mask type. */
628 if (!vectype)
629 continue;
631 if (!mask_type)
632 mask_type = vectype;
633 else if (TYPE_VECTOR_SUBPARTS (mask_type)
634 != TYPE_VECTOR_SUBPARTS (vectype))
636 if (dump_enabled_p ())
638 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
639 "not vectorized: different sized masks "
640 "types in statement, ");
641 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
642 mask_type);
643 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
644 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
645 vectype);
646 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
648 return false;
650 else if (VECTOR_BOOLEAN_TYPE_P (mask_type)
651 != VECTOR_BOOLEAN_TYPE_P (vectype))
653 if (dump_enabled_p ())
655 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
656 "not vectorized: mixed mask and "
657 "nonmask vector types in statement, ");
658 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
659 mask_type);
660 dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
661 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
662 vectype);
663 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
665 return false;
669 /* We may compare boolean value loaded as vector of integers.
670 Fix mask_type in such case. */
671 if (mask_type
672 && !VECTOR_BOOLEAN_TYPE_P (mask_type)
673 && gimple_code (stmt) == GIMPLE_ASSIGN
674 && TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison)
675 mask_type = build_same_sized_truth_vector_type (mask_type);
678 /* No mask_type should mean loop invariant predicate.
679 This is probably a subject for optimization in
680 if-conversion. */
681 if (!mask_type)
683 if (dump_enabled_p ())
685 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
686 "not vectorized: can't compute mask type "
687 "for statement, ");
688 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt,
691 return false;
694 STMT_VINFO_VECTYPE (mask_producers[i]) = mask_type;
697 return true;
701 /* Function vect_is_simple_iv_evolution.
703 FORNOW: A simple evolution of an induction variables in the loop is
704 considered a polynomial evolution. */
706 static bool
707 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init,
708 tree * step)
710 tree init_expr;
711 tree step_expr;
712 tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
713 basic_block bb;
715 /* When there is no evolution in this loop, the evolution function
716 is not "simple". */
717 if (evolution_part == NULL_TREE)
718 return false;
720 /* When the evolution is a polynomial of degree >= 2
721 the evolution function is not "simple". */
722 if (tree_is_chrec (evolution_part))
723 return false;
725 step_expr = evolution_part;
726 init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
728 if (dump_enabled_p ())
730 dump_printf_loc (MSG_NOTE, vect_location, "step: ");
731 dump_generic_expr (MSG_NOTE, TDF_SLIM, step_expr);
732 dump_printf (MSG_NOTE, ", init: ");
733 dump_generic_expr (MSG_NOTE, TDF_SLIM, init_expr);
734 dump_printf (MSG_NOTE, "\n");
737 *init = init_expr;
738 *step = step_expr;
740 if (TREE_CODE (step_expr) != INTEGER_CST
741 && (TREE_CODE (step_expr) != SSA_NAME
742 || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
743 && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
744 || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
745 && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
746 || !flag_associative_math)))
747 && (TREE_CODE (step_expr) != REAL_CST
748 || !flag_associative_math))
750 if (dump_enabled_p ())
751 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
752 "step unknown.\n");
753 return false;
756 return true;
759 /* Function vect_analyze_scalar_cycles_1.
761 Examine the cross iteration def-use cycles of scalar variables
762 in LOOP. LOOP_VINFO represents the loop that is now being
763 considered for vectorization (can be LOOP, or an outer-loop
764 enclosing LOOP). */
766 static void
767 vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, struct loop *loop)
769 basic_block bb = loop->header;
770 tree init, step;
771 auto_vec<gimple *, 64> worklist;
772 gphi_iterator gsi;
773 bool double_reduc;
775 if (dump_enabled_p ())
776 dump_printf_loc (MSG_NOTE, vect_location,
777 "=== vect_analyze_scalar_cycles ===\n");
779 /* First - identify all inductions. Reduction detection assumes that all the
780 inductions have been identified, therefore, this order must not be
781 changed. */
782 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
784 gphi *phi = gsi.phi ();
785 tree access_fn = NULL;
786 tree def = PHI_RESULT (phi);
787 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
789 if (dump_enabled_p ())
791 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
792 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
795 /* Skip virtual phi's. The data dependences that are associated with
796 virtual defs/uses (i.e., memory accesses) are analyzed elsewhere. */
797 if (virtual_operand_p (def))
798 continue;
800 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
802 /* Analyze the evolution function. */
803 access_fn = analyze_scalar_evolution (loop, def);
804 if (access_fn)
806 STRIP_NOPS (access_fn);
807 if (dump_enabled_p ())
809 dump_printf_loc (MSG_NOTE, vect_location,
810 "Access function of PHI: ");
811 dump_generic_expr (MSG_NOTE, TDF_SLIM, access_fn);
812 dump_printf (MSG_NOTE, "\n");
814 STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
815 = initial_condition_in_loop_num (access_fn, loop->num);
816 STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo)
817 = evolution_part_in_loop_num (access_fn, loop->num);
820 if (!access_fn
821 || !vect_is_simple_iv_evolution (loop->num, access_fn, &init, &step)
822 || (LOOP_VINFO_LOOP (loop_vinfo) != loop
823 && TREE_CODE (step) != INTEGER_CST))
825 worklist.safe_push (phi);
826 continue;
829 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
830 != NULL_TREE);
831 gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
833 if (dump_enabled_p ())
834 dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
835 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
839 /* Second - identify all reductions and nested cycles. */
840 while (worklist.length () > 0)
842 gimple *phi = worklist.pop ();
843 tree def = PHI_RESULT (phi);
844 stmt_vec_info stmt_vinfo = vinfo_for_stmt (phi);
845 gimple *reduc_stmt;
846 bool nested_cycle;
848 if (dump_enabled_p ())
850 dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: ");
851 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
854 gcc_assert (!virtual_operand_p (def)
855 && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
857 nested_cycle = (loop != LOOP_VINFO_LOOP (loop_vinfo));
858 reduc_stmt = vect_force_simple_reduction (loop_vinfo, phi, !nested_cycle,
859 &double_reduc, false);
860 if (reduc_stmt)
862 if (double_reduc)
864 if (dump_enabled_p ())
865 dump_printf_loc (MSG_NOTE, vect_location,
866 "Detected double reduction.\n");
868 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
869 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
870 vect_double_reduction_def;
872 else
874 if (nested_cycle)
876 if (dump_enabled_p ())
877 dump_printf_loc (MSG_NOTE, vect_location,
878 "Detected vectorizable nested cycle.\n");
880 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
881 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
882 vect_nested_cycle;
884 else
886 if (dump_enabled_p ())
887 dump_printf_loc (MSG_NOTE, vect_location,
888 "Detected reduction.\n");
890 STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
891 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (reduc_stmt)) =
892 vect_reduction_def;
893 /* Store the reduction cycles for possible vectorization in
894 loop-aware SLP. */
895 LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt);
899 else
900 if (dump_enabled_p ())
901 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
902 "Unknown def-use cycle pattern.\n");
907 /* Function vect_analyze_scalar_cycles.
909 Examine the cross iteration def-use cycles of scalar variables, by
910 analyzing the loop-header PHIs of scalar variables. Classify each
911 cycle as one of the following: invariant, induction, reduction, unknown.
912 We do that for the loop represented by LOOP_VINFO, and also to its
913 inner-loop, if exists.
914 Examples for scalar cycles:
916 Example1: reduction:
918 loop1:
919 for (i=0; i<N; i++)
920 sum += a[i];
922 Example2: induction:
924 loop2:
925 for (i=0; i<N; i++)
926 a[i] = i; */
928 static void
929 vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
931 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
933 vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
935 /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
936 Reductions in such inner-loop therefore have different properties than
937 the reductions in the nest that gets vectorized:
938 1. When vectorized, they are executed in the same order as in the original
939 scalar loop, so we can't change the order of computation when
940 vectorizing them.
941 2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
942 current checks are too strict. */
944 if (loop->inner)
945 vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
948 /* Transfer group and reduction information from STMT to its pattern stmt. */
950 static void
951 vect_fixup_reduc_chain (gimple *stmt)
953 gimple *firstp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
954 gimple *stmtp;
955 gcc_assert (!GROUP_FIRST_ELEMENT (vinfo_for_stmt (firstp))
956 && GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
957 GROUP_SIZE (vinfo_for_stmt (firstp)) = GROUP_SIZE (vinfo_for_stmt (stmt));
960 stmtp = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
961 GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmtp)) = firstp;
962 stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmt));
963 if (stmt)
964 GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmtp))
965 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
967 while (stmt);
968 STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmtp)) = vect_reduction_def;
971 /* Fixup scalar cycles that now have their stmts detected as patterns. */
973 static void
974 vect_fixup_scalar_cycles_with_patterns (loop_vec_info loop_vinfo)
976 gimple *first;
977 unsigned i;
979 FOR_EACH_VEC_ELT (LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo), i, first)
980 if (STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (first)))
982 gimple *next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (first));
983 while (next)
985 if (! STMT_VINFO_IN_PATTERN_P (vinfo_for_stmt (next)))
986 break;
987 next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
989 /* If not all stmt in the chain are patterns try to handle
990 the chain without patterns. */
991 if (! next)
993 vect_fixup_reduc_chain (first);
994 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo)[i]
995 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (first));
1000 /* Function vect_get_loop_niters.
1002 Determine how many iterations the loop is executed and place it
1003 in NUMBER_OF_ITERATIONS. Place the number of latch iterations
1004 in NUMBER_OF_ITERATIONSM1. Place the condition under which the
1005 niter information holds in ASSUMPTIONS.
1007 Return the loop exit condition. */
1010 static gcond *
1011 vect_get_loop_niters (struct loop *loop, tree *assumptions,
1012 tree *number_of_iterations, tree *number_of_iterationsm1)
1014 edge exit = single_exit (loop);
1015 struct tree_niter_desc niter_desc;
1016 tree niter_assumptions, niter, may_be_zero;
1017 gcond *cond = get_loop_exit_condition (loop);
1019 *assumptions = boolean_true_node;
1020 *number_of_iterationsm1 = chrec_dont_know;
1021 *number_of_iterations = chrec_dont_know;
1022 if (dump_enabled_p ())
1023 dump_printf_loc (MSG_NOTE, vect_location,
1024 "=== get_loop_niters ===\n");
1026 if (!exit)
1027 return cond;
1029 niter = chrec_dont_know;
1030 may_be_zero = NULL_TREE;
1031 niter_assumptions = boolean_true_node;
1032 if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
1033 || chrec_contains_undetermined (niter_desc.niter))
1034 return cond;
1036 niter_assumptions = niter_desc.assumptions;
1037 may_be_zero = niter_desc.may_be_zero;
1038 niter = niter_desc.niter;
1040 if (may_be_zero && integer_zerop (may_be_zero))
1041 may_be_zero = NULL_TREE;
1043 if (may_be_zero)
1045 if (COMPARISON_CLASS_P (may_be_zero))
1047 /* Try to combine may_be_zero with assumptions, this can simplify
1048 computation of niter expression. */
1049 if (niter_assumptions && !integer_nonzerop (niter_assumptions))
1050 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1051 niter_assumptions,
1052 fold_build1 (TRUTH_NOT_EXPR,
1053 boolean_type_node,
1054 may_be_zero));
1055 else
1056 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
1057 build_int_cst (TREE_TYPE (niter), 0), niter);
1059 may_be_zero = NULL_TREE;
1061 else if (integer_nonzerop (may_be_zero))
1063 *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
1064 *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
1065 return cond;
1067 else
1068 return cond;
1071 *assumptions = niter_assumptions;
1072 *number_of_iterationsm1 = niter;
1074 /* We want the number of loop header executions which is the number
1075 of latch executions plus one.
1076 ??? For UINT_MAX latch executions this number overflows to zero
1077 for loops like do { n++; } while (n != 0); */
1078 if (niter && !chrec_contains_undetermined (niter))
1079 niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), unshare_expr (niter),
1080 build_int_cst (TREE_TYPE (niter), 1));
1081 *number_of_iterations = niter;
1083 return cond;
1086 /* Function bb_in_loop_p
1088 Used as predicate for dfs order traversal of the loop bbs. */
1090 static bool
1091 bb_in_loop_p (const_basic_block bb, const void *data)
1093 const struct loop *const loop = (const struct loop *)data;
1094 if (flow_bb_inside_loop_p (loop, bb))
1095 return true;
1096 return false;
1100 /* Function new_loop_vec_info.
1102 Create and initialize a new loop_vec_info struct for LOOP, as well as
1103 stmt_vec_info structs for all the stmts in LOOP. */
1105 static loop_vec_info
1106 new_loop_vec_info (struct loop *loop)
1108 loop_vec_info res;
1109 basic_block *bbs;
1110 gimple_stmt_iterator si;
1111 unsigned int i, nbbs;
1113 res = (loop_vec_info) xcalloc (1, sizeof (struct _loop_vec_info));
1114 res->kind = vec_info::loop;
1115 LOOP_VINFO_LOOP (res) = loop;
1117 bbs = get_loop_body (loop);
1119 /* Create/Update stmt_info for all stmts in the loop. */
1120 for (i = 0; i < loop->num_nodes; i++)
1122 basic_block bb = bbs[i];
1124 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1126 gimple *phi = gsi_stmt (si);
1127 gimple_set_uid (phi, 0);
1128 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, res));
1131 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1133 gimple *stmt = gsi_stmt (si);
1134 gimple_set_uid (stmt, 0);
1135 set_vinfo_for_stmt (stmt, new_stmt_vec_info (stmt, res));
1139 /* CHECKME: We want to visit all BBs before their successors (except for
1140 latch blocks, for which this assertion wouldn't hold). In the simple
1141 case of the loop forms we allow, a dfs order of the BBs would the same
1142 as reversed postorder traversal, so we are safe. */
1144 free (bbs);
1145 bbs = XCNEWVEC (basic_block, loop->num_nodes);
1146 nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p,
1147 bbs, loop->num_nodes, loop);
1148 gcc_assert (nbbs == loop->num_nodes);
1150 LOOP_VINFO_BBS (res) = bbs;
1151 LOOP_VINFO_NITERSM1 (res) = NULL;
1152 LOOP_VINFO_NITERS (res) = NULL;
1153 LOOP_VINFO_NITERS_UNCHANGED (res) = NULL;
1154 LOOP_VINFO_NITERS_ASSUMPTIONS (res) = NULL;
1155 LOOP_VINFO_COST_MODEL_THRESHOLD (res) = 0;
1156 LOOP_VINFO_VECTORIZABLE_P (res) = 0;
1157 LOOP_VINFO_PEELING_FOR_ALIGNMENT (res) = 0;
1158 LOOP_VINFO_VECT_FACTOR (res) = 0;
1159 LOOP_VINFO_LOOP_NEST (res) = vNULL;
1160 LOOP_VINFO_DATAREFS (res) = vNULL;
1161 LOOP_VINFO_DDRS (res) = vNULL;
1162 LOOP_VINFO_UNALIGNED_DR (res) = NULL;
1163 LOOP_VINFO_MAY_MISALIGN_STMTS (res) = vNULL;
1164 LOOP_VINFO_MAY_ALIAS_DDRS (res) = vNULL;
1165 LOOP_VINFO_GROUPED_STORES (res) = vNULL;
1166 LOOP_VINFO_REDUCTIONS (res) = vNULL;
1167 LOOP_VINFO_REDUCTION_CHAINS (res) = vNULL;
1168 LOOP_VINFO_SLP_INSTANCES (res) = vNULL;
1169 LOOP_VINFO_SLP_UNROLLING_FACTOR (res) = 1;
1170 LOOP_VINFO_TARGET_COST_DATA (res) = init_cost (loop);
1171 LOOP_VINFO_PEELING_FOR_GAPS (res) = false;
1172 LOOP_VINFO_PEELING_FOR_NITER (res) = false;
1173 LOOP_VINFO_OPERANDS_SWAPPED (res) = false;
1175 return res;
1179 /* Function destroy_loop_vec_info.
1181 Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the
1182 stmts in the loop. */
1184 void
1185 destroy_loop_vec_info (loop_vec_info loop_vinfo, bool clean_stmts)
1187 struct loop *loop;
1188 basic_block *bbs;
1189 int nbbs;
1190 gimple_stmt_iterator si;
1191 int j;
1192 vec<slp_instance> slp_instances;
1193 slp_instance instance;
1194 bool swapped;
1196 if (!loop_vinfo)
1197 return;
1199 loop = LOOP_VINFO_LOOP (loop_vinfo);
1201 bbs = LOOP_VINFO_BBS (loop_vinfo);
1202 nbbs = clean_stmts ? loop->num_nodes : 0;
1203 swapped = LOOP_VINFO_OPERANDS_SWAPPED (loop_vinfo);
1205 for (j = 0; j < nbbs; j++)
1207 basic_block bb = bbs[j];
1208 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
1209 free_stmt_vec_info (gsi_stmt (si));
1211 for (si = gsi_start_bb (bb); !gsi_end_p (si); )
1213 gimple *stmt = gsi_stmt (si);
1215 /* We may have broken canonical form by moving a constant
1216 into RHS1 of a commutative op. Fix such occurrences. */
1217 if (swapped && is_gimple_assign (stmt))
1219 enum tree_code code = gimple_assign_rhs_code (stmt);
1221 if ((code == PLUS_EXPR
1222 || code == POINTER_PLUS_EXPR
1223 || code == MULT_EXPR)
1224 && CONSTANT_CLASS_P (gimple_assign_rhs1 (stmt)))
1225 swap_ssa_operands (stmt,
1226 gimple_assign_rhs1_ptr (stmt),
1227 gimple_assign_rhs2_ptr (stmt));
1230 /* Free stmt_vec_info. */
1231 free_stmt_vec_info (stmt);
1232 gsi_next (&si);
1236 free (LOOP_VINFO_BBS (loop_vinfo));
1237 vect_destroy_datarefs (loop_vinfo);
1238 free_dependence_relations (LOOP_VINFO_DDRS (loop_vinfo));
1239 LOOP_VINFO_LOOP_NEST (loop_vinfo).release ();
1240 LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).release ();
1241 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
1242 LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).release ();
1243 slp_instances = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
1244 FOR_EACH_VEC_ELT (slp_instances, j, instance)
1245 vect_free_slp_instance (instance);
1247 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
1248 LOOP_VINFO_GROUPED_STORES (loop_vinfo).release ();
1249 LOOP_VINFO_REDUCTIONS (loop_vinfo).release ();
1250 LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).release ();
1252 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
1253 loop_vinfo->scalar_cost_vec.release ();
1255 free (loop_vinfo);
1256 loop->aux = NULL;
1260 /* Calculate the cost of one scalar iteration of the loop. */
1261 static void
1262 vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
1264 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1265 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1266 int nbbs = loop->num_nodes, factor, scalar_single_iter_cost = 0;
1267 int innerloop_iters, i;
1269 /* Count statements in scalar loop. Using this as scalar cost for a single
1270 iteration for now.
1272 TODO: Add outer loop support.
1274 TODO: Consider assigning different costs to different scalar
1275 statements. */
1277 /* FORNOW. */
1278 innerloop_iters = 1;
1279 if (loop->inner)
1280 innerloop_iters = 50; /* FIXME */
1282 for (i = 0; i < nbbs; i++)
1284 gimple_stmt_iterator si;
1285 basic_block bb = bbs[i];
1287 if (bb->loop_father == loop->inner)
1288 factor = innerloop_iters;
1289 else
1290 factor = 1;
1292 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
1294 gimple *stmt = gsi_stmt (si);
1295 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1297 if (!is_gimple_assign (stmt) && !is_gimple_call (stmt))
1298 continue;
1300 /* Skip stmts that are not vectorized inside the loop. */
1301 if (stmt_info
1302 && !STMT_VINFO_RELEVANT_P (stmt_info)
1303 && (!STMT_VINFO_LIVE_P (stmt_info)
1304 || !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1305 && !STMT_VINFO_IN_PATTERN_P (stmt_info))
1306 continue;
1308 vect_cost_for_stmt kind;
1309 if (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt)))
1311 if (DR_IS_READ (STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt))))
1312 kind = scalar_load;
1313 else
1314 kind = scalar_store;
1316 else
1317 kind = scalar_stmt;
1319 scalar_single_iter_cost
1320 += record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
1321 factor, kind, NULL, 0, vect_prologue);
1324 LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo)
1325 = scalar_single_iter_cost;
1329 /* Function vect_analyze_loop_form_1.
1331 Verify that certain CFG restrictions hold, including:
1332 - the loop has a pre-header
1333 - the loop has a single entry and exit
1334 - the loop exit condition is simple enough
1335 - the number of iterations can be analyzed, i.e, a countable loop. The
1336 niter could be analyzed under some assumptions. */
1338 bool
1339 vect_analyze_loop_form_1 (struct loop *loop, gcond **loop_cond,
1340 tree *assumptions, tree *number_of_iterationsm1,
1341 tree *number_of_iterations, gcond **inner_loop_cond)
1343 if (dump_enabled_p ())
1344 dump_printf_loc (MSG_NOTE, vect_location,
1345 "=== vect_analyze_loop_form ===\n");
1347 /* Different restrictions apply when we are considering an inner-most loop,
1348 vs. an outer (nested) loop.
1349 (FORNOW. May want to relax some of these restrictions in the future). */
1351 if (!loop->inner)
1353 /* Inner-most loop. We currently require that the number of BBs is
1354 exactly 2 (the header and latch). Vectorizable inner-most loops
1355 look like this:
1357 (pre-header)
1359 header <--------+
1360 | | |
1361 | +--> latch --+
1363 (exit-bb) */
1365 if (loop->num_nodes != 2)
1367 if (dump_enabled_p ())
1368 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1369 "not vectorized: control flow in loop.\n");
1370 return false;
1373 if (empty_block_p (loop->header))
1375 if (dump_enabled_p ())
1376 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1377 "not vectorized: empty loop.\n");
1378 return false;
1381 else
1383 struct loop *innerloop = loop->inner;
1384 edge entryedge;
1386 /* Nested loop. We currently require that the loop is doubly-nested,
1387 contains a single inner loop, and the number of BBs is exactly 5.
1388 Vectorizable outer-loops look like this:
1390 (pre-header)
1392 header <---+
1394 inner-loop |
1396 tail ------+
1398 (exit-bb)
1400 The inner-loop has the properties expected of inner-most loops
1401 as described above. */
1403 if ((loop->inner)->inner || (loop->inner)->next)
1405 if (dump_enabled_p ())
1406 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1407 "not vectorized: multiple nested loops.\n");
1408 return false;
1411 if (loop->num_nodes != 5)
1413 if (dump_enabled_p ())
1414 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1415 "not vectorized: control flow in loop.\n");
1416 return false;
1419 entryedge = loop_preheader_edge (innerloop);
1420 if (entryedge->src != loop->header
1421 || !single_exit (innerloop)
1422 || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
1424 if (dump_enabled_p ())
1425 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1426 "not vectorized: unsupported outerloop form.\n");
1427 return false;
1430 /* Analyze the inner-loop. */
1431 tree inner_niterm1, inner_niter, inner_assumptions;
1432 if (! vect_analyze_loop_form_1 (loop->inner, inner_loop_cond,
1433 &inner_assumptions, &inner_niterm1,
1434 &inner_niter, NULL)
1435 /* Don't support analyzing niter under assumptions for inner
1436 loop. */
1437 || !integer_onep (inner_assumptions))
1439 if (dump_enabled_p ())
1440 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1441 "not vectorized: Bad inner loop.\n");
1442 return false;
1445 if (!expr_invariant_in_loop_p (loop, inner_niter))
1447 if (dump_enabled_p ())
1448 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1449 "not vectorized: inner-loop count not"
1450 " invariant.\n");
1451 return false;
1454 if (dump_enabled_p ())
1455 dump_printf_loc (MSG_NOTE, vect_location,
1456 "Considering outer-loop vectorization.\n");
1459 if (!single_exit (loop)
1460 || EDGE_COUNT (loop->header->preds) != 2)
1462 if (dump_enabled_p ())
1464 if (!single_exit (loop))
1465 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1466 "not vectorized: multiple exits.\n");
1467 else if (EDGE_COUNT (loop->header->preds) != 2)
1468 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1469 "not vectorized: too many incoming edges.\n");
1471 return false;
1474 /* We assume that the loop exit condition is at the end of the loop. i.e,
1475 that the loop is represented as a do-while (with a proper if-guard
1476 before the loop if needed), where the loop header contains all the
1477 executable statements, and the latch is empty. */
1478 if (!empty_block_p (loop->latch)
1479 || !gimple_seq_empty_p (phi_nodes (loop->latch)))
1481 if (dump_enabled_p ())
1482 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1483 "not vectorized: latch block not empty.\n");
1484 return false;
1487 /* Make sure the exit is not abnormal. */
1488 edge e = single_exit (loop);
1489 if (e->flags & EDGE_ABNORMAL)
1491 if (dump_enabled_p ())
1492 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1493 "not vectorized: abnormal loop exit edge.\n");
1494 return false;
1497 *loop_cond = vect_get_loop_niters (loop, assumptions, number_of_iterations,
1498 number_of_iterationsm1);
1499 if (!*loop_cond)
1501 if (dump_enabled_p ())
1502 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1503 "not vectorized: complicated exit condition.\n");
1504 return false;
1507 if (integer_zerop (*assumptions)
1508 || !*number_of_iterations
1509 || chrec_contains_undetermined (*number_of_iterations))
1511 if (dump_enabled_p ())
1512 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1513 "not vectorized: number of iterations cannot be "
1514 "computed.\n");
1515 return false;
1518 if (integer_zerop (*number_of_iterations))
1520 if (dump_enabled_p ())
1521 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1522 "not vectorized: number of iterations = 0.\n");
1523 return false;
1526 return true;
1529 /* Analyze LOOP form and return a loop_vec_info if it is of suitable form. */
1531 loop_vec_info
1532 vect_analyze_loop_form (struct loop *loop)
1534 tree assumptions, number_of_iterations, number_of_iterationsm1;
1535 gcond *loop_cond, *inner_loop_cond = NULL;
1537 if (! vect_analyze_loop_form_1 (loop, &loop_cond,
1538 &assumptions, &number_of_iterationsm1,
1539 &number_of_iterations, &inner_loop_cond))
1540 return NULL;
1542 loop_vec_info loop_vinfo = new_loop_vec_info (loop);
1543 LOOP_VINFO_NITERSM1 (loop_vinfo) = number_of_iterationsm1;
1544 LOOP_VINFO_NITERS (loop_vinfo) = number_of_iterations;
1545 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = number_of_iterations;
1546 if (!integer_onep (assumptions))
1548 /* We consider to vectorize this loop by versioning it under
1549 some assumptions. In order to do this, we need to clear
1550 existing information computed by scev and niter analyzer. */
1551 scev_reset_htab ();
1552 free_numbers_of_iterations_estimates_loop (loop);
1553 /* Also set flag for this loop so that following scev and niter
1554 analysis are done under the assumptions. */
1555 loop_constraint_set (loop, LOOP_C_FINITE);
1556 /* Also record the assumptions for versioning. */
1557 LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = assumptions;
1560 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
1562 if (dump_enabled_p ())
1564 dump_printf_loc (MSG_NOTE, vect_location,
1565 "Symbolic number of iterations is ");
1566 dump_generic_expr (MSG_NOTE, TDF_DETAILS, number_of_iterations);
1567 dump_printf (MSG_NOTE, "\n");
1571 STMT_VINFO_TYPE (vinfo_for_stmt (loop_cond)) = loop_exit_ctrl_vec_info_type;
1572 if (inner_loop_cond)
1573 STMT_VINFO_TYPE (vinfo_for_stmt (inner_loop_cond))
1574 = loop_exit_ctrl_vec_info_type;
1576 gcc_assert (!loop->aux);
1577 loop->aux = loop_vinfo;
1578 return loop_vinfo;
1583 /* Scan the loop stmts and dependent on whether there are any (non-)SLP
1584 statements update the vectorization factor. */
1586 static void
1587 vect_update_vf_for_slp (loop_vec_info loop_vinfo)
1589 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1590 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1591 int nbbs = loop->num_nodes;
1592 unsigned int vectorization_factor;
1593 int i;
1595 if (dump_enabled_p ())
1596 dump_printf_loc (MSG_NOTE, vect_location,
1597 "=== vect_update_vf_for_slp ===\n");
1599 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1600 gcc_assert (vectorization_factor != 0);
1602 /* If all the stmts in the loop can be SLPed, we perform only SLP, and
1603 vectorization factor of the loop is the unrolling factor required by
1604 the SLP instances. If that unrolling factor is 1, we say, that we
1605 perform pure SLP on loop - cross iteration parallelism is not
1606 exploited. */
1607 bool only_slp_in_loop = true;
1608 for (i = 0; i < nbbs; i++)
1610 basic_block bb = bbs[i];
1611 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1612 gsi_next (&si))
1614 gimple *stmt = gsi_stmt (si);
1615 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1616 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
1617 && STMT_VINFO_RELATED_STMT (stmt_info))
1619 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
1620 stmt_info = vinfo_for_stmt (stmt);
1622 if ((STMT_VINFO_RELEVANT_P (stmt_info)
1623 || VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info)))
1624 && !PURE_SLP_STMT (stmt_info))
1625 /* STMT needs both SLP and loop-based vectorization. */
1626 only_slp_in_loop = false;
1630 if (only_slp_in_loop)
1631 vectorization_factor = LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo);
1632 else
1633 vectorization_factor
1634 = least_common_multiple (vectorization_factor,
1635 LOOP_VINFO_SLP_UNROLLING_FACTOR (loop_vinfo));
1637 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = vectorization_factor;
1638 if (dump_enabled_p ())
1639 dump_printf_loc (MSG_NOTE, vect_location,
1640 "Updating vectorization factor to %d\n",
1641 vectorization_factor);
1644 /* Function vect_analyze_loop_operations.
1646 Scan the loop stmts and make sure they are all vectorizable. */
1648 static bool
1649 vect_analyze_loop_operations (loop_vec_info loop_vinfo)
1651 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1652 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1653 int nbbs = loop->num_nodes;
1654 int i;
1655 stmt_vec_info stmt_info;
1656 bool need_to_vectorize = false;
1657 bool ok;
1659 if (dump_enabled_p ())
1660 dump_printf_loc (MSG_NOTE, vect_location,
1661 "=== vect_analyze_loop_operations ===\n");
1663 for (i = 0; i < nbbs; i++)
1665 basic_block bb = bbs[i];
1667 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
1668 gsi_next (&si))
1670 gphi *phi = si.phi ();
1671 ok = true;
1673 stmt_info = vinfo_for_stmt (phi);
1674 if (dump_enabled_p ())
1676 dump_printf_loc (MSG_NOTE, vect_location, "examining phi: ");
1677 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
1679 if (virtual_operand_p (gimple_phi_result (phi)))
1680 continue;
1682 /* Inner-loop loop-closed exit phi in outer-loop vectorization
1683 (i.e., a phi in the tail of the outer-loop). */
1684 if (! is_loop_header_bb_p (bb))
1686 /* FORNOW: we currently don't support the case that these phis
1687 are not used in the outerloop (unless it is double reduction,
1688 i.e., this phi is vect_reduction_def), cause this case
1689 requires to actually do something here. */
1690 if ((!STMT_VINFO_RELEVANT_P (stmt_info)
1691 || STMT_VINFO_LIVE_P (stmt_info))
1692 && STMT_VINFO_DEF_TYPE (stmt_info)
1693 != vect_double_reduction_def)
1695 if (dump_enabled_p ())
1696 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1697 "Unsupported loop-closed phi in "
1698 "outer-loop.\n");
1699 return false;
1702 /* If PHI is used in the outer loop, we check that its operand
1703 is defined in the inner loop. */
1704 if (STMT_VINFO_RELEVANT_P (stmt_info))
1706 tree phi_op;
1707 gimple *op_def_stmt;
1709 if (gimple_phi_num_args (phi) != 1)
1710 return false;
1712 phi_op = PHI_ARG_DEF (phi, 0);
1713 if (TREE_CODE (phi_op) != SSA_NAME)
1714 return false;
1716 op_def_stmt = SSA_NAME_DEF_STMT (phi_op);
1717 if (gimple_nop_p (op_def_stmt)
1718 || !flow_bb_inside_loop_p (loop, gimple_bb (op_def_stmt))
1719 || !vinfo_for_stmt (op_def_stmt))
1720 return false;
1722 if (STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1723 != vect_used_in_outer
1724 && STMT_VINFO_RELEVANT (vinfo_for_stmt (op_def_stmt))
1725 != vect_used_in_outer_by_reduction)
1726 return false;
1729 continue;
1732 gcc_assert (stmt_info);
1734 if ((STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope
1735 || STMT_VINFO_LIVE_P (stmt_info))
1736 && STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
1738 /* A scalar-dependence cycle that we don't support. */
1739 if (dump_enabled_p ())
1740 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1741 "not vectorized: scalar dependence cycle.\n");
1742 return false;
1745 if (STMT_VINFO_RELEVANT_P (stmt_info))
1747 need_to_vectorize = true;
1748 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
1749 ok = vectorizable_induction (phi, NULL, NULL);
1752 if (ok && STMT_VINFO_LIVE_P (stmt_info))
1753 ok = vectorizable_live_operation (phi, NULL, NULL, -1, NULL);
1755 if (!ok)
1757 if (dump_enabled_p ())
1759 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1760 "not vectorized: relevant phi not "
1761 "supported: ");
1762 dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, phi, 0);
1764 return false;
1768 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
1769 gsi_next (&si))
1771 gimple *stmt = gsi_stmt (si);
1772 if (!gimple_clobber_p (stmt)
1773 && !vect_analyze_stmt (stmt, &need_to_vectorize, NULL))
1774 return false;
1776 } /* bbs */
1778 /* All operations in the loop are either irrelevant (deal with loop
1779 control, or dead), or only used outside the loop and can be moved
1780 out of the loop (e.g. invariants, inductions). The loop can be
1781 optimized away by scalar optimizations. We're better off not
1782 touching this loop. */
1783 if (!need_to_vectorize)
1785 if (dump_enabled_p ())
1786 dump_printf_loc (MSG_NOTE, vect_location,
1787 "All the computation can be taken out of the loop.\n");
1788 if (dump_enabled_p ())
1789 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1790 "not vectorized: redundant loop. no profit to "
1791 "vectorize.\n");
1792 return false;
1795 return true;
1799 /* Function vect_analyze_loop_2.
1801 Apply a set of analyses on LOOP, and create a loop_vec_info struct
1802 for it. The different analyses will record information in the
1803 loop_vec_info struct. */
1804 static bool
1805 vect_analyze_loop_2 (loop_vec_info loop_vinfo, bool &fatal)
1807 bool ok;
1808 int max_vf = MAX_VECTORIZATION_FACTOR;
1809 int min_vf = 2;
1810 unsigned int n_stmts = 0;
1812 /* The first group of checks is independent of the vector size. */
1813 fatal = true;
1815 /* Find all data references in the loop (which correspond to vdefs/vuses)
1816 and analyze their evolution in the loop. */
1818 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
1820 loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
1821 if (!find_loop_nest (loop, &LOOP_VINFO_LOOP_NEST (loop_vinfo)))
1823 if (dump_enabled_p ())
1824 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1825 "not vectorized: loop nest containing two "
1826 "or more consecutive inner loops cannot be "
1827 "vectorized\n");
1828 return false;
1831 for (unsigned i = 0; i < loop->num_nodes; i++)
1832 for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
1833 !gsi_end_p (gsi); gsi_next (&gsi))
1835 gimple *stmt = gsi_stmt (gsi);
1836 if (is_gimple_debug (stmt))
1837 continue;
1838 ++n_stmts;
1839 if (!find_data_references_in_stmt (loop, stmt,
1840 &LOOP_VINFO_DATAREFS (loop_vinfo)))
1842 if (is_gimple_call (stmt) && loop->safelen)
1844 tree fndecl = gimple_call_fndecl (stmt), op;
1845 if (fndecl != NULL_TREE)
1847 cgraph_node *node = cgraph_node::get (fndecl);
1848 if (node != NULL && node->simd_clones != NULL)
1850 unsigned int j, n = gimple_call_num_args (stmt);
1851 for (j = 0; j < n; j++)
1853 op = gimple_call_arg (stmt, j);
1854 if (DECL_P (op)
1855 || (REFERENCE_CLASS_P (op)
1856 && get_base_address (op)))
1857 break;
1859 op = gimple_call_lhs (stmt);
1860 /* Ignore #pragma omp declare simd functions
1861 if they don't have data references in the
1862 call stmt itself. */
1863 if (j == n
1864 && !(op
1865 && (DECL_P (op)
1866 || (REFERENCE_CLASS_P (op)
1867 && get_base_address (op)))))
1868 continue;
1872 if (dump_enabled_p ())
1873 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1874 "not vectorized: loop contains function "
1875 "calls or data references that cannot "
1876 "be analyzed\n");
1877 return false;
1881 /* Analyze the data references and also adjust the minimal
1882 vectorization factor according to the loads and stores. */
1884 ok = vect_analyze_data_refs (loop_vinfo, &min_vf);
1885 if (!ok)
1887 if (dump_enabled_p ())
1888 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1889 "bad data references.\n");
1890 return false;
1893 /* Classify all cross-iteration scalar data-flow cycles.
1894 Cross-iteration cycles caused by virtual phis are analyzed separately. */
1895 vect_analyze_scalar_cycles (loop_vinfo);
1897 vect_pattern_recog (loop_vinfo);
1899 vect_fixup_scalar_cycles_with_patterns (loop_vinfo);
1901 /* Analyze the access patterns of the data-refs in the loop (consecutive,
1902 complex, etc.). FORNOW: Only handle consecutive access pattern. */
1904 ok = vect_analyze_data_ref_accesses (loop_vinfo);
1905 if (!ok)
1907 if (dump_enabled_p ())
1908 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1909 "bad data access.\n");
1910 return false;
1913 /* Data-flow analysis to detect stmts that do not need to be vectorized. */
1915 ok = vect_mark_stmts_to_be_vectorized (loop_vinfo);
1916 if (!ok)
1918 if (dump_enabled_p ())
1919 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1920 "unexpected pattern.\n");
1921 return false;
1924 /* While the rest of the analysis below depends on it in some way. */
1925 fatal = false;
1927 /* Analyze data dependences between the data-refs in the loop
1928 and adjust the maximum vectorization factor according to
1929 the dependences.
1930 FORNOW: fail at the first data dependence that we encounter. */
1932 ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
1933 if (!ok
1934 || max_vf < min_vf)
1936 if (dump_enabled_p ())
1937 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1938 "bad data dependence.\n");
1939 return false;
1942 ok = vect_determine_vectorization_factor (loop_vinfo);
1943 if (!ok)
1945 if (dump_enabled_p ())
1946 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1947 "can't determine vectorization factor.\n");
1948 return false;
1950 if (max_vf < LOOP_VINFO_VECT_FACTOR (loop_vinfo))
1952 if (dump_enabled_p ())
1953 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
1954 "bad data dependence.\n");
1955 return false;
1958 /* Compute the scalar iteration cost. */
1959 vect_compute_single_scalar_iteration_cost (loop_vinfo);
1961 int saved_vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1962 HOST_WIDE_INT estimated_niter;
1963 unsigned th;
1964 int min_scalar_loop_bound;
1966 /* Check the SLP opportunities in the loop, analyze and build SLP trees. */
1967 ok = vect_analyze_slp (loop_vinfo, n_stmts);
1968 if (!ok)
1969 return false;
1971 /* If there are any SLP instances mark them as pure_slp. */
1972 bool slp = vect_make_slp_decision (loop_vinfo);
1973 if (slp)
1975 /* Find stmts that need to be both vectorized and SLPed. */
1976 vect_detect_hybrid_slp (loop_vinfo);
1978 /* Update the vectorization factor based on the SLP decision. */
1979 vect_update_vf_for_slp (loop_vinfo);
1982 /* This is the point where we can re-start analysis with SLP forced off. */
1983 start_over:
1985 /* Now the vectorization factor is final. */
1986 unsigned vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
1987 gcc_assert (vectorization_factor != 0);
1989 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
1990 dump_printf_loc (MSG_NOTE, vect_location,
1991 "vectorization_factor = %d, niters = "
1992 HOST_WIDE_INT_PRINT_DEC "\n", vectorization_factor,
1993 LOOP_VINFO_INT_NITERS (loop_vinfo));
1995 HOST_WIDE_INT max_niter
1996 = likely_max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
1997 if ((LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
1998 && (LOOP_VINFO_INT_NITERS (loop_vinfo) < vectorization_factor))
1999 || (max_niter != -1
2000 && (unsigned HOST_WIDE_INT) max_niter < vectorization_factor))
2002 if (dump_enabled_p ())
2003 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2004 "not vectorized: iteration count smaller than "
2005 "vectorization factor.\n");
2006 return false;
2009 /* Analyze the alignment of the data-refs in the loop.
2010 Fail if a data reference is found that cannot be vectorized. */
2012 ok = vect_analyze_data_refs_alignment (loop_vinfo);
2013 if (!ok)
2015 if (dump_enabled_p ())
2016 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2017 "bad data alignment.\n");
2018 return false;
2021 /* Prune the list of ddrs to be tested at run-time by versioning for alias.
2022 It is important to call pruning after vect_analyze_data_ref_accesses,
2023 since we use grouping information gathered by interleaving analysis. */
2024 ok = vect_prune_runtime_alias_test_list (loop_vinfo);
2025 if (!ok)
2026 return false;
2028 /* This pass will decide on using loop versioning and/or loop peeling in
2029 order to enhance the alignment of data references in the loop. */
2030 ok = vect_enhance_data_refs_alignment (loop_vinfo);
2031 if (!ok)
2033 if (dump_enabled_p ())
2034 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2035 "bad data alignment.\n");
2036 return false;
2039 if (slp)
2041 /* Analyze operations in the SLP instances. Note this may
2042 remove unsupported SLP instances which makes the above
2043 SLP kind detection invalid. */
2044 unsigned old_size = LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length ();
2045 vect_slp_analyze_operations (LOOP_VINFO_SLP_INSTANCES (loop_vinfo),
2046 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2047 if (LOOP_VINFO_SLP_INSTANCES (loop_vinfo).length () != old_size)
2048 goto again;
2051 /* Scan all the remaining operations in the loop that are not subject
2052 to SLP and make sure they are vectorizable. */
2053 ok = vect_analyze_loop_operations (loop_vinfo);
2054 if (!ok)
2056 if (dump_enabled_p ())
2057 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2058 "bad operation or unsupported loop bound.\n");
2059 return false;
2062 /* Analyze cost. Decide if worth while to vectorize. */
2063 int min_profitable_estimate, min_profitable_iters;
2064 vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
2065 &min_profitable_estimate);
2067 if (min_profitable_iters < 0)
2069 if (dump_enabled_p ())
2070 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2071 "not vectorized: vectorization not profitable.\n");
2072 if (dump_enabled_p ())
2073 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2074 "not vectorized: vector version will never be "
2075 "profitable.\n");
2076 goto again;
2079 min_scalar_loop_bound = ((PARAM_VALUE (PARAM_MIN_VECT_LOOP_BOUND)
2080 * vectorization_factor) - 1);
2082 /* Use the cost model only if it is more conservative than user specified
2083 threshold. */
2084 th = (unsigned) min_scalar_loop_bound;
2085 if (min_profitable_iters
2086 && (!min_scalar_loop_bound
2087 || min_profitable_iters > min_scalar_loop_bound))
2088 th = (unsigned) min_profitable_iters;
2090 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
2092 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2093 && LOOP_VINFO_INT_NITERS (loop_vinfo) <= th)
2095 if (dump_enabled_p ())
2096 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2097 "not vectorized: vectorization not profitable.\n");
2098 if (dump_enabled_p ())
2099 dump_printf_loc (MSG_NOTE, vect_location,
2100 "not vectorized: iteration count smaller than user "
2101 "specified loop bound parameter or minimum profitable "
2102 "iterations (whichever is more conservative).\n");
2103 goto again;
2106 estimated_niter
2107 = estimated_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
2108 if (estimated_niter == -1)
2109 estimated_niter = max_niter;
2110 if (estimated_niter != -1
2111 && ((unsigned HOST_WIDE_INT) estimated_niter
2112 <= MAX (th, (unsigned)min_profitable_estimate)))
2114 if (dump_enabled_p ())
2115 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2116 "not vectorized: estimated iteration count too "
2117 "small.\n");
2118 if (dump_enabled_p ())
2119 dump_printf_loc (MSG_NOTE, vect_location,
2120 "not vectorized: estimated iteration count smaller "
2121 "than specified loop bound parameter or minimum "
2122 "profitable iterations (whichever is more "
2123 "conservative).\n");
2124 goto again;
2127 /* Decide whether we need to create an epilogue loop to handle
2128 remaining scalar iterations. */
2129 th = ((LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) + 1)
2130 / LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2131 * LOOP_VINFO_VECT_FACTOR (loop_vinfo);
2133 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
2134 && LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) > 0)
2136 if (ctz_hwi (LOOP_VINFO_INT_NITERS (loop_vinfo)
2137 - LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
2138 < exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
2139 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2141 else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
2142 || (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
2143 < (unsigned)exact_log2 (LOOP_VINFO_VECT_FACTOR (loop_vinfo))
2144 /* In case of versioning, check if the maximum number of
2145 iterations is greater than th. If they are identical,
2146 the epilogue is unnecessary. */
2147 && (!LOOP_REQUIRES_VERSIONING (loop_vinfo)
2148 || (unsigned HOST_WIDE_INT) max_niter > th)))
2149 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = true;
2151 /* If an epilogue loop is required make sure we can create one. */
2152 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
2153 || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo))
2155 if (dump_enabled_p ())
2156 dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
2157 if (!vect_can_advance_ivs_p (loop_vinfo)
2158 || !slpeel_can_duplicate_loop_p (LOOP_VINFO_LOOP (loop_vinfo),
2159 single_exit (LOOP_VINFO_LOOP
2160 (loop_vinfo))))
2162 if (dump_enabled_p ())
2163 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2164 "not vectorized: can't create required "
2165 "epilog loop\n");
2166 goto again;
2170 gcc_assert (vectorization_factor
2171 == (unsigned)LOOP_VINFO_VECT_FACTOR (loop_vinfo));
2173 /* Ok to vectorize! */
2174 return true;
2176 again:
2177 /* Try again with SLP forced off but if we didn't do any SLP there is
2178 no point in re-trying. */
2179 if (!slp)
2180 return false;
2182 /* If there are reduction chains re-trying will fail anyway. */
2183 if (! LOOP_VINFO_REDUCTION_CHAINS (loop_vinfo).is_empty ())
2184 return false;
2186 /* Likewise if the grouped loads or stores in the SLP cannot be handled
2187 via interleaving or lane instructions. */
2188 slp_instance instance;
2189 slp_tree node;
2190 unsigned i, j;
2191 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
2193 stmt_vec_info vinfo;
2194 vinfo = vinfo_for_stmt
2195 (SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0]);
2196 if (! STMT_VINFO_GROUPED_ACCESS (vinfo))
2197 continue;
2198 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2199 unsigned int size = STMT_VINFO_GROUP_SIZE (vinfo);
2200 tree vectype = STMT_VINFO_VECTYPE (vinfo);
2201 if (! vect_store_lanes_supported (vectype, size)
2202 && ! vect_grouped_store_supported (vectype, size))
2203 return false;
2204 FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
2206 vinfo = vinfo_for_stmt (SLP_TREE_SCALAR_STMTS (node)[0]);
2207 vinfo = vinfo_for_stmt (STMT_VINFO_GROUP_FIRST_ELEMENT (vinfo));
2208 bool single_element_p = !STMT_VINFO_GROUP_NEXT_ELEMENT (vinfo);
2209 size = STMT_VINFO_GROUP_SIZE (vinfo);
2210 vectype = STMT_VINFO_VECTYPE (vinfo);
2211 if (! vect_load_lanes_supported (vectype, size)
2212 && ! vect_grouped_load_supported (vectype, single_element_p,
2213 size))
2214 return false;
2218 if (dump_enabled_p ())
2219 dump_printf_loc (MSG_NOTE, vect_location,
2220 "re-trying with SLP disabled\n");
2222 /* Roll back state appropriately. No SLP this time. */
2223 slp = false;
2224 /* Restore vectorization factor as it were without SLP. */
2225 LOOP_VINFO_VECT_FACTOR (loop_vinfo) = saved_vectorization_factor;
2226 /* Free the SLP instances. */
2227 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
2228 vect_free_slp_instance (instance);
2229 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
2230 /* Reset SLP type to loop_vect on all stmts. */
2231 for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
2233 basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
2234 for (gimple_stmt_iterator si = gsi_start_bb (bb);
2235 !gsi_end_p (si); gsi_next (&si))
2237 stmt_vec_info stmt_info = vinfo_for_stmt (gsi_stmt (si));
2238 STMT_SLP_TYPE (stmt_info) = loop_vect;
2239 if (STMT_VINFO_IN_PATTERN_P (stmt_info))
2241 stmt_info = vinfo_for_stmt (STMT_VINFO_RELATED_STMT (stmt_info));
2242 STMT_SLP_TYPE (stmt_info) = loop_vect;
2243 for (gimple_stmt_iterator pi
2244 = gsi_start (STMT_VINFO_PATTERN_DEF_SEQ (stmt_info));
2245 !gsi_end_p (pi); gsi_next (&pi))
2247 gimple *pstmt = gsi_stmt (pi);
2248 STMT_SLP_TYPE (vinfo_for_stmt (pstmt)) = loop_vect;
2253 /* Free optimized alias test DDRS. */
2254 LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
2255 /* Reset target cost data. */
2256 destroy_cost_data (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo));
2257 LOOP_VINFO_TARGET_COST_DATA (loop_vinfo)
2258 = init_cost (LOOP_VINFO_LOOP (loop_vinfo));
2259 /* Reset assorted flags. */
2260 LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
2261 LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
2262 LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
2264 goto start_over;
2267 /* Function vect_analyze_loop.
2269 Apply a set of analyses on LOOP, and create a loop_vec_info struct
2270 for it. The different analyses will record information in the
2271 loop_vec_info struct. */
2272 loop_vec_info
2273 vect_analyze_loop (struct loop *loop)
2275 loop_vec_info loop_vinfo;
2276 unsigned int vector_sizes;
2278 /* Autodetect first vector size we try. */
2279 current_vector_size = 0;
2280 vector_sizes = targetm.vectorize.autovectorize_vector_sizes ();
2282 if (dump_enabled_p ())
2283 dump_printf_loc (MSG_NOTE, vect_location,
2284 "===== analyze_loop_nest =====\n");
2286 if (loop_outer (loop)
2287 && loop_vec_info_for_loop (loop_outer (loop))
2288 && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
2290 if (dump_enabled_p ())
2291 dump_printf_loc (MSG_NOTE, vect_location,
2292 "outer-loop already vectorized.\n");
2293 return NULL;
2296 while (1)
2298 /* Check the CFG characteristics of the loop (nesting, entry/exit). */
2299 loop_vinfo = vect_analyze_loop_form (loop);
2300 if (!loop_vinfo)
2302 if (dump_enabled_p ())
2303 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2304 "bad loop form.\n");
2305 return NULL;
2308 bool fatal = false;
2309 if (vect_analyze_loop_2 (loop_vinfo, fatal))
2311 LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
2313 return loop_vinfo;
2316 destroy_loop_vec_info (loop_vinfo, true);
2318 vector_sizes &= ~current_vector_size;
2319 if (fatal
2320 || vector_sizes == 0
2321 || current_vector_size == 0)
2322 return NULL;
2324 /* Try the next biggest vector size. */
2325 current_vector_size = 1 << floor_log2 (vector_sizes);
2326 if (dump_enabled_p ())
2327 dump_printf_loc (MSG_NOTE, vect_location,
2328 "***** Re-trying analysis with "
2329 "vector size %d\n", current_vector_size);
2334 /* Function reduction_code_for_scalar_code
2336 Input:
2337 CODE - tree_code of a reduction operations.
2339 Output:
2340 REDUC_CODE - the corresponding tree-code to be used to reduce the
2341 vector of partial results into a single scalar result, or ERROR_MARK
2342 if the operation is a supported reduction operation, but does not have
2343 such a tree-code.
2345 Return FALSE if CODE currently cannot be vectorized as reduction. */
2347 static bool
2348 reduction_code_for_scalar_code (enum tree_code code,
2349 enum tree_code *reduc_code)
2351 switch (code)
2353 case MAX_EXPR:
2354 *reduc_code = REDUC_MAX_EXPR;
2355 return true;
2357 case MIN_EXPR:
2358 *reduc_code = REDUC_MIN_EXPR;
2359 return true;
2361 case PLUS_EXPR:
2362 *reduc_code = REDUC_PLUS_EXPR;
2363 return true;
2365 case MULT_EXPR:
2366 case MINUS_EXPR:
2367 case BIT_IOR_EXPR:
2368 case BIT_XOR_EXPR:
2369 case BIT_AND_EXPR:
2370 *reduc_code = ERROR_MARK;
2371 return true;
2373 default:
2374 return false;
2379 /* Error reporting helper for vect_is_simple_reduction below. GIMPLE statement
2380 STMT is printed with a message MSG. */
2382 static void
2383 report_vect_op (int msg_type, gimple *stmt, const char *msg)
2385 dump_printf_loc (msg_type, vect_location, "%s", msg);
2386 dump_gimple_stmt (msg_type, TDF_SLIM, stmt, 0);
2390 /* Detect SLP reduction of the form:
2392 #a1 = phi <a5, a0>
2393 a2 = operation (a1)
2394 a3 = operation (a2)
2395 a4 = operation (a3)
2396 a5 = operation (a4)
2398 #a = phi <a5>
2400 PHI is the reduction phi node (#a1 = phi <a5, a0> above)
2401 FIRST_STMT is the first reduction stmt in the chain
2402 (a2 = operation (a1)).
2404 Return TRUE if a reduction chain was detected. */
2406 static bool
2407 vect_is_slp_reduction (loop_vec_info loop_info, gimple *phi,
2408 gimple *first_stmt)
2410 struct loop *loop = (gimple_bb (phi))->loop_father;
2411 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2412 enum tree_code code;
2413 gimple *current_stmt = NULL, *loop_use_stmt = NULL, *first, *next_stmt;
2414 stmt_vec_info use_stmt_info, current_stmt_info;
2415 tree lhs;
2416 imm_use_iterator imm_iter;
2417 use_operand_p use_p;
2418 int nloop_uses, size = 0, n_out_of_loop_uses;
2419 bool found = false;
2421 if (loop != vect_loop)
2422 return false;
2424 lhs = PHI_RESULT (phi);
2425 code = gimple_assign_rhs_code (first_stmt);
2426 while (1)
2428 nloop_uses = 0;
2429 n_out_of_loop_uses = 0;
2430 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
2432 gimple *use_stmt = USE_STMT (use_p);
2433 if (is_gimple_debug (use_stmt))
2434 continue;
2436 /* Check if we got back to the reduction phi. */
2437 if (use_stmt == phi)
2439 loop_use_stmt = use_stmt;
2440 found = true;
2441 break;
2444 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2446 loop_use_stmt = use_stmt;
2447 nloop_uses++;
2449 else
2450 n_out_of_loop_uses++;
2452 /* There are can be either a single use in the loop or two uses in
2453 phi nodes. */
2454 if (nloop_uses > 1 || (n_out_of_loop_uses && nloop_uses))
2455 return false;
2458 if (found)
2459 break;
2461 /* We reached a statement with no loop uses. */
2462 if (nloop_uses == 0)
2463 return false;
2465 /* This is a loop exit phi, and we haven't reached the reduction phi. */
2466 if (gimple_code (loop_use_stmt) == GIMPLE_PHI)
2467 return false;
2469 if (!is_gimple_assign (loop_use_stmt)
2470 || code != gimple_assign_rhs_code (loop_use_stmt)
2471 || !flow_bb_inside_loop_p (loop, gimple_bb (loop_use_stmt)))
2472 return false;
2474 /* Insert USE_STMT into reduction chain. */
2475 use_stmt_info = vinfo_for_stmt (loop_use_stmt);
2476 if (current_stmt)
2478 current_stmt_info = vinfo_for_stmt (current_stmt);
2479 GROUP_NEXT_ELEMENT (current_stmt_info) = loop_use_stmt;
2480 GROUP_FIRST_ELEMENT (use_stmt_info)
2481 = GROUP_FIRST_ELEMENT (current_stmt_info);
2483 else
2484 GROUP_FIRST_ELEMENT (use_stmt_info) = loop_use_stmt;
2486 lhs = gimple_assign_lhs (loop_use_stmt);
2487 current_stmt = loop_use_stmt;
2488 size++;
2491 if (!found || loop_use_stmt != phi || size < 2)
2492 return false;
2494 /* Swap the operands, if needed, to make the reduction operand be the second
2495 operand. */
2496 lhs = PHI_RESULT (phi);
2497 next_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2498 while (next_stmt)
2500 if (gimple_assign_rhs2 (next_stmt) == lhs)
2502 tree op = gimple_assign_rhs1 (next_stmt);
2503 gimple *def_stmt = NULL;
2505 if (TREE_CODE (op) == SSA_NAME)
2506 def_stmt = SSA_NAME_DEF_STMT (op);
2508 /* Check that the other def is either defined in the loop
2509 ("vect_internal_def"), or it's an induction (defined by a
2510 loop-header phi-node). */
2511 if (def_stmt
2512 && gimple_bb (def_stmt)
2513 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2514 && (is_gimple_assign (def_stmt)
2515 || is_gimple_call (def_stmt)
2516 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2517 == vect_induction_def
2518 || (gimple_code (def_stmt) == GIMPLE_PHI
2519 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2520 == vect_internal_def
2521 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2523 lhs = gimple_assign_lhs (next_stmt);
2524 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2525 continue;
2528 return false;
2530 else
2532 tree op = gimple_assign_rhs2 (next_stmt);
2533 gimple *def_stmt = NULL;
2535 if (TREE_CODE (op) == SSA_NAME)
2536 def_stmt = SSA_NAME_DEF_STMT (op);
2538 /* Check that the other def is either defined in the loop
2539 ("vect_internal_def"), or it's an induction (defined by a
2540 loop-header phi-node). */
2541 if (def_stmt
2542 && gimple_bb (def_stmt)
2543 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2544 && (is_gimple_assign (def_stmt)
2545 || is_gimple_call (def_stmt)
2546 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2547 == vect_induction_def
2548 || (gimple_code (def_stmt) == GIMPLE_PHI
2549 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
2550 == vect_internal_def
2551 && !is_loop_header_bb_p (gimple_bb (def_stmt)))))
2553 if (dump_enabled_p ())
2555 dump_printf_loc (MSG_NOTE, vect_location, "swapping oprnds: ");
2556 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, next_stmt, 0);
2559 swap_ssa_operands (next_stmt,
2560 gimple_assign_rhs1_ptr (next_stmt),
2561 gimple_assign_rhs2_ptr (next_stmt));
2562 update_stmt (next_stmt);
2564 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (next_stmt)))
2565 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
2567 else
2568 return false;
2571 lhs = gimple_assign_lhs (next_stmt);
2572 next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
2575 /* Save the chain for further analysis in SLP detection. */
2576 first = GROUP_FIRST_ELEMENT (vinfo_for_stmt (current_stmt));
2577 LOOP_VINFO_REDUCTION_CHAINS (loop_info).safe_push (first);
2578 GROUP_SIZE (vinfo_for_stmt (first)) = size;
2580 return true;
2584 /* Function vect_is_simple_reduction_1
2586 (1) Detect a cross-iteration def-use cycle that represents a simple
2587 reduction computation. We look for the following pattern:
2589 loop_header:
2590 a1 = phi < a0, a2 >
2591 a3 = ...
2592 a2 = operation (a3, a1)
2596 a3 = ...
2597 loop_header:
2598 a1 = phi < a0, a2 >
2599 a2 = operation (a3, a1)
2601 such that:
2602 1. operation is commutative and associative and it is safe to
2603 change the order of the computation (if CHECK_REDUCTION is true)
2604 2. no uses for a2 in the loop (a2 is used out of the loop)
2605 3. no uses of a1 in the loop besides the reduction operation
2606 4. no uses of a1 outside the loop.
2608 Conditions 1,4 are tested here.
2609 Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
2611 (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
2612 nested cycles, if CHECK_REDUCTION is false.
2614 (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
2615 reductions:
2617 a1 = phi < a0, a2 >
2618 inner loop (def of a3)
2619 a2 = phi < a3 >
2621 (4) Detect condition expressions, ie:
2622 for (int i = 0; i < N; i++)
2623 if (a[i] < val)
2624 ret_val = a[i];
2628 static gimple *
2629 vect_is_simple_reduction (loop_vec_info loop_info, gimple *phi,
2630 bool check_reduction, bool *double_reduc,
2631 bool need_wrapping_integral_overflow,
2632 enum vect_reduction_type *v_reduc_type)
2634 struct loop *loop = (gimple_bb (phi))->loop_father;
2635 struct loop *vect_loop = LOOP_VINFO_LOOP (loop_info);
2636 edge latch_e = loop_latch_edge (loop);
2637 tree loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
2638 gimple *def_stmt, *def1 = NULL, *def2 = NULL, *phi_use_stmt = NULL;
2639 enum tree_code orig_code, code;
2640 tree op1, op2, op3 = NULL_TREE, op4 = NULL_TREE;
2641 tree type;
2642 int nloop_uses;
2643 tree name;
2644 imm_use_iterator imm_iter;
2645 use_operand_p use_p;
2646 bool phi_def;
2648 *double_reduc = false;
2649 *v_reduc_type = TREE_CODE_REDUCTION;
2651 /* If CHECK_REDUCTION is true, we assume inner-most loop vectorization,
2652 otherwise, we assume outer loop vectorization. */
2653 gcc_assert ((check_reduction && loop == vect_loop)
2654 || (!check_reduction && flow_loop_nested_p (vect_loop, loop)));
2656 name = PHI_RESULT (phi);
2657 /* ??? If there are no uses of the PHI result the inner loop reduction
2658 won't be detected as possibly double-reduction by vectorizable_reduction
2659 because that tries to walk the PHI arg from the preheader edge which
2660 can be constant. See PR60382. */
2661 if (has_zero_uses (name))
2662 return NULL;
2663 nloop_uses = 0;
2664 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2666 gimple *use_stmt = USE_STMT (use_p);
2667 if (is_gimple_debug (use_stmt))
2668 continue;
2670 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2672 if (dump_enabled_p ())
2673 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2674 "intermediate value used outside loop.\n");
2676 return NULL;
2679 nloop_uses++;
2680 if (nloop_uses > 1)
2682 if (dump_enabled_p ())
2683 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2684 "reduction used in loop.\n");
2685 return NULL;
2688 phi_use_stmt = use_stmt;
2691 if (TREE_CODE (loop_arg) != SSA_NAME)
2693 if (dump_enabled_p ())
2695 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2696 "reduction: not ssa_name: ");
2697 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, loop_arg);
2698 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
2700 return NULL;
2703 def_stmt = SSA_NAME_DEF_STMT (loop_arg);
2704 if (!def_stmt)
2706 if (dump_enabled_p ())
2707 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2708 "reduction: no def_stmt.\n");
2709 return NULL;
2712 if (!is_gimple_assign (def_stmt) && gimple_code (def_stmt) != GIMPLE_PHI)
2714 if (dump_enabled_p ())
2715 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, def_stmt, 0);
2716 return NULL;
2719 if (is_gimple_assign (def_stmt))
2721 name = gimple_assign_lhs (def_stmt);
2722 phi_def = false;
2724 else
2726 name = PHI_RESULT (def_stmt);
2727 phi_def = true;
2730 nloop_uses = 0;
2731 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, name)
2733 gimple *use_stmt = USE_STMT (use_p);
2734 if (is_gimple_debug (use_stmt))
2735 continue;
2736 if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
2737 nloop_uses++;
2738 if (nloop_uses > 1)
2740 if (dump_enabled_p ())
2741 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2742 "reduction used in loop.\n");
2743 return NULL;
2747 /* If DEF_STMT is a phi node itself, we expect it to have a single argument
2748 defined in the inner loop. */
2749 if (phi_def)
2751 op1 = PHI_ARG_DEF (def_stmt, 0);
2753 if (gimple_phi_num_args (def_stmt) != 1
2754 || TREE_CODE (op1) != SSA_NAME)
2756 if (dump_enabled_p ())
2757 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
2758 "unsupported phi node definition.\n");
2760 return NULL;
2763 def1 = SSA_NAME_DEF_STMT (op1);
2764 if (gimple_bb (def1)
2765 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
2766 && loop->inner
2767 && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
2768 && is_gimple_assign (def1)
2769 && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt)))
2771 if (dump_enabled_p ())
2772 report_vect_op (MSG_NOTE, def_stmt,
2773 "detected double reduction: ");
2775 *double_reduc = true;
2776 return def_stmt;
2779 return NULL;
2782 code = orig_code = gimple_assign_rhs_code (def_stmt);
2784 /* We can handle "res -= x[i]", which is non-associative by
2785 simply rewriting this into "res += -x[i]". Avoid changing
2786 gimple instruction for the first simple tests and only do this
2787 if we're allowed to change code at all. */
2788 if (code == MINUS_EXPR
2789 && (op1 = gimple_assign_rhs1 (def_stmt))
2790 && TREE_CODE (op1) == SSA_NAME
2791 && SSA_NAME_DEF_STMT (op1) == phi)
2792 code = PLUS_EXPR;
2794 if (code == COND_EXPR)
2796 if (check_reduction)
2797 *v_reduc_type = COND_REDUCTION;
2799 else if (!commutative_tree_code (code) || !associative_tree_code (code))
2801 if (dump_enabled_p ())
2802 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2803 "reduction: not commutative/associative: ");
2804 return NULL;
2807 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
2809 if (code != COND_EXPR)
2811 if (dump_enabled_p ())
2812 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2813 "reduction: not binary operation: ");
2815 return NULL;
2818 op3 = gimple_assign_rhs1 (def_stmt);
2819 if (COMPARISON_CLASS_P (op3))
2821 op4 = TREE_OPERAND (op3, 1);
2822 op3 = TREE_OPERAND (op3, 0);
2825 op1 = gimple_assign_rhs2 (def_stmt);
2826 op2 = gimple_assign_rhs3 (def_stmt);
2828 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2830 if (dump_enabled_p ())
2831 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2832 "reduction: uses not ssa_names: ");
2834 return NULL;
2837 else
2839 op1 = gimple_assign_rhs1 (def_stmt);
2840 op2 = gimple_assign_rhs2 (def_stmt);
2842 if (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op2) != SSA_NAME)
2844 if (dump_enabled_p ())
2845 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2846 "reduction: uses not ssa_names: ");
2848 return NULL;
2852 type = TREE_TYPE (gimple_assign_lhs (def_stmt));
2853 if ((TREE_CODE (op1) == SSA_NAME
2854 && !types_compatible_p (type,TREE_TYPE (op1)))
2855 || (TREE_CODE (op2) == SSA_NAME
2856 && !types_compatible_p (type, TREE_TYPE (op2)))
2857 || (op3 && TREE_CODE (op3) == SSA_NAME
2858 && !types_compatible_p (type, TREE_TYPE (op3)))
2859 || (op4 && TREE_CODE (op4) == SSA_NAME
2860 && !types_compatible_p (type, TREE_TYPE (op4))))
2862 if (dump_enabled_p ())
2864 dump_printf_loc (MSG_NOTE, vect_location,
2865 "reduction: multiple types: operation type: ");
2866 dump_generic_expr (MSG_NOTE, TDF_SLIM, type);
2867 dump_printf (MSG_NOTE, ", operands types: ");
2868 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2869 TREE_TYPE (op1));
2870 dump_printf (MSG_NOTE, ",");
2871 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2872 TREE_TYPE (op2));
2873 if (op3)
2875 dump_printf (MSG_NOTE, ",");
2876 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2877 TREE_TYPE (op3));
2880 if (op4)
2882 dump_printf (MSG_NOTE, ",");
2883 dump_generic_expr (MSG_NOTE, TDF_SLIM,
2884 TREE_TYPE (op4));
2886 dump_printf (MSG_NOTE, "\n");
2889 return NULL;
2892 /* Check that it's ok to change the order of the computation.
2893 Generally, when vectorizing a reduction we change the order of the
2894 computation. This may change the behavior of the program in some
2895 cases, so we need to check that this is ok. One exception is when
2896 vectorizing an outer-loop: the inner-loop is executed sequentially,
2897 and therefore vectorizing reductions in the inner-loop during
2898 outer-loop vectorization is safe. */
2900 if (*v_reduc_type != COND_REDUCTION
2901 && check_reduction)
2903 /* CHECKME: check for !flag_finite_math_only too? */
2904 if (SCALAR_FLOAT_TYPE_P (type) && !flag_associative_math)
2906 /* Changing the order of operations changes the semantics. */
2907 if (dump_enabled_p ())
2908 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2909 "reduction: unsafe fp math optimization: ");
2910 return NULL;
2912 else if (INTEGRAL_TYPE_P (type))
2914 if (!operation_no_trapping_overflow (type, code))
2916 /* Changing the order of operations changes the semantics. */
2917 if (dump_enabled_p ())
2918 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2919 "reduction: unsafe int math optimization"
2920 " (overflow traps): ");
2921 return NULL;
2923 if (need_wrapping_integral_overflow
2924 && !TYPE_OVERFLOW_WRAPS (type)
2925 && operation_can_overflow (code))
2927 /* Changing the order of operations changes the semantics. */
2928 if (dump_enabled_p ())
2929 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2930 "reduction: unsafe int math optimization"
2931 " (overflow doesn't wrap): ");
2932 return NULL;
2935 else if (SAT_FIXED_POINT_TYPE_P (type))
2937 /* Changing the order of operations changes the semantics. */
2938 if (dump_enabled_p ())
2939 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
2940 "reduction: unsafe fixed-point math optimization: ");
2941 return NULL;
2945 /* Reduction is safe. We're dealing with one of the following:
2946 1) integer arithmetic and no trapv
2947 2) floating point arithmetic, and special flags permit this optimization
2948 3) nested cycle (i.e., outer loop vectorization). */
2949 if (TREE_CODE (op1) == SSA_NAME)
2950 def1 = SSA_NAME_DEF_STMT (op1);
2952 if (TREE_CODE (op2) == SSA_NAME)
2953 def2 = SSA_NAME_DEF_STMT (op2);
2955 if (code != COND_EXPR
2956 && ((!def1 || gimple_nop_p (def1)) && (!def2 || gimple_nop_p (def2))))
2958 if (dump_enabled_p ())
2959 report_vect_op (MSG_NOTE, def_stmt, "reduction: no defs for operands: ");
2960 return NULL;
2963 /* Check that one def is the reduction def, defined by PHI,
2964 the other def is either defined in the loop ("vect_internal_def"),
2965 or it's an induction (defined by a loop-header phi-node). */
2967 if (def2 && def2 == phi
2968 && (code == COND_EXPR
2969 || !def1 || gimple_nop_p (def1)
2970 || !flow_bb_inside_loop_p (loop, gimple_bb (def1))
2971 || (def1 && flow_bb_inside_loop_p (loop, gimple_bb (def1))
2972 && (is_gimple_assign (def1)
2973 || is_gimple_call (def1)
2974 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2975 == vect_induction_def
2976 || (gimple_code (def1) == GIMPLE_PHI
2977 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def1))
2978 == vect_internal_def
2979 && !is_loop_header_bb_p (gimple_bb (def1)))))))
2981 if (dump_enabled_p ())
2982 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
2983 return def_stmt;
2986 if (def1 && def1 == phi
2987 && (code == COND_EXPR
2988 || !def2 || gimple_nop_p (def2)
2989 || !flow_bb_inside_loop_p (loop, gimple_bb (def2))
2990 || (def2 && flow_bb_inside_loop_p (loop, gimple_bb (def2))
2991 && (is_gimple_assign (def2)
2992 || is_gimple_call (def2)
2993 || STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
2994 == vect_induction_def
2995 || (gimple_code (def2) == GIMPLE_PHI
2996 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def2))
2997 == vect_internal_def
2998 && !is_loop_header_bb_p (gimple_bb (def2)))))))
3000 if (check_reduction
3001 && orig_code != MINUS_EXPR)
3003 if (code == COND_EXPR)
3005 /* No current known use where this case would be useful. */
3006 if (dump_enabled_p ())
3007 report_vect_op (MSG_NOTE, def_stmt,
3008 "detected reduction: cannot currently swap "
3009 "operands for cond_expr");
3010 return NULL;
3013 /* Swap operands (just for simplicity - so that the rest of the code
3014 can assume that the reduction variable is always the last (second)
3015 argument). */
3016 if (dump_enabled_p ())
3017 report_vect_op (MSG_NOTE, def_stmt,
3018 "detected reduction: need to swap operands: ");
3020 swap_ssa_operands (def_stmt, gimple_assign_rhs1_ptr (def_stmt),
3021 gimple_assign_rhs2_ptr (def_stmt));
3023 if (CONSTANT_CLASS_P (gimple_assign_rhs1 (def_stmt)))
3024 LOOP_VINFO_OPERANDS_SWAPPED (loop_info) = true;
3026 else
3028 if (dump_enabled_p ())
3029 report_vect_op (MSG_NOTE, def_stmt, "detected reduction: ");
3032 return def_stmt;
3035 /* Try to find SLP reduction chain. */
3036 if (check_reduction && code != COND_EXPR
3037 && vect_is_slp_reduction (loop_info, phi, def_stmt))
3039 if (dump_enabled_p ())
3040 report_vect_op (MSG_NOTE, def_stmt,
3041 "reduction: detected reduction chain: ");
3043 return def_stmt;
3046 if (dump_enabled_p ())
3047 report_vect_op (MSG_MISSED_OPTIMIZATION, def_stmt,
3048 "reduction: unknown pattern: ");
3050 return NULL;
3053 /* Wrapper around vect_is_simple_reduction_1, which will modify code
3054 in-place if it enables detection of more reductions. Arguments
3055 as there. */
3057 gimple *
3058 vect_force_simple_reduction (loop_vec_info loop_info, gimple *phi,
3059 bool check_reduction, bool *double_reduc,
3060 bool need_wrapping_integral_overflow)
3062 enum vect_reduction_type v_reduc_type;
3063 return vect_is_simple_reduction (loop_info, phi, check_reduction,
3064 double_reduc,
3065 need_wrapping_integral_overflow,
3066 &v_reduc_type);
3069 /* Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times. */
3071 vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue,
3072 int *peel_iters_epilogue,
3073 stmt_vector_for_cost *scalar_cost_vec,
3074 stmt_vector_for_cost *prologue_cost_vec,
3075 stmt_vector_for_cost *epilogue_cost_vec)
3077 int retval = 0;
3078 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3080 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
3082 *peel_iters_epilogue = vf/2;
3083 if (dump_enabled_p ())
3084 dump_printf_loc (MSG_NOTE, vect_location,
3085 "cost model: epilogue peel iters set to vf/2 "
3086 "because loop iterations are unknown .\n");
3088 /* If peeled iterations are known but number of scalar loop
3089 iterations are unknown, count a taken branch per peeled loop. */
3090 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3091 NULL, 0, vect_prologue);
3092 retval = record_stmt_cost (prologue_cost_vec, 1, cond_branch_taken,
3093 NULL, 0, vect_epilogue);
3095 else
3097 int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
3098 peel_iters_prologue = niters < peel_iters_prologue ?
3099 niters : peel_iters_prologue;
3100 *peel_iters_epilogue = (niters - peel_iters_prologue) % vf;
3101 /* If we need to peel for gaps, but no peeling is required, we have to
3102 peel VF iterations. */
3103 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !*peel_iters_epilogue)
3104 *peel_iters_epilogue = vf;
3107 stmt_info_for_cost *si;
3108 int j;
3109 if (peel_iters_prologue)
3110 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3111 retval += record_stmt_cost (prologue_cost_vec,
3112 si->count * peel_iters_prologue,
3113 si->kind, NULL, si->misalign,
3114 vect_prologue);
3115 if (*peel_iters_epilogue)
3116 FOR_EACH_VEC_ELT (*scalar_cost_vec, j, si)
3117 retval += record_stmt_cost (epilogue_cost_vec,
3118 si->count * *peel_iters_epilogue,
3119 si->kind, NULL, si->misalign,
3120 vect_epilogue);
3122 return retval;
3125 /* Function vect_estimate_min_profitable_iters
3127 Return the number of iterations required for the vector version of the
3128 loop to be profitable relative to the cost of the scalar version of the
3129 loop.
3131 *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
3132 of iterations for vectorization. -1 value means loop vectorization
3133 is not profitable. This returned value may be used for dynamic
3134 profitability check.
3136 *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
3137 for static check against estimated number of iterations. */
3139 static void
3140 vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
3141 int *ret_min_profitable_niters,
3142 int *ret_min_profitable_estimate)
3144 int min_profitable_iters;
3145 int min_profitable_estimate;
3146 int peel_iters_prologue;
3147 int peel_iters_epilogue;
3148 unsigned vec_inside_cost = 0;
3149 int vec_outside_cost = 0;
3150 unsigned vec_prologue_cost = 0;
3151 unsigned vec_epilogue_cost = 0;
3152 int scalar_single_iter_cost = 0;
3153 int scalar_outside_cost = 0;
3154 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3155 int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
3156 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3158 /* Cost model disabled. */
3159 if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
3161 dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
3162 *ret_min_profitable_niters = 0;
3163 *ret_min_profitable_estimate = 0;
3164 return;
3167 /* Requires loop versioning tests to handle misalignment. */
3168 if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
3170 /* FIXME: Make cost depend on complexity of individual check. */
3171 unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
3172 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3173 vect_prologue);
3174 dump_printf (MSG_NOTE,
3175 "cost model: Adding cost of checks for loop "
3176 "versioning to treat misalignment.\n");
3179 /* Requires loop versioning with alias checks. */
3180 if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
3182 /* FIXME: Make cost depend on complexity of individual check. */
3183 unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
3184 (void) add_stmt_cost (target_cost_data, len, vector_stmt, NULL, 0,
3185 vect_prologue);
3186 dump_printf (MSG_NOTE,
3187 "cost model: Adding cost of checks for loop "
3188 "versioning aliasing.\n");
3191 /* Requires loop versioning with niter checks. */
3192 if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
3194 /* FIXME: Make cost depend on complexity of individual check. */
3195 (void) add_stmt_cost (target_cost_data, 1, vector_stmt, NULL, 0,
3196 vect_prologue);
3197 dump_printf (MSG_NOTE,
3198 "cost model: Adding cost of checks for loop "
3199 "versioning niters.\n");
3202 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3203 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken, NULL, 0,
3204 vect_prologue);
3206 /* Count statements in scalar loop. Using this as scalar cost for a single
3207 iteration for now.
3209 TODO: Add outer loop support.
3211 TODO: Consider assigning different costs to different scalar
3212 statements. */
3214 scalar_single_iter_cost
3215 = LOOP_VINFO_SINGLE_SCALAR_ITERATION_COST (loop_vinfo);
3217 /* Add additional cost for the peeled instructions in prologue and epilogue
3218 loop.
3220 FORNOW: If we don't know the value of peel_iters for prologue or epilogue
3221 at compile-time - we assume it's vf/2 (the worst would be vf-1).
3223 TODO: Build an expression that represents peel_iters for prologue and
3224 epilogue to be used in a run-time test. */
3226 if (npeel < 0)
3228 peel_iters_prologue = vf/2;
3229 dump_printf (MSG_NOTE, "cost model: "
3230 "prologue peel iters set to vf/2.\n");
3232 /* If peeling for alignment is unknown, loop bound of main loop becomes
3233 unknown. */
3234 peel_iters_epilogue = vf/2;
3235 dump_printf (MSG_NOTE, "cost model: "
3236 "epilogue peel iters set to vf/2 because "
3237 "peeling for alignment is unknown.\n");
3239 /* If peeled iterations are unknown, count a taken branch and a not taken
3240 branch per peeled loop. Even if scalar loop iterations are known,
3241 vector iterations are not known since peeled prologue iterations are
3242 not known. Hence guards remain the same. */
3243 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3244 NULL, 0, vect_prologue);
3245 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3246 NULL, 0, vect_prologue);
3247 (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
3248 NULL, 0, vect_epilogue);
3249 (void) add_stmt_cost (target_cost_data, 1, cond_branch_not_taken,
3250 NULL, 0, vect_epilogue);
3251 stmt_info_for_cost *si;
3252 int j;
3253 FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
3255 struct _stmt_vec_info *stmt_info
3256 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3257 (void) add_stmt_cost (target_cost_data,
3258 si->count * peel_iters_prologue,
3259 si->kind, stmt_info, si->misalign,
3260 vect_prologue);
3261 (void) add_stmt_cost (target_cost_data,
3262 si->count * peel_iters_epilogue,
3263 si->kind, stmt_info, si->misalign,
3264 vect_epilogue);
3267 else
3269 stmt_vector_for_cost prologue_cost_vec, epilogue_cost_vec;
3270 stmt_info_for_cost *si;
3271 int j;
3272 void *data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3274 prologue_cost_vec.create (2);
3275 epilogue_cost_vec.create (2);
3276 peel_iters_prologue = npeel;
3278 (void) vect_get_known_peeling_cost (loop_vinfo, peel_iters_prologue,
3279 &peel_iters_epilogue,
3280 &LOOP_VINFO_SCALAR_ITERATION_COST
3281 (loop_vinfo),
3282 &prologue_cost_vec,
3283 &epilogue_cost_vec);
3285 FOR_EACH_VEC_ELT (prologue_cost_vec, j, si)
3287 struct _stmt_vec_info *stmt_info
3288 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3289 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3290 si->misalign, vect_prologue);
3293 FOR_EACH_VEC_ELT (epilogue_cost_vec, j, si)
3295 struct _stmt_vec_info *stmt_info
3296 = si->stmt ? vinfo_for_stmt (si->stmt) : NULL;
3297 (void) add_stmt_cost (data, si->count, si->kind, stmt_info,
3298 si->misalign, vect_epilogue);
3301 prologue_cost_vec.release ();
3302 epilogue_cost_vec.release ();
3305 /* FORNOW: The scalar outside cost is incremented in one of the
3306 following ways:
3308 1. The vectorizer checks for alignment and aliasing and generates
3309 a condition that allows dynamic vectorization. A cost model
3310 check is ANDED with the versioning condition. Hence scalar code
3311 path now has the added cost of the versioning check.
3313 if (cost > th & versioning_check)
3314 jmp to vector code
3316 Hence run-time scalar is incremented by not-taken branch cost.
3318 2. The vectorizer then checks if a prologue is required. If the
3319 cost model check was not done before during versioning, it has to
3320 be done before the prologue check.
3322 if (cost <= th)
3323 prologue = scalar_iters
3324 if (prologue == 0)
3325 jmp to vector code
3326 else
3327 execute prologue
3328 if (prologue == num_iters)
3329 go to exit
3331 Hence the run-time scalar cost is incremented by a taken branch,
3332 plus a not-taken branch, plus a taken branch cost.
3334 3. The vectorizer then checks if an epilogue is required. If the
3335 cost model check was not done before during prologue check, it
3336 has to be done with the epilogue check.
3338 if (prologue == 0)
3339 jmp to vector code
3340 else
3341 execute prologue
3342 if (prologue == num_iters)
3343 go to exit
3344 vector code:
3345 if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
3346 jmp to epilogue
3348 Hence the run-time scalar cost should be incremented by 2 taken
3349 branches.
3351 TODO: The back end may reorder the BBS's differently and reverse
3352 conditions/branch directions. Change the estimates below to
3353 something more reasonable. */
3355 /* If the number of iterations is known and we do not do versioning, we can
3356 decide whether to vectorize at compile time. Hence the scalar version
3357 do not carry cost model guard costs. */
3358 if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
3359 || LOOP_REQUIRES_VERSIONING (loop_vinfo))
3361 /* Cost model check occurs at versioning. */
3362 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
3363 scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
3364 else
3366 /* Cost model check occurs at prologue generation. */
3367 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
3368 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
3369 + vect_get_stmt_cost (cond_branch_not_taken);
3370 /* Cost model check occurs at epilogue generation. */
3371 else
3372 scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
3376 /* Complete the target-specific cost calculations. */
3377 finish_cost (LOOP_VINFO_TARGET_COST_DATA (loop_vinfo), &vec_prologue_cost,
3378 &vec_inside_cost, &vec_epilogue_cost);
3380 vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
3382 if (dump_enabled_p ())
3384 dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
3385 dump_printf (MSG_NOTE, " Vector inside of loop cost: %d\n",
3386 vec_inside_cost);
3387 dump_printf (MSG_NOTE, " Vector prologue cost: %d\n",
3388 vec_prologue_cost);
3389 dump_printf (MSG_NOTE, " Vector epilogue cost: %d\n",
3390 vec_epilogue_cost);
3391 dump_printf (MSG_NOTE, " Scalar iteration cost: %d\n",
3392 scalar_single_iter_cost);
3393 dump_printf (MSG_NOTE, " Scalar outside cost: %d\n",
3394 scalar_outside_cost);
3395 dump_printf (MSG_NOTE, " Vector outside cost: %d\n",
3396 vec_outside_cost);
3397 dump_printf (MSG_NOTE, " prologue iterations: %d\n",
3398 peel_iters_prologue);
3399 dump_printf (MSG_NOTE, " epilogue iterations: %d\n",
3400 peel_iters_epilogue);
3403 /* Calculate number of iterations required to make the vector version
3404 profitable, relative to the loop bodies only. The following condition
3405 must hold true:
3406 SIC * niters + SOC > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC
3407 where
3408 SIC = scalar iteration cost, VIC = vector iteration cost,
3409 VOC = vector outside cost, VF = vectorization factor,
3410 PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations
3411 SOC = scalar outside cost for run time cost model check. */
3413 if ((scalar_single_iter_cost * vf) > (int) vec_inside_cost)
3415 if (vec_outside_cost <= 0)
3416 min_profitable_iters = 1;
3417 else
3419 min_profitable_iters = ((vec_outside_cost - scalar_outside_cost) * vf
3420 - vec_inside_cost * peel_iters_prologue
3421 - vec_inside_cost * peel_iters_epilogue)
3422 / ((scalar_single_iter_cost * vf)
3423 - vec_inside_cost);
3425 if ((scalar_single_iter_cost * vf * min_profitable_iters)
3426 <= (((int) vec_inside_cost * min_profitable_iters)
3427 + (((int) vec_outside_cost - scalar_outside_cost) * vf)))
3428 min_profitable_iters++;
3431 /* vector version will never be profitable. */
3432 else
3434 if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
3435 warning_at (vect_location, OPT_Wopenmp_simd, "vectorization "
3436 "did not happen for a simd loop");
3438 if (dump_enabled_p ())
3439 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3440 "cost model: the vector iteration cost = %d "
3441 "divided by the scalar iteration cost = %d "
3442 "is greater or equal to the vectorization factor = %d"
3443 ".\n",
3444 vec_inside_cost, scalar_single_iter_cost, vf);
3445 *ret_min_profitable_niters = -1;
3446 *ret_min_profitable_estimate = -1;
3447 return;
3450 dump_printf (MSG_NOTE,
3451 " Calculated minimum iters for profitability: %d\n",
3452 min_profitable_iters);
3454 min_profitable_iters =
3455 min_profitable_iters < vf ? vf : min_profitable_iters;
3457 /* Because the condition we create is:
3458 if (niters <= min_profitable_iters)
3459 then skip the vectorized loop. */
3460 min_profitable_iters--;
3462 if (dump_enabled_p ())
3463 dump_printf_loc (MSG_NOTE, vect_location,
3464 " Runtime profitability threshold = %d\n",
3465 min_profitable_iters);
3467 *ret_min_profitable_niters = min_profitable_iters;
3469 /* Calculate number of iterations required to make the vector version
3470 profitable, relative to the loop bodies only.
3472 Non-vectorized variant is SIC * niters and it must win over vector
3473 variant on the expected loop trip count. The following condition must hold true:
3474 SIC * niters > VIC * ((niters-PL_ITERS-EP_ITERS)/VF) + VOC + SOC */
3476 if (vec_outside_cost <= 0)
3477 min_profitable_estimate = 1;
3478 else
3480 min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost) * vf
3481 - vec_inside_cost * peel_iters_prologue
3482 - vec_inside_cost * peel_iters_epilogue)
3483 / ((scalar_single_iter_cost * vf)
3484 - vec_inside_cost);
3486 min_profitable_estimate --;
3487 min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
3488 if (dump_enabled_p ())
3489 dump_printf_loc (MSG_NOTE, vect_location,
3490 " Static estimate profitability threshold = %d\n",
3491 min_profitable_estimate);
3493 *ret_min_profitable_estimate = min_profitable_estimate;
3496 /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
3497 vector elements (not bits) for a vector of mode MODE. */
3498 static void
3499 calc_vec_perm_mask_for_shift (enum machine_mode mode, unsigned int offset,
3500 unsigned char *sel)
3502 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3504 for (i = 0; i < nelt; i++)
3505 sel[i] = (i + offset) & (2*nelt - 1);
3508 /* Checks whether the target supports whole-vector shifts for vectors of mode
3509 MODE. This is the case if _either_ the platform handles vec_shr_optab, _or_
3510 it supports vec_perm_const with masks for all necessary shift amounts. */
3511 static bool
3512 have_whole_vector_shift (enum machine_mode mode)
3514 if (optab_handler (vec_shr_optab, mode) != CODE_FOR_nothing)
3515 return true;
3517 if (direct_optab_handler (vec_perm_const_optab, mode) == CODE_FOR_nothing)
3518 return false;
3520 unsigned int i, nelt = GET_MODE_NUNITS (mode);
3521 unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
3523 for (i = nelt/2; i >= 1; i/=2)
3525 calc_vec_perm_mask_for_shift (mode, i, sel);
3526 if (!can_vec_perm_p (mode, false, sel))
3527 return false;
3529 return true;
3532 /* Return the reduction operand (with index REDUC_INDEX) of STMT. */
3534 static tree
3535 get_reduction_op (gimple *stmt, int reduc_index)
3537 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
3539 case GIMPLE_SINGLE_RHS:
3540 gcc_assert (TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt))
3541 == ternary_op);
3542 return TREE_OPERAND (gimple_assign_rhs1 (stmt), reduc_index);
3543 case GIMPLE_UNARY_RHS:
3544 return gimple_assign_rhs1 (stmt);
3545 case GIMPLE_BINARY_RHS:
3546 return (reduc_index
3547 ? gimple_assign_rhs2 (stmt) : gimple_assign_rhs1 (stmt));
3548 case GIMPLE_TERNARY_RHS:
3549 return gimple_op (stmt, reduc_index + 1);
3550 default:
3551 gcc_unreachable ();
3555 /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
3556 functions. Design better to avoid maintenance issues. */
3558 /* Function vect_model_reduction_cost.
3560 Models cost for a reduction operation, including the vector ops
3561 generated within the strip-mine loop, the initial definition before
3562 the loop, and the epilogue code that must be generated. */
3564 static bool
3565 vect_model_reduction_cost (stmt_vec_info stmt_info, enum tree_code reduc_code,
3566 int ncopies, int reduc_index)
3568 int prologue_cost = 0, epilogue_cost = 0;
3569 enum tree_code code;
3570 optab optab;
3571 tree vectype;
3572 gimple *stmt, *orig_stmt;
3573 tree reduction_op;
3574 machine_mode mode;
3575 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3576 struct loop *loop = NULL;
3577 void *target_cost_data;
3579 if (loop_vinfo)
3581 loop = LOOP_VINFO_LOOP (loop_vinfo);
3582 target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3584 else
3585 target_cost_data = BB_VINFO_TARGET_COST_DATA (STMT_VINFO_BB_VINFO (stmt_info));
3587 /* Condition reductions generate two reductions in the loop. */
3588 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3589 ncopies *= 2;
3591 /* Cost of reduction op inside loop. */
3592 unsigned inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3593 stmt_info, 0, vect_body);
3594 stmt = STMT_VINFO_STMT (stmt_info);
3596 reduction_op = get_reduction_op (stmt, reduc_index);
3598 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
3599 if (!vectype)
3601 if (dump_enabled_p ())
3603 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
3604 "unsupported data-type ");
3605 dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
3606 TREE_TYPE (reduction_op));
3607 dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
3609 return false;
3612 mode = TYPE_MODE (vectype);
3613 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
3615 if (!orig_stmt)
3616 orig_stmt = STMT_VINFO_STMT (stmt_info);
3618 code = gimple_assign_rhs_code (orig_stmt);
3620 /* Add in cost for initial definition.
3621 For cond reduction we have four vectors: initial index, step, initial
3622 result of the data reduction, initial value of the index reduction. */
3623 int prologue_stmts = STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
3624 == COND_REDUCTION ? 4 : 1;
3625 prologue_cost += add_stmt_cost (target_cost_data, prologue_stmts,
3626 scalar_to_vec, stmt_info, 0,
3627 vect_prologue);
3629 /* Determine cost of epilogue code.
3631 We have a reduction operator that will reduce the vector in one statement.
3632 Also requires scalar extract. */
3634 if (!loop || !nested_in_vect_loop_p (loop, orig_stmt))
3636 if (reduc_code != ERROR_MARK)
3638 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
3640 /* An EQ stmt and an COND_EXPR stmt. */
3641 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3642 vector_stmt, stmt_info, 0,
3643 vect_epilogue);
3644 /* Reduction of the max index and a reduction of the found
3645 values. */
3646 epilogue_cost += add_stmt_cost (target_cost_data, 2,
3647 vec_to_scalar, stmt_info, 0,
3648 vect_epilogue);
3649 /* A broadcast of the max value. */
3650 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3651 scalar_to_vec, stmt_info, 0,
3652 vect_epilogue);
3654 else
3656 epilogue_cost += add_stmt_cost (target_cost_data, 1, vector_stmt,
3657 stmt_info, 0, vect_epilogue);
3658 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3659 vec_to_scalar, stmt_info, 0,
3660 vect_epilogue);
3663 else
3665 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
3666 tree bitsize =
3667 TYPE_SIZE (TREE_TYPE (gimple_assign_lhs (orig_stmt)));
3668 int element_bitsize = tree_to_uhwi (bitsize);
3669 int nelements = vec_size_in_bits / element_bitsize;
3671 optab = optab_for_tree_code (code, vectype, optab_default);
3673 /* We have a whole vector shift available. */
3674 if (VECTOR_MODE_P (mode)
3675 && optab_handler (optab, mode) != CODE_FOR_nothing
3676 && have_whole_vector_shift (mode))
3678 /* Final reduction via vector shifts and the reduction operator.
3679 Also requires scalar extract. */
3680 epilogue_cost += add_stmt_cost (target_cost_data,
3681 exact_log2 (nelements) * 2,
3682 vector_stmt, stmt_info, 0,
3683 vect_epilogue);
3684 epilogue_cost += add_stmt_cost (target_cost_data, 1,
3685 vec_to_scalar, stmt_info, 0,
3686 vect_epilogue);
3688 else
3689 /* Use extracts and reduction op for final reduction. For N
3690 elements, we have N extracts and N-1 reduction ops. */
3691 epilogue_cost += add_stmt_cost (target_cost_data,
3692 nelements + nelements - 1,
3693 vector_stmt, stmt_info, 0,
3694 vect_epilogue);
3698 if (dump_enabled_p ())
3699 dump_printf (MSG_NOTE,
3700 "vect_model_reduction_cost: inside_cost = %d, "
3701 "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
3702 prologue_cost, epilogue_cost);
3704 return true;
3708 /* Function vect_model_induction_cost.
3710 Models cost for induction operations. */
3712 static void
3713 vect_model_induction_cost (stmt_vec_info stmt_info, int ncopies)
3715 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
3716 void *target_cost_data = LOOP_VINFO_TARGET_COST_DATA (loop_vinfo);
3717 unsigned inside_cost, prologue_cost;
3719 /* loop cost for vec_loop. */
3720 inside_cost = add_stmt_cost (target_cost_data, ncopies, vector_stmt,
3721 stmt_info, 0, vect_body);
3723 /* prologue cost for vec_init and vec_step. */
3724 prologue_cost = add_stmt_cost (target_cost_data, 2, scalar_to_vec,
3725 stmt_info, 0, vect_prologue);
3727 if (dump_enabled_p ())
3728 dump_printf_loc (MSG_NOTE, vect_location,
3729 "vect_model_induction_cost: inside_cost = %d, "
3730 "prologue_cost = %d .\n", inside_cost, prologue_cost);
3734 /* Function get_initial_def_for_induction
3736 Input:
3737 STMT - a stmt that performs an induction operation in the loop.
3738 IV_PHI - the initial value of the induction variable
3740 Output:
3741 Return a vector variable, initialized with the first VF values of
3742 the induction variable. E.g., for an iv with IV_PHI='X' and
3743 evolution S, for a vector of 4 units, we want to return:
3744 [X, X + S, X + 2*S, X + 3*S]. */
3746 static tree
3747 get_initial_def_for_induction (gimple *iv_phi)
3749 stmt_vec_info stmt_vinfo = vinfo_for_stmt (iv_phi);
3750 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
3751 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
3752 tree vectype;
3753 int nunits;
3754 edge pe = loop_preheader_edge (loop);
3755 struct loop *iv_loop;
3756 basic_block new_bb;
3757 tree new_vec, vec_init, vec_step, t;
3758 tree new_name;
3759 gimple *new_stmt;
3760 gphi *induction_phi;
3761 tree induc_def, vec_def, vec_dest;
3762 tree init_expr, step_expr;
3763 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
3764 int i;
3765 int ncopies;
3766 tree expr;
3767 stmt_vec_info phi_info = vinfo_for_stmt (iv_phi);
3768 bool nested_in_vect_loop = false;
3769 gimple_seq stmts;
3770 imm_use_iterator imm_iter;
3771 use_operand_p use_p;
3772 gimple *exit_phi;
3773 edge latch_e;
3774 tree loop_arg;
3775 gimple_stmt_iterator si;
3776 basic_block bb = gimple_bb (iv_phi);
3777 tree stepvectype;
3778 tree resvectype;
3780 /* Is phi in an inner-loop, while vectorizing an enclosing outer-loop? */
3781 if (nested_in_vect_loop_p (loop, iv_phi))
3783 nested_in_vect_loop = true;
3784 iv_loop = loop->inner;
3786 else
3787 iv_loop = loop;
3788 gcc_assert (iv_loop == (gimple_bb (iv_phi))->loop_father);
3790 latch_e = loop_latch_edge (iv_loop);
3791 loop_arg = PHI_ARG_DEF_FROM_EDGE (iv_phi, latch_e);
3793 step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
3794 gcc_assert (step_expr != NULL_TREE);
3796 pe = loop_preheader_edge (iv_loop);
3797 init_expr = PHI_ARG_DEF_FROM_EDGE (iv_phi,
3798 loop_preheader_edge (iv_loop));
3800 vectype = get_vectype_for_scalar_type (TREE_TYPE (init_expr));
3801 resvectype = get_vectype_for_scalar_type (TREE_TYPE (PHI_RESULT (iv_phi)));
3802 gcc_assert (vectype);
3803 nunits = TYPE_VECTOR_SUBPARTS (vectype);
3804 ncopies = vf / nunits;
3806 gcc_assert (phi_info);
3807 gcc_assert (ncopies >= 1);
3809 /* Convert the step to the desired type. */
3810 stmts = NULL;
3811 step_expr = gimple_convert (&stmts, TREE_TYPE (vectype), step_expr);
3812 if (stmts)
3814 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3815 gcc_assert (!new_bb);
3818 /* Find the first insertion point in the BB. */
3819 si = gsi_after_labels (bb);
3821 /* Create the vector that holds the initial_value of the induction. */
3822 if (nested_in_vect_loop)
3824 /* iv_loop is nested in the loop to be vectorized. init_expr had already
3825 been created during vectorization of previous stmts. We obtain it
3826 from the STMT_VINFO_VEC_STMT of the defining stmt. */
3827 vec_init = vect_get_vec_def_for_operand (init_expr, iv_phi);
3828 /* If the initial value is not of proper type, convert it. */
3829 if (!useless_type_conversion_p (vectype, TREE_TYPE (vec_init)))
3831 new_stmt
3832 = gimple_build_assign (vect_get_new_ssa_name (vectype,
3833 vect_simple_var,
3834 "vec_iv_"),
3835 VIEW_CONVERT_EXPR,
3836 build1 (VIEW_CONVERT_EXPR, vectype,
3837 vec_init));
3838 vec_init = gimple_assign_lhs (new_stmt);
3839 new_bb = gsi_insert_on_edge_immediate (loop_preheader_edge (iv_loop),
3840 new_stmt);
3841 gcc_assert (!new_bb);
3842 set_vinfo_for_stmt (new_stmt,
3843 new_stmt_vec_info (new_stmt, loop_vinfo));
3846 else
3848 vec<constructor_elt, va_gc> *v;
3850 /* iv_loop is the loop to be vectorized. Create:
3851 vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr) */
3852 stmts = NULL;
3853 new_name = gimple_convert (&stmts, TREE_TYPE (vectype), init_expr);
3855 vec_alloc (v, nunits);
3856 bool constant_p = is_gimple_min_invariant (new_name);
3857 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3858 for (i = 1; i < nunits; i++)
3860 /* Create: new_name_i = new_name + step_expr */
3861 new_name = gimple_build (&stmts, PLUS_EXPR, TREE_TYPE (new_name),
3862 new_name, step_expr);
3863 if (!is_gimple_min_invariant (new_name))
3864 constant_p = false;
3865 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, new_name);
3867 if (stmts)
3869 new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
3870 gcc_assert (!new_bb);
3873 /* Create a vector from [new_name_0, new_name_1, ..., new_name_nunits-1] */
3874 if (constant_p)
3875 new_vec = build_vector_from_ctor (vectype, v);
3876 else
3877 new_vec = build_constructor (vectype, v);
3878 vec_init = vect_init_vector (iv_phi, new_vec, vectype, NULL);
3882 /* Create the vector that holds the step of the induction. */
3883 if (nested_in_vect_loop)
3884 /* iv_loop is nested in the loop to be vectorized. Generate:
3885 vec_step = [S, S, S, S] */
3886 new_name = step_expr;
3887 else
3889 /* iv_loop is the loop to be vectorized. Generate:
3890 vec_step = [VF*S, VF*S, VF*S, VF*S] */
3891 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3893 expr = build_int_cst (integer_type_node, vf);
3894 expr = fold_convert (TREE_TYPE (step_expr), expr);
3896 else
3897 expr = build_int_cst (TREE_TYPE (step_expr), vf);
3898 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3899 expr, step_expr);
3900 if (TREE_CODE (step_expr) == SSA_NAME)
3901 new_name = vect_init_vector (iv_phi, new_name,
3902 TREE_TYPE (step_expr), NULL);
3905 t = unshare_expr (new_name);
3906 gcc_assert (CONSTANT_CLASS_P (new_name)
3907 || TREE_CODE (new_name) == SSA_NAME);
3908 stepvectype = get_vectype_for_scalar_type (TREE_TYPE (new_name));
3909 gcc_assert (stepvectype);
3910 new_vec = build_vector_from_val (stepvectype, t);
3911 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3914 /* Create the following def-use cycle:
3915 loop prolog:
3916 vec_init = ...
3917 vec_step = ...
3918 loop:
3919 vec_iv = PHI <vec_init, vec_loop>
3921 STMT
3923 vec_loop = vec_iv + vec_step; */
3925 /* Create the induction-phi that defines the induction-operand. */
3926 vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
3927 induction_phi = create_phi_node (vec_dest, iv_loop->header);
3928 set_vinfo_for_stmt (induction_phi,
3929 new_stmt_vec_info (induction_phi, loop_vinfo));
3930 induc_def = PHI_RESULT (induction_phi);
3932 /* Create the iv update inside the loop */
3933 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR, induc_def, vec_step);
3934 vec_def = make_ssa_name (vec_dest, new_stmt);
3935 gimple_assign_set_lhs (new_stmt, vec_def);
3936 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3937 set_vinfo_for_stmt (new_stmt, new_stmt_vec_info (new_stmt, loop_vinfo));
3939 /* Set the arguments of the phi node: */
3940 add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
3941 add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
3942 UNKNOWN_LOCATION);
3945 /* In case that vectorization factor (VF) is bigger than the number
3946 of elements that we can fit in a vectype (nunits), we have to generate
3947 more than one vector stmt - i.e - we need to "unroll" the
3948 vector stmt by a factor VF/nunits. For more details see documentation
3949 in vectorizable_operation. */
3951 if (ncopies > 1)
3953 stmt_vec_info prev_stmt_vinfo;
3954 /* FORNOW. This restriction should be relaxed. */
3955 gcc_assert (!nested_in_vect_loop);
3957 /* Create the vector that holds the step of the induction. */
3958 if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr)))
3960 expr = build_int_cst (integer_type_node, nunits);
3961 expr = fold_convert (TREE_TYPE (step_expr), expr);
3963 else
3964 expr = build_int_cst (TREE_TYPE (step_expr), nunits);
3965 new_name = fold_build2 (MULT_EXPR, TREE_TYPE (step_expr),
3966 expr, step_expr);
3967 if (TREE_CODE (step_expr) == SSA_NAME)
3968 new_name = vect_init_vector (iv_phi, new_name,
3969 TREE_TYPE (step_expr), NULL);
3970 t = unshare_expr (new_name);
3971 gcc_assert (CONSTANT_CLASS_P (new_name)
3972 || TREE_CODE (new_name) == SSA_NAME);
3973 new_vec = build_vector_from_val (stepvectype, t);
3974 vec_step = vect_init_vector (iv_phi, new_vec, stepvectype, NULL);
3976 vec_def = induc_def;
3977 prev_stmt_vinfo = vinfo_for_stmt (induction_phi);
3978 for (i = 1; i < ncopies; i++)
3980 /* vec_i = vec_prev + vec_step */
3981 new_stmt = gimple_build_assign (vec_dest, PLUS_EXPR,
3982 vec_def, vec_step);
3983 vec_def = make_ssa_name (vec_dest, new_stmt);
3984 gimple_assign_set_lhs (new_stmt, vec_def);
3986 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
3987 if (!useless_type_conversion_p (resvectype, vectype))
3989 new_stmt
3990 = gimple_build_assign
3991 (vect_get_new_vect_var (resvectype, vect_simple_var,
3992 "vec_iv_"),
3993 VIEW_CONVERT_EXPR,
3994 build1 (VIEW_CONVERT_EXPR, resvectype,
3995 gimple_assign_lhs (new_stmt)));
3996 gimple_assign_set_lhs (new_stmt,
3997 make_ssa_name
3998 (gimple_assign_lhs (new_stmt), new_stmt));
3999 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4001 set_vinfo_for_stmt (new_stmt,
4002 new_stmt_vec_info (new_stmt, loop_vinfo));
4003 STMT_VINFO_RELATED_STMT (prev_stmt_vinfo) = new_stmt;
4004 prev_stmt_vinfo = vinfo_for_stmt (new_stmt);
4008 if (nested_in_vect_loop)
4010 /* Find the loop-closed exit-phi of the induction, and record
4011 the final vector of induction results: */
4012 exit_phi = NULL;
4013 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
4015 gimple *use_stmt = USE_STMT (use_p);
4016 if (is_gimple_debug (use_stmt))
4017 continue;
4019 if (!flow_bb_inside_loop_p (iv_loop, gimple_bb (use_stmt)))
4021 exit_phi = use_stmt;
4022 break;
4025 if (exit_phi)
4027 stmt_vec_info stmt_vinfo = vinfo_for_stmt (exit_phi);
4028 /* FORNOW. Currently not supporting the case that an inner-loop induction
4029 is not used in the outer-loop (i.e. only outside the outer-loop). */
4030 gcc_assert (STMT_VINFO_RELEVANT_P (stmt_vinfo)
4031 && !STMT_VINFO_LIVE_P (stmt_vinfo));
4033 STMT_VINFO_VEC_STMT (stmt_vinfo) = new_stmt;
4034 if (dump_enabled_p ())
4036 dump_printf_loc (MSG_NOTE, vect_location,
4037 "vector of inductions after inner-loop:");
4038 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, new_stmt, 0);
4044 if (dump_enabled_p ())
4046 dump_printf_loc (MSG_NOTE, vect_location,
4047 "transform induction: created def-use cycle: ");
4048 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, induction_phi, 0);
4049 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
4050 SSA_NAME_DEF_STMT (vec_def), 0);
4053 STMT_VINFO_VEC_STMT (phi_info) = induction_phi;
4054 if (!useless_type_conversion_p (resvectype, vectype))
4056 new_stmt = gimple_build_assign (vect_get_new_vect_var (resvectype,
4057 vect_simple_var,
4058 "vec_iv_"),
4059 VIEW_CONVERT_EXPR,
4060 build1 (VIEW_CONVERT_EXPR, resvectype,
4061 induc_def));
4062 induc_def = make_ssa_name (gimple_assign_lhs (new_stmt), new_stmt);
4063 gimple_assign_set_lhs (new_stmt, induc_def);
4064 si = gsi_after_labels (bb);
4065 gsi_insert_before (&si, new_stmt, GSI_SAME_STMT);
4066 set_vinfo_for_stmt (new_stmt,
4067 new_stmt_vec_info (new_stmt, loop_vinfo));
4068 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_stmt))
4069 = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (induction_phi));
4072 return induc_def;
4076 /* Function get_initial_def_for_reduction
4078 Input:
4079 STMT - a stmt that performs a reduction operation in the loop.
4080 INIT_VAL - the initial value of the reduction variable
4082 Output:
4083 ADJUSTMENT_DEF - a tree that holds a value to be added to the final result
4084 of the reduction (used for adjusting the epilog - see below).
4085 Return a vector variable, initialized according to the operation that STMT
4086 performs. This vector will be used as the initial value of the
4087 vector of partial results.
4089 Option1 (adjust in epilog): Initialize the vector as follows:
4090 add/bit or/xor: [0,0,...,0,0]
4091 mult/bit and: [1,1,...,1,1]
4092 min/max/cond_expr: [init_val,init_val,..,init_val,init_val]
4093 and when necessary (e.g. add/mult case) let the caller know
4094 that it needs to adjust the result by init_val.
4096 Option2: Initialize the vector as follows:
4097 add/bit or/xor: [init_val,0,0,...,0]
4098 mult/bit and: [init_val,1,1,...,1]
4099 min/max/cond_expr: [init_val,init_val,...,init_val]
4100 and no adjustments are needed.
4102 For example, for the following code:
4104 s = init_val;
4105 for (i=0;i<n;i++)
4106 s = s + a[i];
4108 STMT is 's = s + a[i]', and the reduction variable is 's'.
4109 For a vector of 4 units, we want to return either [0,0,0,init_val],
4110 or [0,0,0,0] and let the caller know that it needs to adjust
4111 the result at the end by 'init_val'.
4113 FORNOW, we are using the 'adjust in epilog' scheme, because this way the
4114 initialization vector is simpler (same element in all entries), if
4115 ADJUSTMENT_DEF is not NULL, and Option2 otherwise.
4117 A cost model should help decide between these two schemes. */
4119 tree
4120 get_initial_def_for_reduction (gimple *stmt, tree init_val,
4121 tree *adjustment_def)
4123 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
4124 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
4125 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
4126 tree scalar_type = TREE_TYPE (init_val);
4127 tree vectype = get_vectype_for_scalar_type (scalar_type);
4128 int nunits;
4129 enum tree_code code = gimple_assign_rhs_code (stmt);
4130 tree def_for_init;
4131 tree init_def;
4132 tree *elts;
4133 int i;
4134 bool nested_in_vect_loop = false;
4135 REAL_VALUE_TYPE real_init_val = dconst0;
4136 int int_init_val = 0;
4137 gimple *def_stmt = NULL;
4138 gimple_seq stmts = NULL;
4140 gcc_assert (vectype);
4141 nunits = TYPE_VECTOR_SUBPARTS (vectype);
4143 gcc_assert (POINTER_TYPE_P (scalar_type) || INTEGRAL_TYPE_P (scalar_type)
4144 || SCALAR_FLOAT_TYPE_P (scalar_type));
4146 if (nested_in_vect_loop_p (loop, stmt))
4147 nested_in_vect_loop = true;
4148 else
4149 gcc_assert (loop == (gimple_bb (stmt))->loop_father);
4151 /* In case of double reduction we only create a vector variable to be put
4152 in the reduction phi node. The actual statement creation is done in
4153 vect_create_epilog_for_reduction. */
4154 if (adjustment_def && nested_in_vect_loop
4155 && TREE_CODE (init_val) == SSA_NAME
4156 && (def_stmt = SSA_NAME_DEF_STMT (init_val))
4157 && gimple_code (def_stmt) == GIMPLE_PHI
4158 && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
4159 && vinfo_for_stmt (def_stmt)
4160 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_stmt))
4161 == vect_double_reduction_def)
4163 *adjustment_def = NULL;
4164 return vect_create_destination_var (init_val, vectype);
4167 /* In case of a nested reduction do not use an adjustment def as
4168 that case is not supported by the epilogue generation correctly
4169 if ncopies is not one. */
4170 if (adjustment_def && nested_in_vect_loop)
4172 *adjustment_def = NULL;
4173 return vect_get_vec_def_for_operand (init_val, stmt);
4176 switch (code)
4178 case WIDEN_SUM_EXPR:
4179 case DOT_PROD_EXPR:
4180 case SAD_EXPR:
4181 case PLUS_EXPR:
4182 case MINUS_EXPR:
4183 case BIT_IOR_EXPR:
4184 case BIT_XOR_EXPR:
4185 case MULT_EXPR:
4186 case BIT_AND_EXPR:
4187 /* ADJUSMENT_DEF is NULL when called from
4188 vect_create_epilog_for_reduction to vectorize double reduction. */
4189 if (adjustment_def)
4190 *adjustment_def = init_val;
4192 if (code == MULT_EXPR)
4194 real_init_val = dconst1;
4195 int_init_val = 1;
4198 if (code == BIT_AND_EXPR)
4199 int_init_val = -1;
4201 if (SCALAR_FLOAT_TYPE_P (scalar_type))
4202 def_for_init = build_real (scalar_type, real_init_val);
4203 else
4204 def_for_init = build_int_cst (scalar_type, int_init_val);
4206 /* Create a vector of '0' or '1' except the first element. */
4207 elts = XALLOCAVEC (tree, nunits);
4208 for (i = nunits - 2; i >= 0; --i)
4209 elts[i + 1] = def_for_init;
4211 /* Option1: the first element is '0' or '1' as well. */
4212 if (adjustment_def)
4214 elts[0] = def_for_init;
4215 init_def = build_vector (vectype, elts);
4216 break;
4219 /* Option2: the first element is INIT_VAL. */
4220 elts[0] = init_val;
4221 if (TREE_CONSTANT (init_val))
4222 init_def = build_vector (vectype, elts);
4223 else
4225 vec<constructor_elt, va_gc> *v;
4226 vec_alloc (v, nunits);
4227 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init_val);
4228 for (i = 1; i < nunits; ++i)
4229 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, elts[i]);
4230 init_def = build_constructor (vectype, v);
4233 break;
4235 case MIN_EXPR:
4236 case MAX_EXPR:
4237 case COND_EXPR:
4238 if (adjustment_def)
4240 *adjustment_def = NULL_TREE;
4241 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_vinfo) != COND_REDUCTION)
4243 init_def = vect_get_vec_def_for_operand (init_val, stmt);
4244 break;
4247 init_val = gimple_convert (&stmts, TREE_TYPE (vectype), init_val);
4248 if (! gimple_seq_empty_p (stmts))
4249 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4250 init_def = build_vector_from_val (vectype, init_val);
4251 break;
4253 default:
4254 gcc_unreachable ();
4257 return init_def;
4260 /* Function vect_create_epilog_for_reduction
4262 Create code at the loop-epilog to finalize the result of a reduction
4263 computation.
4265 VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector
4266 reduction statements.
4267 STMT is the scalar reduction stmt that is being vectorized.
4268 NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the
4269 number of elements that we can fit in a vectype (nunits). In this case
4270 we have to generate more than one vector stmt - i.e - we need to "unroll"
4271 the vector stmt by a factor VF/nunits. For more details see documentation
4272 in vectorizable_operation.
4273 REDUC_CODE is the tree-code for the epilog reduction.
4274 REDUCTION_PHIS is a list of the phi-nodes that carry the reduction
4275 computation.
4276 REDUC_INDEX is the index of the operand in the right hand side of the
4277 statement that is defined by REDUCTION_PHI.
4278 DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled.
4279 SLP_NODE is an SLP node containing a group of reduction statements. The
4280 first one in this group is STMT.
4281 INDUCTION_INDEX is the index of the loop for condition reductions.
4282 Otherwise it is undefined.
4284 This function:
4285 1. Creates the reduction def-use cycles: sets the arguments for
4286 REDUCTION_PHIS:
4287 The loop-entry argument is the vectorized initial-value of the reduction.
4288 The loop-latch argument is taken from VECT_DEFS - the vector of partial
4289 sums.
4290 2. "Reduces" each vector of partial results VECT_DEFS into a single result,
4291 by applying the operation specified by REDUC_CODE if available, or by
4292 other means (whole-vector shifts or a scalar loop).
4293 The function also creates a new phi node at the loop exit to preserve
4294 loop-closed form, as illustrated below.
4296 The flow at the entry to this function:
4298 loop:
4299 vec_def = phi <null, null> # REDUCTION_PHI
4300 VECT_DEF = vector_stmt # vectorized form of STMT
4301 s_loop = scalar_stmt # (scalar) STMT
4302 loop_exit:
4303 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4304 use <s_out0>
4305 use <s_out0>
4307 The above is transformed by this function into:
4309 loop:
4310 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4311 VECT_DEF = vector_stmt # vectorized form of STMT
4312 s_loop = scalar_stmt # (scalar) STMT
4313 loop_exit:
4314 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
4315 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4316 v_out2 = reduce <v_out1>
4317 s_out3 = extract_field <v_out2, 0>
4318 s_out4 = adjust_result <s_out3>
4319 use <s_out4>
4320 use <s_out4>
4323 static void
4324 vect_create_epilog_for_reduction (vec<tree> vect_defs, gimple *stmt,
4325 int ncopies, enum tree_code reduc_code,
4326 vec<gimple *> reduction_phis,
4327 int reduc_index, bool double_reduc,
4328 slp_tree slp_node, tree induction_index)
4330 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
4331 stmt_vec_info prev_phi_info;
4332 tree vectype;
4333 machine_mode mode;
4334 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
4335 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo), *outer_loop = NULL;
4336 basic_block exit_bb;
4337 tree scalar_dest;
4338 tree scalar_type;
4339 gimple *new_phi = NULL, *phi;
4340 gimple_stmt_iterator exit_gsi;
4341 tree vec_dest;
4342 tree new_temp = NULL_TREE, new_dest, new_name, new_scalar_dest;
4343 gimple *epilog_stmt = NULL;
4344 enum tree_code code = gimple_assign_rhs_code (stmt);
4345 gimple *exit_phi;
4346 tree bitsize;
4347 tree adjustment_def = NULL;
4348 tree vec_initial_def = NULL;
4349 tree reduction_op, expr, def, initial_def = NULL;
4350 tree orig_name, scalar_result;
4351 imm_use_iterator imm_iter, phi_imm_iter;
4352 use_operand_p use_p, phi_use_p;
4353 gimple *use_stmt, *orig_stmt, *reduction_phi = NULL;
4354 bool nested_in_vect_loop = false;
4355 auto_vec<gimple *> new_phis;
4356 auto_vec<gimple *> inner_phis;
4357 enum vect_def_type dt = vect_unknown_def_type;
4358 int j, i;
4359 auto_vec<tree> scalar_results;
4360 unsigned int group_size = 1, k, ratio;
4361 auto_vec<tree> vec_initial_defs;
4362 auto_vec<gimple *> phis;
4363 bool slp_reduc = false;
4364 tree new_phi_result;
4365 gimple *inner_phi = NULL;
4367 if (slp_node)
4368 group_size = SLP_TREE_SCALAR_STMTS (slp_node).length ();
4370 if (nested_in_vect_loop_p (loop, stmt))
4372 outer_loop = loop;
4373 loop = loop->inner;
4374 nested_in_vect_loop = true;
4375 gcc_assert (!slp_node);
4378 reduction_op = get_reduction_op (stmt, reduc_index);
4380 vectype = get_vectype_for_scalar_type (TREE_TYPE (reduction_op));
4381 gcc_assert (vectype);
4382 mode = TYPE_MODE (vectype);
4384 /* 1. Create the reduction def-use cycle:
4385 Set the arguments of REDUCTION_PHIS, i.e., transform
4387 loop:
4388 vec_def = phi <null, null> # REDUCTION_PHI
4389 VECT_DEF = vector_stmt # vectorized form of STMT
4392 into:
4394 loop:
4395 vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI
4396 VECT_DEF = vector_stmt # vectorized form of STMT
4399 (in case of SLP, do it for all the phis). */
4401 /* Get the loop-entry arguments. */
4402 enum vect_def_type initial_def_dt = vect_unknown_def_type;
4403 if (slp_node)
4404 vect_get_vec_defs (reduction_op, NULL_TREE, stmt, &vec_initial_defs,
4405 NULL, slp_node, reduc_index);
4406 else
4408 /* Get at the scalar def before the loop, that defines the initial value
4409 of the reduction variable. */
4410 gimple *def_stmt = SSA_NAME_DEF_STMT (reduction_op);
4411 initial_def = PHI_ARG_DEF_FROM_EDGE (def_stmt,
4412 loop_preheader_edge (loop));
4413 vect_is_simple_use (initial_def, loop_vinfo, &def_stmt, &initial_def_dt);
4414 vec_initial_def = get_initial_def_for_reduction (stmt, initial_def,
4415 &adjustment_def);
4416 vec_initial_defs.create (1);
4417 vec_initial_defs.quick_push (vec_initial_def);
4420 /* Set phi nodes arguments. */
4421 FOR_EACH_VEC_ELT (reduction_phis, i, phi)
4423 tree vec_init_def, def;
4424 gimple_seq stmts;
4425 vec_init_def = force_gimple_operand (vec_initial_defs[i], &stmts,
4426 true, NULL_TREE);
4427 if (stmts)
4428 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
4430 def = vect_defs[i];
4431 for (j = 0; j < ncopies; j++)
4433 if (j != 0)
4435 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4436 if (nested_in_vect_loop)
4437 vec_init_def
4438 = vect_get_vec_def_for_stmt_copy (initial_def_dt,
4439 vec_init_def);
4442 /* Set the loop-entry arg of the reduction-phi. */
4444 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4445 == INTEGER_INDUC_COND_REDUCTION)
4447 /* Initialise the reduction phi to zero. This prevents initial
4448 values of non-zero interferring with the reduction op. */
4449 gcc_assert (ncopies == 1);
4450 gcc_assert (i == 0);
4452 tree vec_init_def_type = TREE_TYPE (vec_init_def);
4453 tree zero_vec = build_zero_cst (vec_init_def_type);
4455 add_phi_arg (as_a <gphi *> (phi), zero_vec,
4456 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4458 else
4459 add_phi_arg (as_a <gphi *> (phi), vec_init_def,
4460 loop_preheader_edge (loop), UNKNOWN_LOCATION);
4462 /* Set the loop-latch arg for the reduction-phi. */
4463 if (j > 0)
4464 def = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type, def);
4466 add_phi_arg (as_a <gphi *> (phi), def, loop_latch_edge (loop),
4467 UNKNOWN_LOCATION);
4469 if (dump_enabled_p ())
4471 dump_printf_loc (MSG_NOTE, vect_location,
4472 "transform reduction: created def-use cycle: ");
4473 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
4474 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (def), 0);
4479 /* 2. Create epilog code.
4480 The reduction epilog code operates across the elements of the vector
4481 of partial results computed by the vectorized loop.
4482 The reduction epilog code consists of:
4484 step 1: compute the scalar result in a vector (v_out2)
4485 step 2: extract the scalar result (s_out3) from the vector (v_out2)
4486 step 3: adjust the scalar result (s_out3) if needed.
4488 Step 1 can be accomplished using one the following three schemes:
4489 (scheme 1) using reduc_code, if available.
4490 (scheme 2) using whole-vector shifts, if available.
4491 (scheme 3) using a scalar loop. In this case steps 1+2 above are
4492 combined.
4494 The overall epilog code looks like this:
4496 s_out0 = phi <s_loop> # original EXIT_PHI
4497 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
4498 v_out2 = reduce <v_out1> # step 1
4499 s_out3 = extract_field <v_out2, 0> # step 2
4500 s_out4 = adjust_result <s_out3> # step 3
4502 (step 3 is optional, and steps 1 and 2 may be combined).
4503 Lastly, the uses of s_out0 are replaced by s_out4. */
4506 /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
4507 v_out1 = phi <VECT_DEF>
4508 Store them in NEW_PHIS. */
4510 exit_bb = single_exit (loop)->dest;
4511 prev_phi_info = NULL;
4512 new_phis.create (vect_defs.length ());
4513 FOR_EACH_VEC_ELT (vect_defs, i, def)
4515 for (j = 0; j < ncopies; j++)
4517 tree new_def = copy_ssa_name (def);
4518 phi = create_phi_node (new_def, exit_bb);
4519 set_vinfo_for_stmt (phi, new_stmt_vec_info (phi, loop_vinfo));
4520 if (j == 0)
4521 new_phis.quick_push (phi);
4522 else
4524 def = vect_get_vec_def_for_stmt_copy (dt, def);
4525 STMT_VINFO_RELATED_STMT (prev_phi_info) = phi;
4528 SET_PHI_ARG_DEF (phi, single_exit (loop)->dest_idx, def);
4529 prev_phi_info = vinfo_for_stmt (phi);
4533 /* The epilogue is created for the outer-loop, i.e., for the loop being
4534 vectorized. Create exit phis for the outer loop. */
4535 if (double_reduc)
4537 loop = outer_loop;
4538 exit_bb = single_exit (loop)->dest;
4539 inner_phis.create (vect_defs.length ());
4540 FOR_EACH_VEC_ELT (new_phis, i, phi)
4542 tree new_result = copy_ssa_name (PHI_RESULT (phi));
4543 gphi *outer_phi = create_phi_node (new_result, exit_bb);
4544 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4545 PHI_RESULT (phi));
4546 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4547 loop_vinfo));
4548 inner_phis.quick_push (phi);
4549 new_phis[i] = outer_phi;
4550 prev_phi_info = vinfo_for_stmt (outer_phi);
4551 while (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi)))
4553 phi = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (phi));
4554 new_result = copy_ssa_name (PHI_RESULT (phi));
4555 outer_phi = create_phi_node (new_result, exit_bb);
4556 SET_PHI_ARG_DEF (outer_phi, single_exit (loop)->dest_idx,
4557 PHI_RESULT (phi));
4558 set_vinfo_for_stmt (outer_phi, new_stmt_vec_info (outer_phi,
4559 loop_vinfo));
4560 STMT_VINFO_RELATED_STMT (prev_phi_info) = outer_phi;
4561 prev_phi_info = vinfo_for_stmt (outer_phi);
4566 exit_gsi = gsi_after_labels (exit_bb);
4568 /* 2.2 Get the relevant tree-code to use in the epilog for schemes 2,3
4569 (i.e. when reduc_code is not available) and in the final adjustment
4570 code (if needed). Also get the original scalar reduction variable as
4571 defined in the loop. In case STMT is a "pattern-stmt" (i.e. - it
4572 represents a reduction pattern), the tree-code and scalar-def are
4573 taken from the original stmt that the pattern-stmt (STMT) replaces.
4574 Otherwise (it is a regular reduction) - the tree-code and scalar-def
4575 are taken from STMT. */
4577 orig_stmt = STMT_VINFO_RELATED_STMT (stmt_info);
4578 if (!orig_stmt)
4580 /* Regular reduction */
4581 orig_stmt = stmt;
4583 else
4585 /* Reduction pattern */
4586 stmt_vec_info stmt_vinfo = vinfo_for_stmt (orig_stmt);
4587 gcc_assert (STMT_VINFO_IN_PATTERN_P (stmt_vinfo));
4588 gcc_assert (STMT_VINFO_RELATED_STMT (stmt_vinfo) == stmt);
4591 code = gimple_assign_rhs_code (orig_stmt);
4592 /* For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore,
4593 partial results are added and not subtracted. */
4594 if (code == MINUS_EXPR)
4595 code = PLUS_EXPR;
4597 scalar_dest = gimple_assign_lhs (orig_stmt);
4598 scalar_type = TREE_TYPE (scalar_dest);
4599 scalar_results.create (group_size);
4600 new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
4601 bitsize = TYPE_SIZE (scalar_type);
4603 /* In case this is a reduction in an inner-loop while vectorizing an outer
4604 loop - we don't need to extract a single scalar result at the end of the
4605 inner-loop (unless it is double reduction, i.e., the use of reduction is
4606 outside the outer-loop). The final vector of partial results will be used
4607 in the vectorized outer-loop, or reduced to a scalar result at the end of
4608 the outer-loop. */
4609 if (nested_in_vect_loop && !double_reduc)
4610 goto vect_finalize_reduction;
4612 /* SLP reduction without reduction chain, e.g.,
4613 # a1 = phi <a2, a0>
4614 # b1 = phi <b2, b0>
4615 a2 = operation (a1)
4616 b2 = operation (b1) */
4617 slp_reduc = (slp_node && !GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)));
4619 /* In case of reduction chain, e.g.,
4620 # a1 = phi <a3, a0>
4621 a2 = operation (a1)
4622 a3 = operation (a2),
4624 we may end up with more than one vector result. Here we reduce them to
4625 one vector. */
4626 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
4628 tree first_vect = PHI_RESULT (new_phis[0]);
4629 tree tmp;
4630 gassign *new_vec_stmt = NULL;
4632 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4633 for (k = 1; k < new_phis.length (); k++)
4635 gimple *next_phi = new_phis[k];
4636 tree second_vect = PHI_RESULT (next_phi);
4638 tmp = build2 (code, vectype, first_vect, second_vect);
4639 new_vec_stmt = gimple_build_assign (vec_dest, tmp);
4640 first_vect = make_ssa_name (vec_dest, new_vec_stmt);
4641 gimple_assign_set_lhs (new_vec_stmt, first_vect);
4642 gsi_insert_before (&exit_gsi, new_vec_stmt, GSI_SAME_STMT);
4645 new_phi_result = first_vect;
4646 if (new_vec_stmt)
4648 new_phis.truncate (0);
4649 new_phis.safe_push (new_vec_stmt);
4652 else
4653 new_phi_result = PHI_RESULT (new_phis[0]);
4655 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
4657 /* For condition reductions, we have a vector (NEW_PHI_RESULT) containing
4658 various data values where the condition matched and another vector
4659 (INDUCTION_INDEX) containing all the indexes of those matches. We
4660 need to extract the last matching index (which will be the index with
4661 highest value) and use this to index into the data vector.
4662 For the case where there were no matches, the data vector will contain
4663 all default values and the index vector will be all zeros. */
4665 /* Get various versions of the type of the vector of indexes. */
4666 tree index_vec_type = TREE_TYPE (induction_index);
4667 gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
4668 tree index_scalar_type = TREE_TYPE (index_vec_type);
4669 tree index_vec_cmp_type = build_same_sized_truth_vector_type
4670 (index_vec_type);
4672 /* Get an unsigned integer version of the type of the data vector. */
4673 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
4674 tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
4675 tree vectype_unsigned = build_vector_type
4676 (scalar_type_unsigned, TYPE_VECTOR_SUBPARTS (vectype));
4678 /* First we need to create a vector (ZERO_VEC) of zeros and another
4679 vector (MAX_INDEX_VEC) filled with the last matching index, which we
4680 can create using a MAX reduction and then expanding.
4681 In the case where the loop never made any matches, the max index will
4682 be zero. */
4684 /* Vector of {0, 0, 0,...}. */
4685 tree zero_vec = make_ssa_name (vectype);
4686 tree zero_vec_rhs = build_zero_cst (vectype);
4687 gimple *zero_vec_stmt = gimple_build_assign (zero_vec, zero_vec_rhs);
4688 gsi_insert_before (&exit_gsi, zero_vec_stmt, GSI_SAME_STMT);
4690 /* Find maximum value from the vector of found indexes. */
4691 tree max_index = make_ssa_name (index_scalar_type);
4692 gimple *max_index_stmt = gimple_build_assign (max_index, REDUC_MAX_EXPR,
4693 induction_index);
4694 gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
4696 /* Vector of {max_index, max_index, max_index,...}. */
4697 tree max_index_vec = make_ssa_name (index_vec_type);
4698 tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
4699 max_index);
4700 gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
4701 max_index_vec_rhs);
4702 gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
4704 /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
4705 with the vector (INDUCTION_INDEX) of found indexes, choosing values
4706 from the data vector (NEW_PHI_RESULT) for matches, 0 (ZERO_VEC)
4707 otherwise. Only one value should match, resulting in a vector
4708 (VEC_COND) with one data value and the rest zeros.
4709 In the case where the loop never made any matches, every index will
4710 match, resulting in a vector with all data values (which will all be
4711 the default value). */
4713 /* Compare the max index vector to the vector of found indexes to find
4714 the position of the max value. */
4715 tree vec_compare = make_ssa_name (index_vec_cmp_type);
4716 gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
4717 induction_index,
4718 max_index_vec);
4719 gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
4721 /* Use the compare to choose either values from the data vector or
4722 zero. */
4723 tree vec_cond = make_ssa_name (vectype);
4724 gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
4725 vec_compare, new_phi_result,
4726 zero_vec);
4727 gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
4729 /* Finally we need to extract the data value from the vector (VEC_COND)
4730 into a scalar (MATCHED_DATA_REDUC). Logically we want to do a OR
4731 reduction, but because this doesn't exist, we can use a MAX reduction
4732 instead. The data value might be signed or a float so we need to cast
4733 it first.
4734 In the case where the loop never made any matches, the data values are
4735 all identical, and so will reduce down correctly. */
4737 /* Make the matched data values unsigned. */
4738 tree vec_cond_cast = make_ssa_name (vectype_unsigned);
4739 tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
4740 vec_cond);
4741 gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
4742 VIEW_CONVERT_EXPR,
4743 vec_cond_cast_rhs);
4744 gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
4746 /* Reduce down to a scalar value. */
4747 tree data_reduc = make_ssa_name (scalar_type_unsigned);
4748 optab ot = optab_for_tree_code (REDUC_MAX_EXPR, vectype_unsigned,
4749 optab_default);
4750 gcc_assert (optab_handler (ot, TYPE_MODE (vectype_unsigned))
4751 != CODE_FOR_nothing);
4752 gimple *data_reduc_stmt = gimple_build_assign (data_reduc,
4753 REDUC_MAX_EXPR,
4754 vec_cond_cast);
4755 gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
4757 /* Convert the reduced value back to the result type and set as the
4758 result. */
4759 tree data_reduc_cast = build1 (VIEW_CONVERT_EXPR, scalar_type,
4760 data_reduc);
4761 epilog_stmt = gimple_build_assign (new_scalar_dest, data_reduc_cast);
4762 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4763 gimple_assign_set_lhs (epilog_stmt, new_temp);
4764 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4765 scalar_results.safe_push (new_temp);
4768 /* 2.3 Create the reduction code, using one of the three schemes described
4769 above. In SLP we simply need to extract all the elements from the
4770 vector (without reducing them), so we use scalar shifts. */
4771 else if (reduc_code != ERROR_MARK && !slp_reduc)
4773 tree tmp;
4774 tree vec_elem_type;
4776 /*** Case 1: Create:
4777 v_out2 = reduc_expr <v_out1> */
4779 if (dump_enabled_p ())
4780 dump_printf_loc (MSG_NOTE, vect_location,
4781 "Reduce using direct vector reduction.\n");
4783 vec_elem_type = TREE_TYPE (TREE_TYPE (new_phi_result));
4784 if (!useless_type_conversion_p (scalar_type, vec_elem_type))
4786 tree tmp_dest =
4787 vect_create_destination_var (scalar_dest, vec_elem_type);
4788 tmp = build1 (reduc_code, vec_elem_type, new_phi_result);
4789 epilog_stmt = gimple_build_assign (tmp_dest, tmp);
4790 new_temp = make_ssa_name (tmp_dest, epilog_stmt);
4791 gimple_assign_set_lhs (epilog_stmt, new_temp);
4792 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4794 tmp = build1 (NOP_EXPR, scalar_type, new_temp);
4796 else
4797 tmp = build1 (reduc_code, scalar_type, new_phi_result);
4799 epilog_stmt = gimple_build_assign (new_scalar_dest, tmp);
4800 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4801 gimple_assign_set_lhs (epilog_stmt, new_temp);
4802 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4804 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
4805 == INTEGER_INDUC_COND_REDUCTION)
4807 /* Earlier we set the initial value to be zero. Check the result
4808 and if it is zero then replace with the original initial
4809 value. */
4810 tree zero = build_zero_cst (scalar_type);
4811 tree zcompare = build2 (EQ_EXPR, boolean_type_node, new_temp, zero);
4813 tmp = make_ssa_name (new_scalar_dest);
4814 epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
4815 initial_def, new_temp);
4816 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4817 new_temp = tmp;
4820 scalar_results.safe_push (new_temp);
4822 else
4824 bool reduce_with_shift = have_whole_vector_shift (mode);
4825 int element_bitsize = tree_to_uhwi (bitsize);
4826 int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4827 tree vec_temp;
4829 /* Regardless of whether we have a whole vector shift, if we're
4830 emulating the operation via tree-vect-generic, we don't want
4831 to use it. Only the first round of the reduction is likely
4832 to still be profitable via emulation. */
4833 /* ??? It might be better to emit a reduction tree code here, so that
4834 tree-vect-generic can expand the first round via bit tricks. */
4835 if (!VECTOR_MODE_P (mode))
4836 reduce_with_shift = false;
4837 else
4839 optab optab = optab_for_tree_code (code, vectype, optab_default);
4840 if (optab_handler (optab, mode) == CODE_FOR_nothing)
4841 reduce_with_shift = false;
4844 if (reduce_with_shift && !slp_reduc)
4846 int nelements = vec_size_in_bits / element_bitsize;
4847 unsigned char *sel = XALLOCAVEC (unsigned char, nelements);
4849 int elt_offset;
4851 tree zero_vec = build_zero_cst (vectype);
4852 /*** Case 2: Create:
4853 for (offset = nelements/2; offset >= 1; offset/=2)
4855 Create: va' = vec_shift <va, offset>
4856 Create: va = vop <va, va'>
4857 } */
4859 tree rhs;
4861 if (dump_enabled_p ())
4862 dump_printf_loc (MSG_NOTE, vect_location,
4863 "Reduce using vector shifts\n");
4865 vec_dest = vect_create_destination_var (scalar_dest, vectype);
4866 new_temp = new_phi_result;
4867 for (elt_offset = nelements / 2;
4868 elt_offset >= 1;
4869 elt_offset /= 2)
4871 calc_vec_perm_mask_for_shift (mode, elt_offset, sel);
4872 tree mask = vect_gen_perm_mask_any (vectype, sel);
4873 epilog_stmt = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
4874 new_temp, zero_vec, mask);
4875 new_name = make_ssa_name (vec_dest, epilog_stmt);
4876 gimple_assign_set_lhs (epilog_stmt, new_name);
4877 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4879 epilog_stmt = gimple_build_assign (vec_dest, code, new_name,
4880 new_temp);
4881 new_temp = make_ssa_name (vec_dest, epilog_stmt);
4882 gimple_assign_set_lhs (epilog_stmt, new_temp);
4883 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4886 /* 2.4 Extract the final scalar result. Create:
4887 s_out3 = extract_field <v_out2, bitpos> */
4889 if (dump_enabled_p ())
4890 dump_printf_loc (MSG_NOTE, vect_location,
4891 "extract scalar result\n");
4893 rhs = build3 (BIT_FIELD_REF, scalar_type, new_temp,
4894 bitsize, bitsize_zero_node);
4895 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4896 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4897 gimple_assign_set_lhs (epilog_stmt, new_temp);
4898 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4899 scalar_results.safe_push (new_temp);
4901 else
4903 /*** Case 3: Create:
4904 s = extract_field <v_out2, 0>
4905 for (offset = element_size;
4906 offset < vector_size;
4907 offset += element_size;)
4909 Create: s' = extract_field <v_out2, offset>
4910 Create: s = op <s, s'> // For non SLP cases
4911 } */
4913 if (dump_enabled_p ())
4914 dump_printf_loc (MSG_NOTE, vect_location,
4915 "Reduce using scalar code.\n");
4917 vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
4918 FOR_EACH_VEC_ELT (new_phis, i, new_phi)
4920 int bit_offset;
4921 if (gimple_code (new_phi) == GIMPLE_PHI)
4922 vec_temp = PHI_RESULT (new_phi);
4923 else
4924 vec_temp = gimple_assign_lhs (new_phi);
4925 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp, bitsize,
4926 bitsize_zero_node);
4927 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4928 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4929 gimple_assign_set_lhs (epilog_stmt, new_temp);
4930 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4932 /* In SLP we don't need to apply reduction operation, so we just
4933 collect s' values in SCALAR_RESULTS. */
4934 if (slp_reduc)
4935 scalar_results.safe_push (new_temp);
4937 for (bit_offset = element_bitsize;
4938 bit_offset < vec_size_in_bits;
4939 bit_offset += element_bitsize)
4941 tree bitpos = bitsize_int (bit_offset);
4942 tree rhs = build3 (BIT_FIELD_REF, scalar_type, vec_temp,
4943 bitsize, bitpos);
4945 epilog_stmt = gimple_build_assign (new_scalar_dest, rhs);
4946 new_name = make_ssa_name (new_scalar_dest, epilog_stmt);
4947 gimple_assign_set_lhs (epilog_stmt, new_name);
4948 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4950 if (slp_reduc)
4952 /* In SLP we don't need to apply reduction operation, so
4953 we just collect s' values in SCALAR_RESULTS. */
4954 new_temp = new_name;
4955 scalar_results.safe_push (new_name);
4957 else
4959 epilog_stmt = gimple_build_assign (new_scalar_dest, code,
4960 new_name, new_temp);
4961 new_temp = make_ssa_name (new_scalar_dest, epilog_stmt);
4962 gimple_assign_set_lhs (epilog_stmt, new_temp);
4963 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
4968 /* The only case where we need to reduce scalar results in SLP, is
4969 unrolling. If the size of SCALAR_RESULTS is greater than
4970 GROUP_SIZE, we reduce them combining elements modulo
4971 GROUP_SIZE. */
4972 if (slp_reduc)
4974 tree res, first_res, new_res;
4975 gimple *new_stmt;
4977 /* Reduce multiple scalar results in case of SLP unrolling. */
4978 for (j = group_size; scalar_results.iterate (j, &res);
4979 j++)
4981 first_res = scalar_results[j % group_size];
4982 new_stmt = gimple_build_assign (new_scalar_dest, code,
4983 first_res, res);
4984 new_res = make_ssa_name (new_scalar_dest, new_stmt);
4985 gimple_assign_set_lhs (new_stmt, new_res);
4986 gsi_insert_before (&exit_gsi, new_stmt, GSI_SAME_STMT);
4987 scalar_results[j % group_size] = new_res;
4990 else
4991 /* Not SLP - we have one scalar to keep in SCALAR_RESULTS. */
4992 scalar_results.safe_push (new_temp);
4996 vect_finalize_reduction:
4998 if (double_reduc)
4999 loop = loop->inner;
5001 /* 2.5 Adjust the final result by the initial value of the reduction
5002 variable. (When such adjustment is not needed, then
5003 'adjustment_def' is zero). For example, if code is PLUS we create:
5004 new_temp = loop_exit_def + adjustment_def */
5006 if (adjustment_def)
5008 gcc_assert (!slp_reduc);
5009 if (nested_in_vect_loop)
5011 new_phi = new_phis[0];
5012 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) == VECTOR_TYPE);
5013 expr = build2 (code, vectype, PHI_RESULT (new_phi), adjustment_def);
5014 new_dest = vect_create_destination_var (scalar_dest, vectype);
5016 else
5018 new_temp = scalar_results[0];
5019 gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
5020 expr = build2 (code, scalar_type, new_temp, adjustment_def);
5021 new_dest = vect_create_destination_var (scalar_dest, scalar_type);
5024 epilog_stmt = gimple_build_assign (new_dest, expr);
5025 new_temp = make_ssa_name (new_dest, epilog_stmt);
5026 gimple_assign_set_lhs (epilog_stmt, new_temp);
5027 gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
5028 if (nested_in_vect_loop)
5030 set_vinfo_for_stmt (epilog_stmt,
5031 new_stmt_vec_info (epilog_stmt, loop_vinfo));
5032 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (epilog_stmt)) =
5033 STMT_VINFO_RELATED_STMT (vinfo_for_stmt (new_phi));
5035 if (!double_reduc)
5036 scalar_results.quick_push (new_temp);
5037 else
5038 scalar_results[0] = new_temp;
5040 else
5041 scalar_results[0] = new_temp;
5043 new_phis[0] = epilog_stmt;
5046 /* 2.6 Handle the loop-exit phis. Replace the uses of scalar loop-exit
5047 phis with new adjusted scalar results, i.e., replace use <s_out0>
5048 with use <s_out4>.
5050 Transform:
5051 loop_exit:
5052 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5053 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5054 v_out2 = reduce <v_out1>
5055 s_out3 = extract_field <v_out2, 0>
5056 s_out4 = adjust_result <s_out3>
5057 use <s_out0>
5058 use <s_out0>
5060 into:
5062 loop_exit:
5063 s_out0 = phi <s_loop> # (scalar) EXIT_PHI
5064 v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI
5065 v_out2 = reduce <v_out1>
5066 s_out3 = extract_field <v_out2, 0>
5067 s_out4 = adjust_result <s_out3>
5068 use <s_out4>
5069 use <s_out4> */
5072 /* In SLP reduction chain we reduce vector results into one vector if
5073 necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of
5074 the last stmt in the reduction chain, since we are looking for the loop
5075 exit phi node. */
5076 if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
5078 gimple *dest_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[group_size - 1];
5079 /* Handle reduction patterns. */
5080 if (STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt)))
5081 dest_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (dest_stmt));
5083 scalar_dest = gimple_assign_lhs (dest_stmt);
5084 group_size = 1;
5087 /* In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in
5088 case that GROUP_SIZE is greater than vectorization factor). Therefore, we
5089 need to match SCALAR_RESULTS with corresponding statements. The first
5090 (GROUP_SIZE / number of new vector stmts) scalar results correspond to
5091 the first vector stmt, etc.
5092 (RATIO is equal to (GROUP_SIZE / number of new vector stmts)). */
5093 if (group_size > new_phis.length ())
5095 ratio = group_size / new_phis.length ();
5096 gcc_assert (!(group_size % new_phis.length ()));
5098 else
5099 ratio = 1;
5101 for (k = 0; k < group_size; k++)
5103 if (k % ratio == 0)
5105 epilog_stmt = new_phis[k / ratio];
5106 reduction_phi = reduction_phis[k / ratio];
5107 if (double_reduc)
5108 inner_phi = inner_phis[k / ratio];
5111 if (slp_reduc)
5113 gimple *current_stmt = SLP_TREE_SCALAR_STMTS (slp_node)[k];
5115 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (current_stmt));
5116 /* SLP statements can't participate in patterns. */
5117 gcc_assert (!orig_stmt);
5118 scalar_dest = gimple_assign_lhs (current_stmt);
5121 phis.create (3);
5122 /* Find the loop-closed-use at the loop exit of the original scalar
5123 result. (The reduction result is expected to have two immediate uses -
5124 one at the latch block, and one at the loop exit). */
5125 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5126 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p)))
5127 && !is_gimple_debug (USE_STMT (use_p)))
5128 phis.safe_push (USE_STMT (use_p));
5130 /* While we expect to have found an exit_phi because of loop-closed-ssa
5131 form we can end up without one if the scalar cycle is dead. */
5133 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5135 if (outer_loop)
5137 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
5138 gphi *vect_phi;
5140 /* FORNOW. Currently not supporting the case that an inner-loop
5141 reduction is not used in the outer-loop (but only outside the
5142 outer-loop), unless it is double reduction. */
5143 gcc_assert ((STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
5144 && !STMT_VINFO_LIVE_P (exit_phi_vinfo))
5145 || double_reduc);
5147 if (double_reduc)
5148 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = inner_phi;
5149 else
5150 STMT_VINFO_VEC_STMT (exit_phi_vinfo) = epilog_stmt;
5151 if (!double_reduc
5152 || STMT_VINFO_DEF_TYPE (exit_phi_vinfo)
5153 != vect_double_reduction_def)
5154 continue;
5156 /* Handle double reduction:
5158 stmt1: s1 = phi <s0, s2> - double reduction phi (outer loop)
5159 stmt2: s3 = phi <s1, s4> - (regular) reduc phi (inner loop)
5160 stmt3: s4 = use (s3) - (regular) reduc stmt (inner loop)
5161 stmt4: s2 = phi <s4> - double reduction stmt (outer loop)
5163 At that point the regular reduction (stmt2 and stmt3) is
5164 already vectorized, as well as the exit phi node, stmt4.
5165 Here we vectorize the phi node of double reduction, stmt1, and
5166 update all relevant statements. */
5168 /* Go through all the uses of s2 to find double reduction phi
5169 node, i.e., stmt1 above. */
5170 orig_name = PHI_RESULT (exit_phi);
5171 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5173 stmt_vec_info use_stmt_vinfo;
5174 stmt_vec_info new_phi_vinfo;
5175 tree vect_phi_init, preheader_arg, vect_phi_res, init_def;
5176 basic_block bb = gimple_bb (use_stmt);
5177 gimple *use;
5179 /* Check that USE_STMT is really double reduction phi
5180 node. */
5181 if (gimple_code (use_stmt) != GIMPLE_PHI
5182 || gimple_phi_num_args (use_stmt) != 2
5183 || bb->loop_father != outer_loop)
5184 continue;
5185 use_stmt_vinfo = vinfo_for_stmt (use_stmt);
5186 if (!use_stmt_vinfo
5187 || STMT_VINFO_DEF_TYPE (use_stmt_vinfo)
5188 != vect_double_reduction_def)
5189 continue;
5191 /* Create vector phi node for double reduction:
5192 vs1 = phi <vs0, vs2>
5193 vs1 was created previously in this function by a call to
5194 vect_get_vec_def_for_operand and is stored in
5195 vec_initial_def;
5196 vs2 is defined by INNER_PHI, the vectorized EXIT_PHI;
5197 vs0 is created here. */
5199 /* Create vector phi node. */
5200 vect_phi = create_phi_node (vec_initial_def, bb);
5201 new_phi_vinfo = new_stmt_vec_info (vect_phi,
5202 loop_vec_info_for_loop (outer_loop));
5203 set_vinfo_for_stmt (vect_phi, new_phi_vinfo);
5205 /* Create vs0 - initial def of the double reduction phi. */
5206 preheader_arg = PHI_ARG_DEF_FROM_EDGE (use_stmt,
5207 loop_preheader_edge (outer_loop));
5208 init_def = get_initial_def_for_reduction (stmt,
5209 preheader_arg, NULL);
5210 vect_phi_init = vect_init_vector (use_stmt, init_def,
5211 vectype, NULL);
5213 /* Update phi node arguments with vs0 and vs2. */
5214 add_phi_arg (vect_phi, vect_phi_init,
5215 loop_preheader_edge (outer_loop),
5216 UNKNOWN_LOCATION);
5217 add_phi_arg (vect_phi, PHI_RESULT (inner_phi),
5218 loop_latch_edge (outer_loop), UNKNOWN_LOCATION);
5219 if (dump_enabled_p ())
5221 dump_printf_loc (MSG_NOTE, vect_location,
5222 "created double reduction phi node: ");
5223 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, vect_phi, 0);
5226 vect_phi_res = PHI_RESULT (vect_phi);
5228 /* Replace the use, i.e., set the correct vs1 in the regular
5229 reduction phi node. FORNOW, NCOPIES is always 1, so the
5230 loop is redundant. */
5231 use = reduction_phi;
5232 for (j = 0; j < ncopies; j++)
5234 edge pr_edge = loop_preheader_edge (loop);
5235 SET_PHI_ARG_DEF (use, pr_edge->dest_idx, vect_phi_res);
5236 use = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (use));
5242 phis.release ();
5243 if (nested_in_vect_loop)
5245 if (double_reduc)
5246 loop = outer_loop;
5247 else
5248 continue;
5251 phis.create (3);
5252 /* Find the loop-closed-use at the loop exit of the original scalar
5253 result. (The reduction result is expected to have two immediate uses,
5254 one at the latch block, and one at the loop exit). For double
5255 reductions we are looking for exit phis of the outer loop. */
5256 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
5258 if (!flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
5260 if (!is_gimple_debug (USE_STMT (use_p)))
5261 phis.safe_push (USE_STMT (use_p));
5263 else
5265 if (double_reduc && gimple_code (USE_STMT (use_p)) == GIMPLE_PHI)
5267 tree phi_res = PHI_RESULT (USE_STMT (use_p));
5269 FOR_EACH_IMM_USE_FAST (phi_use_p, phi_imm_iter, phi_res)
5271 if (!flow_bb_inside_loop_p (loop,
5272 gimple_bb (USE_STMT (phi_use_p)))
5273 && !is_gimple_debug (USE_STMT (phi_use_p)))
5274 phis.safe_push (USE_STMT (phi_use_p));
5280 FOR_EACH_VEC_ELT (phis, i, exit_phi)
5282 /* Replace the uses: */
5283 orig_name = PHI_RESULT (exit_phi);
5284 scalar_result = scalar_results[k];
5285 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
5286 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
5287 SET_USE (use_p, scalar_result);
5290 phis.release ();
5295 /* Function is_nonwrapping_integer_induction.
5297 Check if STMT (which is part of loop LOOP) both increments and
5298 does not cause overflow. */
5300 static bool
5301 is_nonwrapping_integer_induction (gimple *stmt, struct loop *loop)
5303 stmt_vec_info stmt_vinfo = vinfo_for_stmt (stmt);
5304 tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
5305 tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
5306 tree lhs_type = TREE_TYPE (gimple_phi_result (stmt));
5307 widest_int ni, max_loop_value, lhs_max;
5308 bool overflow = false;
5310 /* Make sure the loop is integer based. */
5311 if (TREE_CODE (base) != INTEGER_CST
5312 || TREE_CODE (step) != INTEGER_CST)
5313 return false;
5315 /* Check that the induction increments. */
5316 if (tree_int_cst_sgn (step) == -1)
5317 return false;
5319 /* Check that the max size of the loop will not wrap. */
5321 if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
5322 return true;
5324 if (! max_stmt_executions (loop, &ni))
5325 return false;
5327 max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
5328 &overflow);
5329 if (overflow)
5330 return false;
5332 max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
5333 TYPE_SIGN (lhs_type), &overflow);
5334 if (overflow)
5335 return false;
5337 return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
5338 <= TYPE_PRECISION (lhs_type));
5341 /* Function vectorizable_reduction.
5343 Check if STMT performs a reduction operation that can be vectorized.
5344 If VEC_STMT is also passed, vectorize the STMT: create a vectorized
5345 stmt to replace it, put it in VEC_STMT, and insert it at GSI.
5346 Return FALSE if not a vectorizable STMT, TRUE otherwise.
5348 This function also handles reduction idioms (patterns) that have been
5349 recognized in advance during vect_pattern_recog. In this case, STMT may be
5350 of this form:
5351 X = pattern_expr (arg0, arg1, ..., X)
5352 and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original
5353 sequence that had been detected and replaced by the pattern-stmt (STMT).
5355 This function also handles reduction of condition expressions, for example:
5356 for (int i = 0; i < N; i++)
5357 if (a[i] < value)
5358 last = a[i];
5359 This is handled by vectorising the loop and creating an additional vector
5360 containing the loop indexes for which "a[i] < value" was true. In the
5361 function epilogue this is reduced to a single max value and then used to
5362 index into the vector of results.
5364 In some cases of reduction patterns, the type of the reduction variable X is
5365 different than the type of the other arguments of STMT.
5366 In such cases, the vectype that is used when transforming STMT into a vector
5367 stmt is different than the vectype that is used to determine the
5368 vectorization factor, because it consists of a different number of elements
5369 than the actual number of elements that are being operated upon in parallel.
5371 For example, consider an accumulation of shorts into an int accumulator.
5372 On some targets it's possible to vectorize this pattern operating on 8
5373 shorts at a time (hence, the vectype for purposes of determining the
5374 vectorization factor should be V8HI); on the other hand, the vectype that
5375 is used to create the vector form is actually V4SI (the type of the result).
5377 Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
5378 indicates what is the actual level of parallelism (V8HI in the example), so
5379 that the right vectorization factor would be derived. This vectype
5380 corresponds to the type of arguments to the reduction stmt, and should *NOT*
5381 be used to create the vectorized stmt. The right vectype for the vectorized
5382 stmt is obtained from the type of the result X:
5383 get_vectype_for_scalar_type (TREE_TYPE (X))
5385 This means that, contrary to "regular" reductions (or "regular" stmts in
5386 general), the following equation:
5387 STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X))
5388 does *NOT* necessarily hold for reduction patterns. */
5390 bool
5391 vectorizable_reduction (gimple *stmt, gimple_stmt_iterator *gsi,
5392 gimple **vec_stmt, slp_tree slp_node)
5394 tree vec_dest;
5395 tree scalar_dest;
5396 tree loop_vec_def0 = NULL_TREE, loop_vec_def1 = NULL_TREE;
5397 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
5398 tree vectype_out = STMT_VINFO_VECTYPE (stmt_info);
5399 tree vectype_in = NULL_TREE;
5400 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
5401 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
5402 enum tree_code code, orig_code, epilog_reduc_code;
5403 machine_mode vec_mode;
5404 int op_type;
5405 optab optab, reduc_optab;
5406 tree new_temp = NULL_TREE;
5407 gimple *def_stmt;
5408 enum vect_def_type dt, cond_reduc_dt = vect_unknown_def_type;
5409 gphi *new_phi = NULL;
5410 tree scalar_type;
5411 bool is_simple_use;
5412 gimple *orig_stmt;
5413 stmt_vec_info orig_stmt_info;
5414 tree expr = NULL_TREE;
5415 int i;
5416 int ncopies;
5417 int epilog_copies;
5418 stmt_vec_info prev_stmt_info, prev_phi_info;
5419 bool single_defuse_cycle = false;
5420 tree reduc_def = NULL_TREE;
5421 gimple *new_stmt = NULL;
5422 int j;
5423 tree ops[3];
5424 bool nested_cycle = false, found_nested_cycle_def = false;
5425 gimple *reduc_def_stmt = NULL;
5426 bool double_reduc = false, dummy;
5427 basic_block def_bb;
5428 struct loop * def_stmt_loop, *outer_loop = NULL;
5429 tree def_arg;
5430 gimple *def_arg_stmt;
5431 auto_vec<tree> vec_oprnds0;
5432 auto_vec<tree> vec_oprnds1;
5433 auto_vec<tree> vect_defs;
5434 auto_vec<gimple *> phis;
5435 int vec_num;
5436 tree def0, def1, tem, op1 = NULL_TREE;
5437 bool first_p = true;
5438 tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
5439 tree cond_reduc_val = NULL_TREE;
5441 /* In case of reduction chain we switch to the first stmt in the chain, but
5442 we don't update STMT_INFO, since only the last stmt is marked as reduction
5443 and has reduction properties. */
5444 if (GROUP_FIRST_ELEMENT (stmt_info)
5445 && GROUP_FIRST_ELEMENT (stmt_info) != stmt)
5447 stmt = GROUP_FIRST_ELEMENT (stmt_info);
5448 first_p = false;
5451 if (nested_in_vect_loop_p (loop, stmt))
5453 outer_loop = loop;
5454 loop = loop->inner;
5455 nested_cycle = true;
5458 /* 1. Is vectorizable reduction? */
5459 /* Not supportable if the reduction variable is used in the loop, unless
5460 it's a reduction chain. */
5461 if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
5462 && !GROUP_FIRST_ELEMENT (stmt_info))
5463 return false;
5465 /* Reductions that are not used even in an enclosing outer-loop,
5466 are expected to be "live" (used out of the loop). */
5467 if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
5468 && !STMT_VINFO_LIVE_P (stmt_info))
5469 return false;
5471 /* Make sure it was already recognized as a reduction computation. */
5472 if (STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_reduction_def
5473 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (stmt)) != vect_nested_cycle)
5474 return false;
5476 /* 2. Has this been recognized as a reduction pattern?
5478 Check if STMT represents a pattern that has been recognized
5479 in earlier analysis stages. For stmts that represent a pattern,
5480 the STMT_VINFO_RELATED_STMT field records the last stmt in
5481 the original sequence that constitutes the pattern. */
5483 orig_stmt = STMT_VINFO_RELATED_STMT (vinfo_for_stmt (stmt));
5484 if (orig_stmt)
5486 orig_stmt_info = vinfo_for_stmt (orig_stmt);
5487 gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
5488 gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
5491 /* 3. Check the operands of the operation. The first operands are defined
5492 inside the loop body. The last operand is the reduction variable,
5493 which is defined by the loop-header-phi. */
5495 gcc_assert (is_gimple_assign (stmt));
5497 /* Flatten RHS. */
5498 switch (get_gimple_rhs_class (gimple_assign_rhs_code (stmt)))
5500 case GIMPLE_SINGLE_RHS:
5501 op_type = TREE_OPERAND_LENGTH (gimple_assign_rhs1 (stmt));
5502 if (op_type == ternary_op)
5504 tree rhs = gimple_assign_rhs1 (stmt);
5505 ops[0] = TREE_OPERAND (rhs, 0);
5506 ops[1] = TREE_OPERAND (rhs, 1);
5507 ops[2] = TREE_OPERAND (rhs, 2);
5508 code = TREE_CODE (rhs);
5510 else
5511 return false;
5512 break;
5514 case GIMPLE_BINARY_RHS:
5515 code = gimple_assign_rhs_code (stmt);
5516 op_type = TREE_CODE_LENGTH (code);
5517 gcc_assert (op_type == binary_op);
5518 ops[0] = gimple_assign_rhs1 (stmt);
5519 ops[1] = gimple_assign_rhs2 (stmt);
5520 break;
5522 case GIMPLE_TERNARY_RHS:
5523 code = gimple_assign_rhs_code (stmt);
5524 op_type = TREE_CODE_LENGTH (code);
5525 gcc_assert (op_type == ternary_op);
5526 ops[0] = gimple_assign_rhs1 (stmt);
5527 ops[1] = gimple_assign_rhs2 (stmt);
5528 ops[2] = gimple_assign_rhs3 (stmt);
5529 break;
5531 case GIMPLE_UNARY_RHS:
5532 return false;
5534 default:
5535 gcc_unreachable ();
5537 /* The default is that the reduction variable is the last in statement. */
5538 int reduc_index = op_type - 1;
5539 if (code == MINUS_EXPR)
5540 reduc_index = 0;
5542 if (code == COND_EXPR && slp_node)
5543 return false;
5545 scalar_dest = gimple_assign_lhs (stmt);
5546 scalar_type = TREE_TYPE (scalar_dest);
5547 if (!POINTER_TYPE_P (scalar_type) && !INTEGRAL_TYPE_P (scalar_type)
5548 && !SCALAR_FLOAT_TYPE_P (scalar_type))
5549 return false;
5551 /* Do not try to vectorize bit-precision reductions. */
5552 if ((TYPE_PRECISION (scalar_type)
5553 != GET_MODE_PRECISION (TYPE_MODE (scalar_type))))
5554 return false;
5556 /* All uses but the last are expected to be defined in the loop.
5557 The last use is the reduction variable. In case of nested cycle this
5558 assumption is not true: we use reduc_index to record the index of the
5559 reduction variable. */
5560 for (i = 0; i < op_type; i++)
5562 if (i == reduc_index)
5563 continue;
5565 /* The condition of COND_EXPR is checked in vectorizable_condition(). */
5566 if (i == 0 && code == COND_EXPR)
5567 continue;
5569 is_simple_use = vect_is_simple_use (ops[i], loop_vinfo,
5570 &def_stmt, &dt, &tem);
5571 if (!vectype_in)
5572 vectype_in = tem;
5573 gcc_assert (is_simple_use);
5575 if (dt != vect_internal_def
5576 && dt != vect_external_def
5577 && dt != vect_constant_def
5578 && dt != vect_induction_def
5579 && !(dt == vect_nested_cycle && nested_cycle))
5580 return false;
5582 if (dt == vect_nested_cycle)
5584 found_nested_cycle_def = true;
5585 reduc_def_stmt = def_stmt;
5586 reduc_index = i;
5589 if (i == 1 && code == COND_EXPR)
5591 /* Record how value of COND_EXPR is defined. */
5592 if (dt == vect_constant_def)
5594 cond_reduc_dt = dt;
5595 cond_reduc_val = ops[i];
5597 if (dt == vect_induction_def && def_stmt != NULL
5598 && is_nonwrapping_integer_induction (def_stmt, loop))
5599 cond_reduc_dt = dt;
5603 is_simple_use = vect_is_simple_use (ops[reduc_index], loop_vinfo,
5604 &def_stmt, &dt, &tem);
5605 if (!vectype_in)
5606 vectype_in = tem;
5607 gcc_assert (is_simple_use);
5608 if (!found_nested_cycle_def)
5609 reduc_def_stmt = def_stmt;
5611 if (reduc_def_stmt && gimple_code (reduc_def_stmt) != GIMPLE_PHI)
5612 return false;
5614 if (!(dt == vect_reduction_def
5615 || dt == vect_nested_cycle
5616 || ((dt == vect_internal_def || dt == vect_external_def
5617 || dt == vect_constant_def || dt == vect_induction_def)
5618 && nested_cycle && found_nested_cycle_def)))
5620 /* For pattern recognized stmts, orig_stmt might be a reduction,
5621 but some helper statements for the pattern might not, or
5622 might be COND_EXPRs with reduction uses in the condition. */
5623 gcc_assert (orig_stmt);
5624 return false;
5627 enum vect_reduction_type v_reduc_type;
5628 gimple *tmp = vect_is_simple_reduction (loop_vinfo, reduc_def_stmt,
5629 !nested_cycle, &dummy, false,
5630 &v_reduc_type);
5632 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = v_reduc_type;
5633 /* If we have a condition reduction, see if we can simplify it further. */
5634 if (v_reduc_type == COND_REDUCTION)
5636 if (cond_reduc_dt == vect_induction_def)
5638 if (dump_enabled_p ())
5639 dump_printf_loc (MSG_NOTE, vect_location,
5640 "condition expression based on "
5641 "integer induction.\n");
5642 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5643 = INTEGER_INDUC_COND_REDUCTION;
5646 /* Loop peeling modifies initial value of reduction PHI, which
5647 makes the reduction stmt to be transformed different to the
5648 original stmt analyzed. We need to record reduction code for
5649 CONST_COND_REDUCTION type reduction at analyzing stage, thus
5650 it can be used directly at transform stage. */
5651 if (STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MAX_EXPR
5652 || STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info) == MIN_EXPR)
5654 /* Also set the reduction type to CONST_COND_REDUCTION. */
5655 gcc_assert (cond_reduc_dt == vect_constant_def);
5656 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) = CONST_COND_REDUCTION;
5658 else if (cond_reduc_dt == vect_constant_def)
5660 enum vect_def_type cond_initial_dt;
5661 gimple *def_stmt = SSA_NAME_DEF_STMT (ops[reduc_index]);
5662 tree cond_initial_val
5663 = PHI_ARG_DEF_FROM_EDGE (def_stmt, loop_preheader_edge (loop));
5665 gcc_assert (cond_reduc_val != NULL_TREE);
5666 vect_is_simple_use (cond_initial_val, loop_vinfo,
5667 &def_stmt, &cond_initial_dt);
5668 if (cond_initial_dt == vect_constant_def
5669 && types_compatible_p (TREE_TYPE (cond_initial_val),
5670 TREE_TYPE (cond_reduc_val)))
5672 tree e = fold_build2 (LE_EXPR, boolean_type_node,
5673 cond_initial_val, cond_reduc_val);
5674 if (e && (integer_onep (e) || integer_zerop (e)))
5676 if (dump_enabled_p ())
5677 dump_printf_loc (MSG_NOTE, vect_location,
5678 "condition expression based on "
5679 "compile time constant.\n");
5680 /* Record reduction code at analysis stage. */
5681 STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info)
5682 = integer_onep (e) ? MAX_EXPR : MIN_EXPR;
5683 STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5684 = CONST_COND_REDUCTION;
5690 if (orig_stmt)
5691 gcc_assert (tmp == orig_stmt
5692 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == orig_stmt);
5693 else
5694 /* We changed STMT to be the first stmt in reduction chain, hence we
5695 check that in this case the first element in the chain is STMT. */
5696 gcc_assert (stmt == tmp
5697 || GROUP_FIRST_ELEMENT (vinfo_for_stmt (tmp)) == stmt);
5699 if (STMT_VINFO_LIVE_P (vinfo_for_stmt (reduc_def_stmt)))
5700 return false;
5702 if (slp_node)
5703 ncopies = 1;
5704 else
5705 ncopies = (LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5706 / TYPE_VECTOR_SUBPARTS (vectype_in));
5708 gcc_assert (ncopies >= 1);
5710 vec_mode = TYPE_MODE (vectype_in);
5712 if (code == COND_EXPR)
5714 /* Only call during the analysis stage, otherwise we'll lose
5715 STMT_VINFO_TYPE. */
5716 if (!vec_stmt && !vectorizable_condition (stmt, gsi, NULL,
5717 ops[reduc_index], 0, NULL))
5719 if (dump_enabled_p ())
5720 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5721 "unsupported condition in reduction\n");
5722 return false;
5725 else
5727 /* 4. Supportable by target? */
5729 if (code == LSHIFT_EXPR || code == RSHIFT_EXPR
5730 || code == LROTATE_EXPR || code == RROTATE_EXPR)
5732 /* Shifts and rotates are only supported by vectorizable_shifts,
5733 not vectorizable_reduction. */
5734 if (dump_enabled_p ())
5735 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5736 "unsupported shift or rotation.\n");
5737 return false;
5740 /* 4.1. check support for the operation in the loop */
5741 optab = optab_for_tree_code (code, vectype_in, optab_default);
5742 if (!optab)
5744 if (dump_enabled_p ())
5745 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5746 "no optab.\n");
5748 return false;
5751 if (optab_handler (optab, vec_mode) == CODE_FOR_nothing)
5753 if (dump_enabled_p ())
5754 dump_printf (MSG_NOTE, "op not supported by target.\n");
5756 if (GET_MODE_SIZE (vec_mode) != UNITS_PER_WORD
5757 || LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5758 < vect_min_worthwhile_factor (code))
5759 return false;
5761 if (dump_enabled_p ())
5762 dump_printf (MSG_NOTE, "proceeding using word mode.\n");
5765 /* Worthwhile without SIMD support? */
5766 if (!VECTOR_MODE_P (TYPE_MODE (vectype_in))
5767 && LOOP_VINFO_VECT_FACTOR (loop_vinfo)
5768 < vect_min_worthwhile_factor (code))
5770 if (dump_enabled_p ())
5771 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5772 "not worthwhile without SIMD support.\n");
5774 return false;
5778 /* 4.2. Check support for the epilog operation.
5780 If STMT represents a reduction pattern, then the type of the
5781 reduction variable may be different than the type of the rest
5782 of the arguments. For example, consider the case of accumulation
5783 of shorts into an int accumulator; The original code:
5784 S1: int_a = (int) short_a;
5785 orig_stmt-> S2: int_acc = plus <int_a ,int_acc>;
5787 was replaced with:
5788 STMT: int_acc = widen_sum <short_a, int_acc>
5790 This means that:
5791 1. The tree-code that is used to create the vector operation in the
5792 epilog code (that reduces the partial results) is not the
5793 tree-code of STMT, but is rather the tree-code of the original
5794 stmt from the pattern that STMT is replacing. I.e, in the example
5795 above we want to use 'widen_sum' in the loop, but 'plus' in the
5796 epilog.
5797 2. The type (mode) we use to check available target support
5798 for the vector operation to be created in the *epilog*, is
5799 determined by the type of the reduction variable (in the example
5800 above we'd check this: optab_handler (plus_optab, vect_int_mode])).
5801 However the type (mode) we use to check available target support
5802 for the vector operation to be created *inside the loop*, is
5803 determined by the type of the other arguments to STMT (in the
5804 example we'd check this: optab_handler (widen_sum_optab,
5805 vect_short_mode)).
5807 This is contrary to "regular" reductions, in which the types of all
5808 the arguments are the same as the type of the reduction variable.
5809 For "regular" reductions we can therefore use the same vector type
5810 (and also the same tree-code) when generating the epilog code and
5811 when generating the code inside the loop. */
5813 if (orig_stmt)
5815 /* This is a reduction pattern: get the vectype from the type of the
5816 reduction variable, and get the tree-code from orig_stmt. */
5817 gcc_assert (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5818 == TREE_CODE_REDUCTION);
5819 orig_code = gimple_assign_rhs_code (orig_stmt);
5820 gcc_assert (vectype_out);
5821 vec_mode = TYPE_MODE (vectype_out);
5823 else
5825 /* Regular reduction: use the same vectype and tree-code as used for
5826 the vector code inside the loop can be used for the epilog code. */
5827 orig_code = code;
5829 if (code == MINUS_EXPR)
5830 orig_code = PLUS_EXPR;
5832 /* For simple condition reductions, replace with the actual expression
5833 we want to base our reduction around. */
5834 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == CONST_COND_REDUCTION)
5836 orig_code = STMT_VINFO_VEC_CONST_COND_REDUC_CODE (stmt_info);
5837 gcc_assert (orig_code == MAX_EXPR || orig_code == MIN_EXPR);
5839 else if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5840 == INTEGER_INDUC_COND_REDUCTION)
5841 orig_code = MAX_EXPR;
5844 if (nested_cycle)
5846 def_bb = gimple_bb (reduc_def_stmt);
5847 def_stmt_loop = def_bb->loop_father;
5848 def_arg = PHI_ARG_DEF_FROM_EDGE (reduc_def_stmt,
5849 loop_preheader_edge (def_stmt_loop));
5850 if (TREE_CODE (def_arg) == SSA_NAME
5851 && (def_arg_stmt = SSA_NAME_DEF_STMT (def_arg))
5852 && gimple_code (def_arg_stmt) == GIMPLE_PHI
5853 && flow_bb_inside_loop_p (outer_loop, gimple_bb (def_arg_stmt))
5854 && vinfo_for_stmt (def_arg_stmt)
5855 && STMT_VINFO_DEF_TYPE (vinfo_for_stmt (def_arg_stmt))
5856 == vect_double_reduction_def)
5857 double_reduc = true;
5860 epilog_reduc_code = ERROR_MARK;
5862 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != COND_REDUCTION)
5864 if (reduction_code_for_scalar_code (orig_code, &epilog_reduc_code))
5866 reduc_optab = optab_for_tree_code (epilog_reduc_code, vectype_out,
5867 optab_default);
5868 if (!reduc_optab)
5870 if (dump_enabled_p ())
5871 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5872 "no optab for reduction.\n");
5874 epilog_reduc_code = ERROR_MARK;
5876 else if (optab_handler (reduc_optab, vec_mode) == CODE_FOR_nothing)
5878 if (dump_enabled_p ())
5879 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5880 "reduc op not supported by target.\n");
5882 epilog_reduc_code = ERROR_MARK;
5885 /* When epilog_reduc_code is ERROR_MARK then a reduction will be
5886 generated in the epilog using multiple expressions. This does not
5887 work for condition reductions. */
5888 if (epilog_reduc_code == ERROR_MARK
5889 && (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5890 == INTEGER_INDUC_COND_REDUCTION
5891 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info)
5892 == CONST_COND_REDUCTION))
5894 if (dump_enabled_p ())
5895 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5896 "no reduc code for scalar code.\n");
5897 return false;
5900 else
5902 if (!nested_cycle || double_reduc)
5904 if (dump_enabled_p ())
5905 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5906 "no reduc code for scalar code.\n");
5908 return false;
5912 else
5914 int scalar_precision = GET_MODE_PRECISION (TYPE_MODE (scalar_type));
5915 cr_index_scalar_type = make_unsigned_type (scalar_precision);
5916 cr_index_vector_type = build_vector_type
5917 (cr_index_scalar_type, TYPE_VECTOR_SUBPARTS (vectype_out));
5919 epilog_reduc_code = REDUC_MAX_EXPR;
5920 optab = optab_for_tree_code (REDUC_MAX_EXPR, cr_index_vector_type,
5921 optab_default);
5922 if (optab_handler (optab, TYPE_MODE (cr_index_vector_type))
5923 == CODE_FOR_nothing)
5925 if (dump_enabled_p ())
5926 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5927 "reduc max op not supported by target.\n");
5928 return false;
5932 if ((double_reduc
5933 || STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) != TREE_CODE_REDUCTION)
5934 && ncopies > 1)
5936 if (dump_enabled_p ())
5937 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5938 "multiple types in double reduction or condition "
5939 "reduction.\n");
5940 return false;
5943 /* In case of widenning multiplication by a constant, we update the type
5944 of the constant to be the type of the other operand. We check that the
5945 constant fits the type in the pattern recognition pass. */
5946 if (code == DOT_PROD_EXPR
5947 && !types_compatible_p (TREE_TYPE (ops[0]), TREE_TYPE (ops[1])))
5949 if (TREE_CODE (ops[0]) == INTEGER_CST)
5950 ops[0] = fold_convert (TREE_TYPE (ops[1]), ops[0]);
5951 else if (TREE_CODE (ops[1]) == INTEGER_CST)
5952 ops[1] = fold_convert (TREE_TYPE (ops[0]), ops[1]);
5953 else
5955 if (dump_enabled_p ())
5956 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
5957 "invalid types in dot-prod\n");
5959 return false;
5963 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
5965 widest_int ni;
5967 if (! max_loop_iterations (loop, &ni))
5969 if (dump_enabled_p ())
5970 dump_printf_loc (MSG_NOTE, vect_location,
5971 "loop count not known, cannot create cond "
5972 "reduction.\n");
5973 return false;
5975 /* Convert backedges to iterations. */
5976 ni += 1;
5978 /* The additional index will be the same type as the condition. Check
5979 that the loop can fit into this less one (because we'll use up the
5980 zero slot for when there are no matches). */
5981 tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
5982 if (wi::geu_p (ni, wi::to_widest (max_index)))
5984 if (dump_enabled_p ())
5985 dump_printf_loc (MSG_NOTE, vect_location,
5986 "loop size is greater than data size.\n");
5987 return false;
5991 if (!vec_stmt) /* transformation not required. */
5993 if (first_p
5994 && !vect_model_reduction_cost (stmt_info, epilog_reduc_code, ncopies,
5995 reduc_index))
5996 return false;
5997 STMT_VINFO_TYPE (stmt_info) = reduc_vec_info_type;
5998 return true;
6001 /** Transform. **/
6003 if (dump_enabled_p ())
6004 dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
6006 /* FORNOW: Multiple types are not supported for condition. */
6007 if (code == COND_EXPR)
6008 gcc_assert (ncopies == 1);
6010 /* Create the destination vector */
6011 vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
6013 /* In case the vectorization factor (VF) is bigger than the number
6014 of elements that we can fit in a vectype (nunits), we have to generate
6015 more than one vector stmt - i.e - we need to "unroll" the
6016 vector stmt by a factor VF/nunits. For more details see documentation
6017 in vectorizable_operation. */
6019 /* If the reduction is used in an outer loop we need to generate
6020 VF intermediate results, like so (e.g. for ncopies=2):
6021 r0 = phi (init, r0)
6022 r1 = phi (init, r1)
6023 r0 = x0 + r0;
6024 r1 = x1 + r1;
6025 (i.e. we generate VF results in 2 registers).
6026 In this case we have a separate def-use cycle for each copy, and therefore
6027 for each copy we get the vector def for the reduction variable from the
6028 respective phi node created for this copy.
6030 Otherwise (the reduction is unused in the loop nest), we can combine
6031 together intermediate results, like so (e.g. for ncopies=2):
6032 r = phi (init, r)
6033 r = x0 + r;
6034 r = x1 + r;
6035 (i.e. we generate VF/2 results in a single register).
6036 In this case for each copy we get the vector def for the reduction variable
6037 from the vectorized reduction operation generated in the previous iteration.
6040 if (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
6042 single_defuse_cycle = true;
6043 epilog_copies = 1;
6045 else
6046 epilog_copies = ncopies;
6048 prev_stmt_info = NULL;
6049 prev_phi_info = NULL;
6050 if (slp_node)
6051 vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6052 else
6054 vec_num = 1;
6055 vec_oprnds0.create (1);
6056 if (op_type == ternary_op)
6057 vec_oprnds1.create (1);
6060 phis.create (vec_num);
6061 vect_defs.create (vec_num);
6062 if (!slp_node)
6063 vect_defs.quick_push (NULL_TREE);
6065 for (j = 0; j < ncopies; j++)
6067 if (j == 0 || !single_defuse_cycle)
6069 for (i = 0; i < vec_num; i++)
6071 /* Create the reduction-phi that defines the reduction
6072 operand. */
6073 new_phi = create_phi_node (vec_dest, loop->header);
6074 set_vinfo_for_stmt (new_phi,
6075 new_stmt_vec_info (new_phi, loop_vinfo));
6076 if (j == 0 || slp_node)
6077 phis.quick_push (new_phi);
6081 if (code == COND_EXPR)
6083 gcc_assert (!slp_node);
6084 vectorizable_condition (stmt, gsi, vec_stmt,
6085 PHI_RESULT (phis[0]),
6086 reduc_index, NULL);
6087 /* Multiple types are not supported for condition. */
6088 break;
6091 /* Handle uses. */
6092 if (j == 0)
6094 if (slp_node)
6096 /* Get vec defs for all the operands except the reduction index,
6097 ensuring the ordering of the ops in the vector is kept. */
6098 auto_vec<tree, 3> slp_ops;
6099 auto_vec<vec<tree>, 3> vec_defs;
6101 slp_ops.quick_push ((reduc_index == 0) ? NULL : ops[0]);
6102 slp_ops.quick_push ((reduc_index == 1) ? NULL : ops[1]);
6103 if (op_type == ternary_op)
6104 slp_ops.quick_push ((reduc_index == 2) ? NULL : ops[2]);
6106 vect_get_slp_defs (slp_ops, slp_node, &vec_defs, -1);
6108 vec_oprnds0.safe_splice (vec_defs[(reduc_index == 0) ? 1 : 0]);
6109 if (op_type == ternary_op)
6110 vec_oprnds1.safe_splice (vec_defs[(reduc_index == 2) ? 1 : 2]);
6112 else
6114 loop_vec_def0 = vect_get_vec_def_for_operand (ops[!reduc_index],
6115 stmt);
6116 vec_oprnds0.quick_push (loop_vec_def0);
6117 if (op_type == ternary_op)
6119 op1 = (reduc_index == 0) ? ops[2] : ops[1];
6120 loop_vec_def1 = vect_get_vec_def_for_operand (op1, stmt);
6121 vec_oprnds1.quick_push (loop_vec_def1);
6125 else
6127 if (!slp_node)
6129 enum vect_def_type dt;
6130 gimple *dummy_stmt;
6132 vect_is_simple_use (ops[!reduc_index], loop_vinfo,
6133 &dummy_stmt, &dt);
6134 loop_vec_def0 = vect_get_vec_def_for_stmt_copy (dt,
6135 loop_vec_def0);
6136 vec_oprnds0[0] = loop_vec_def0;
6137 if (op_type == ternary_op)
6139 vect_is_simple_use (op1, loop_vinfo, &dummy_stmt, &dt);
6140 loop_vec_def1 = vect_get_vec_def_for_stmt_copy (dt,
6141 loop_vec_def1);
6142 vec_oprnds1[0] = loop_vec_def1;
6146 if (single_defuse_cycle)
6147 reduc_def = gimple_assign_lhs (new_stmt);
6149 STMT_VINFO_RELATED_STMT (prev_phi_info) = new_phi;
6152 FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
6154 if (slp_node)
6155 reduc_def = PHI_RESULT (phis[i]);
6156 else
6158 if (!single_defuse_cycle || j == 0)
6159 reduc_def = PHI_RESULT (new_phi);
6162 def1 = ((op_type == ternary_op)
6163 ? vec_oprnds1[i] : NULL);
6164 if (op_type == binary_op)
6166 if (reduc_index == 0)
6167 expr = build2 (code, vectype_out, reduc_def, def0);
6168 else
6169 expr = build2 (code, vectype_out, def0, reduc_def);
6171 else
6173 if (reduc_index == 0)
6174 expr = build3 (code, vectype_out, reduc_def, def0, def1);
6175 else
6177 if (reduc_index == 1)
6178 expr = build3 (code, vectype_out, def0, reduc_def, def1);
6179 else
6180 expr = build3 (code, vectype_out, def0, def1, reduc_def);
6184 new_stmt = gimple_build_assign (vec_dest, expr);
6185 new_temp = make_ssa_name (vec_dest, new_stmt);
6186 gimple_assign_set_lhs (new_stmt, new_temp);
6187 vect_finish_stmt_generation (stmt, new_stmt, gsi);
6189 if (slp_node)
6191 SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt);
6192 vect_defs.quick_push (new_temp);
6194 else
6195 vect_defs[0] = new_temp;
6198 if (slp_node)
6199 continue;
6201 if (j == 0)
6202 STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt;
6203 else
6204 STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt;
6206 prev_stmt_info = vinfo_for_stmt (new_stmt);
6207 prev_phi_info = vinfo_for_stmt (new_phi);
6210 tree indx_before_incr, indx_after_incr, cond_name = NULL;
6212 /* Finalize the reduction-phi (set its arguments) and create the
6213 epilog reduction code. */
6214 if ((!single_defuse_cycle || code == COND_EXPR) && !slp_node)
6216 new_temp = gimple_assign_lhs (*vec_stmt);
6217 vect_defs[0] = new_temp;
6219 /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
6220 which is updated with the current index of the loop for every match of
6221 the original loop's cond_expr (VEC_STMT). This results in a vector
6222 containing the last time the condition passed for that vector lane.
6223 The first match will be a 1 to allow 0 to be used for non-matching
6224 indexes. If there are no matches at all then the vector will be all
6225 zeroes. */
6226 if (STMT_VINFO_VEC_REDUCTION_TYPE (stmt_info) == COND_REDUCTION)
6228 int nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
6229 int k;
6231 gcc_assert (gimple_assign_rhs_code (*vec_stmt) == VEC_COND_EXPR);
6233 /* First we create a simple vector induction variable which starts
6234 with the values {1,2,3,...} (SERIES_VECT) and increments by the
6235 vector size (STEP). */
6237 /* Create a {1,2,3,...} vector. */
6238 tree *vtemp = XALLOCAVEC (tree, nunits_out);
6239 for (k = 0; k < nunits_out; ++k)
6240 vtemp[k] = build_int_cst (cr_index_scalar_type, k + 1);
6241 tree series_vect = build_vector (cr_index_vector_type, vtemp);
6243 /* Create a vector of the step value. */
6244 tree step = build_int_cst (cr_index_scalar_type, nunits_out);
6245 tree vec_step = build_vector_from_val (cr_index_vector_type, step);
6247 /* Create an induction variable. */
6248 gimple_stmt_iterator incr_gsi;
6249 bool insert_after;
6250 standard_iv_increment_position (loop, &incr_gsi, &insert_after);
6251 create_iv (series_vect, vec_step, NULL_TREE, loop, &incr_gsi,
6252 insert_after, &indx_before_incr, &indx_after_incr);
6254 /* Next create a new phi node vector (NEW_PHI_TREE) which starts
6255 filled with zeros (VEC_ZERO). */
6257 /* Create a vector of 0s. */
6258 tree zero = build_zero_cst (cr_index_scalar_type);
6259 tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
6261 /* Create a vector phi node. */
6262 tree new_phi_tree = make_ssa_name (cr_index_vector_type);
6263 new_phi = create_phi_node (new_phi_tree, loop->header);
6264 set_vinfo_for_stmt (new_phi,
6265 new_stmt_vec_info (new_phi, loop_vinfo));
6266 add_phi_arg (new_phi, vec_zero, loop_preheader_edge (loop),
6267 UNKNOWN_LOCATION);
6269 /* Now take the condition from the loops original cond_expr
6270 (VEC_STMT) and produce a new cond_expr (INDEX_COND_EXPR) which for
6271 every match uses values from the induction variable
6272 (INDEX_BEFORE_INCR) otherwise uses values from the phi node
6273 (NEW_PHI_TREE).
6274 Finally, we update the phi (NEW_PHI_TREE) to take the value of
6275 the new cond_expr (INDEX_COND_EXPR). */
6277 /* Duplicate the condition from vec_stmt. */
6278 tree ccompare = unshare_expr (gimple_assign_rhs1 (*vec_stmt));
6280 /* Create a conditional, where the condition is taken from vec_stmt
6281 (CCOMPARE), then is the induction index (INDEX_BEFORE_INCR) and
6282 else is the phi (NEW_PHI_TREE). */
6283 tree index_cond_expr = build3 (VEC_COND_EXPR, cr_index_vector_type,
6284 ccompare, indx_before_incr,
6285 new_phi_tree);
6286 cond_name = make_ssa_name (cr_index_vector_type);
6287 gimple *index_condition = gimple_build_assign (cond_name,
6288 index_cond_expr);
6289 gsi_insert_before (&incr_gsi, index_condition, GSI_SAME_STMT);
6290 stmt_vec_info index_vec_info = new_stmt_vec_info (index_condition,
6291 loop_vinfo);
6292 STMT_VINFO_VECTYPE (index_vec_info) = cr_index_vector_type;
6293 set_vinfo_for_stmt (index_condition, index_vec_info);
6295 /* Update the phi with the vec cond. */
6296 add_phi_arg (new_phi, cond_name, loop_latch_edge (loop),
6297 UNKNOWN_LOCATION);
6301 vect_create_epilog_for_reduction (vect_defs, stmt, epilog_copies,
6302 epilog_reduc_code, phis, reduc_index,
6303 double_reduc, slp_node, cond_name);
6305 return true;
6308 /* Function vect_min_worthwhile_factor.
6310 For a loop where we could vectorize the operation indicated by CODE,
6311 return the minimum vectorization factor that makes it worthwhile
6312 to use generic vectors. */
6314 vect_min_worthwhile_factor (enum tree_code code)
6316 switch (code)
6318 case PLUS_EXPR:
6319 case MINUS_EXPR:
6320 case NEGATE_EXPR:
6321 return 4;
6323 case BIT_AND_EXPR:
6324 case BIT_IOR_EXPR:
6325 case BIT_XOR_EXPR:
6326 case BIT_NOT_EXPR:
6327 return 2;
6329 default:
6330 return INT_MAX;
6335 /* Function vectorizable_induction
6337 Check if PHI performs an induction computation that can be vectorized.
6338 If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
6339 phi to replace it, put it in VEC_STMT, and add it to the same basic block.
6340 Return FALSE if not a vectorizable STMT, TRUE otherwise. */
6342 bool
6343 vectorizable_induction (gimple *phi,
6344 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6345 gimple **vec_stmt)
6347 stmt_vec_info stmt_info = vinfo_for_stmt (phi);
6348 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6349 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6350 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6351 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6352 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6353 tree vec_def;
6355 gcc_assert (ncopies >= 1);
6356 /* FORNOW. These restrictions should be relaxed. */
6357 if (nested_in_vect_loop_p (loop, phi))
6359 imm_use_iterator imm_iter;
6360 use_operand_p use_p;
6361 gimple *exit_phi;
6362 edge latch_e;
6363 tree loop_arg;
6365 if (ncopies > 1)
6367 if (dump_enabled_p ())
6368 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6369 "multiple types in nested loop.\n");
6370 return false;
6373 exit_phi = NULL;
6374 latch_e = loop_latch_edge (loop->inner);
6375 loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
6376 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
6378 gimple *use_stmt = USE_STMT (use_p);
6379 if (is_gimple_debug (use_stmt))
6380 continue;
6382 if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
6384 exit_phi = use_stmt;
6385 break;
6388 if (exit_phi)
6390 stmt_vec_info exit_phi_vinfo = vinfo_for_stmt (exit_phi);
6391 if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
6392 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
6394 if (dump_enabled_p ())
6395 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
6396 "inner-loop induction only used outside "
6397 "of the outer vectorized loop.\n");
6398 return false;
6403 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6404 return false;
6406 /* FORNOW: SLP not supported. */
6407 if (STMT_SLP_TYPE (stmt_info))
6408 return false;
6410 gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def);
6412 if (gimple_code (phi) != GIMPLE_PHI)
6413 return false;
6415 if (!vec_stmt) /* transformation not required. */
6417 STMT_VINFO_TYPE (stmt_info) = induc_vec_info_type;
6418 if (dump_enabled_p ())
6419 dump_printf_loc (MSG_NOTE, vect_location,
6420 "=== vectorizable_induction ===\n");
6421 vect_model_induction_cost (stmt_info, ncopies);
6422 return true;
6425 /** Transform. **/
6427 if (dump_enabled_p ())
6428 dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
6430 vec_def = get_initial_def_for_induction (phi);
6431 *vec_stmt = SSA_NAME_DEF_STMT (vec_def);
6432 return true;
6435 /* Function vectorizable_live_operation.
6437 STMT computes a value that is used outside the loop. Check if
6438 it can be supported. */
6440 bool
6441 vectorizable_live_operation (gimple *stmt,
6442 gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
6443 slp_tree slp_node, int slp_index,
6444 gimple **vec_stmt)
6446 stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
6447 loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
6448 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6449 imm_use_iterator imm_iter;
6450 tree lhs, lhs_type, bitsize, vec_bitsize;
6451 tree vectype = STMT_VINFO_VECTYPE (stmt_info);
6452 int nunits = TYPE_VECTOR_SUBPARTS (vectype);
6453 int ncopies = LOOP_VINFO_VECT_FACTOR (loop_vinfo) / nunits;
6454 gimple *use_stmt;
6455 auto_vec<tree> vec_oprnds;
6457 gcc_assert (STMT_VINFO_LIVE_P (stmt_info));
6459 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def)
6460 return false;
6462 /* FORNOW. CHECKME. */
6463 if (nested_in_vect_loop_p (loop, stmt))
6464 return false;
6466 /* If STMT is not relevant and it is a simple assignment and its inputs are
6467 invariant then it can remain in place, unvectorized. The original last
6468 scalar value that it computes will be used. */
6469 if (!STMT_VINFO_RELEVANT_P (stmt_info))
6471 gcc_assert (is_simple_and_all_uses_invariant (stmt, loop_vinfo));
6472 if (dump_enabled_p ())
6473 dump_printf_loc (MSG_NOTE, vect_location,
6474 "statement is simple and uses invariant. Leaving in "
6475 "place.\n");
6476 return true;
6479 if (!vec_stmt)
6480 /* No transformation required. */
6481 return true;
6483 /* If stmt has a related stmt, then use that for getting the lhs. */
6484 if (is_pattern_stmt_p (stmt_info))
6485 stmt = STMT_VINFO_RELATED_STMT (stmt_info);
6487 lhs = (is_a <gphi *> (stmt)) ? gimple_phi_result (stmt)
6488 : gimple_get_lhs (stmt);
6489 lhs_type = TREE_TYPE (lhs);
6491 /* Find all uses of STMT outside the loop - there should be at least one. */
6492 auto_vec<gimple *, 4> worklist;
6493 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
6494 if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt))
6495 && !is_gimple_debug (use_stmt))
6496 worklist.safe_push (use_stmt);
6497 gcc_assert (worklist.length () >= 1);
6499 bitsize = TYPE_SIZE (TREE_TYPE (vectype));
6500 vec_bitsize = TYPE_SIZE (vectype);
6502 /* Get the vectorized lhs of STMT and the lane to use (counted in bits). */
6503 tree vec_lhs, bitstart;
6504 if (slp_node)
6506 gcc_assert (slp_index >= 0);
6508 int num_scalar = SLP_TREE_SCALAR_STMTS (slp_node).length ();
6509 int num_vec = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
6511 /* Get the last occurrence of the scalar index from the concatenation of
6512 all the slp vectors. Calculate which slp vector it is and the index
6513 within. */
6514 int pos = (num_vec * nunits) - num_scalar + slp_index;
6515 int vec_entry = pos / nunits;
6516 int vec_index = pos % nunits;
6518 /* Get the correct slp vectorized stmt. */
6519 vec_lhs = gimple_get_lhs (SLP_TREE_VEC_STMTS (slp_node)[vec_entry]);
6521 /* Get entry to use. */
6522 bitstart = build_int_cst (unsigned_type_node, vec_index);
6523 bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
6525 else
6527 enum vect_def_type dt = STMT_VINFO_DEF_TYPE (stmt_info);
6528 vec_lhs = vect_get_vec_def_for_operand_1 (stmt, dt);
6530 /* For multiple copies, get the last copy. */
6531 for (int i = 1; i < ncopies; ++i)
6532 vec_lhs = vect_get_vec_def_for_stmt_copy (vect_unknown_def_type,
6533 vec_lhs);
6535 /* Get the last lane in the vector. */
6536 bitstart = int_const_binop (MINUS_EXPR, vec_bitsize, bitsize);
6539 /* Create a new vectorized stmt for the uses of STMT and insert outside the
6540 loop. */
6541 gimple_seq stmts = NULL;
6542 tree new_tree = build3 (BIT_FIELD_REF, TREE_TYPE (vectype), vec_lhs, bitsize,
6543 bitstart);
6544 new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree), &stmts,
6545 true, NULL_TREE);
6546 if (stmts)
6547 gsi_insert_seq_on_edge_immediate (single_exit (loop), stmts);
6549 /* Replace all uses of the USE_STMT in the worklist with the newly inserted
6550 statement. */
6551 while (!worklist.is_empty ())
6553 use_stmt = worklist.pop ();
6554 replace_uses_by (gimple_phi_result (use_stmt), new_tree);
6555 update_stmt (use_stmt);
6558 return true;
6561 /* Kill any debug uses outside LOOP of SSA names defined in STMT. */
6563 static void
6564 vect_loop_kill_debug_uses (struct loop *loop, gimple *stmt)
6566 ssa_op_iter op_iter;
6567 imm_use_iterator imm_iter;
6568 def_operand_p def_p;
6569 gimple *ustmt;
6571 FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt, op_iter, SSA_OP_DEF)
6573 FOR_EACH_IMM_USE_STMT (ustmt, imm_iter, DEF_FROM_PTR (def_p))
6575 basic_block bb;
6577 if (!is_gimple_debug (ustmt))
6578 continue;
6580 bb = gimple_bb (ustmt);
6582 if (!flow_bb_inside_loop_p (loop, bb))
6584 if (gimple_debug_bind_p (ustmt))
6586 if (dump_enabled_p ())
6587 dump_printf_loc (MSG_NOTE, vect_location,
6588 "killing debug use\n");
6590 gimple_debug_bind_reset_value (ustmt);
6591 update_stmt (ustmt);
6593 else
6594 gcc_unreachable ();
6601 /* This function builds ni_name = number of iterations. Statements
6602 are emitted on the loop preheader edge. */
6604 static tree
6605 vect_build_loop_niters (loop_vec_info loop_vinfo)
6607 tree ni = unshare_expr (LOOP_VINFO_NITERS (loop_vinfo));
6608 if (TREE_CODE (ni) == INTEGER_CST)
6609 return ni;
6610 else
6612 tree ni_name, var;
6613 gimple_seq stmts = NULL;
6614 edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
6616 var = create_tmp_var (TREE_TYPE (ni), "niters");
6617 ni_name = force_gimple_operand (ni, &stmts, false, var);
6618 if (stmts)
6619 gsi_insert_seq_on_edge_immediate (pe, stmts);
6621 return ni_name;
6626 /* This function generates the following statements:
6628 ni_name = number of iterations loop executes
6629 ratio = ni_name / vf
6630 ratio_mult_vf_name = ratio * vf
6632 and places them on the loop preheader edge. */
6634 static void
6635 vect_generate_tmps_on_preheader (loop_vec_info loop_vinfo,
6636 tree ni_name,
6637 tree *ratio_mult_vf_name_ptr,
6638 tree *ratio_name_ptr)
6640 tree ni_minus_gap_name;
6641 tree var;
6642 tree ratio_name;
6643 tree ratio_mult_vf_name;
6644 int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6645 edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
6646 tree log_vf;
6648 log_vf = build_int_cst (TREE_TYPE (ni_name), exact_log2 (vf));
6650 /* If epilogue loop is required because of data accesses with gaps, we
6651 subtract one iteration from the total number of iterations here for
6652 correct calculation of RATIO. */
6653 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
6655 ni_minus_gap_name = fold_build2 (MINUS_EXPR, TREE_TYPE (ni_name),
6656 ni_name,
6657 build_one_cst (TREE_TYPE (ni_name)));
6658 if (!is_gimple_val (ni_minus_gap_name))
6660 var = create_tmp_var (TREE_TYPE (ni_name), "ni_gap");
6661 gimple *stmts = NULL;
6662 ni_minus_gap_name = force_gimple_operand (ni_minus_gap_name, &stmts,
6663 true, var);
6664 gsi_insert_seq_on_edge_immediate (pe, stmts);
6667 else
6668 ni_minus_gap_name = ni_name;
6670 /* Create: ratio = ni >> log2(vf) */
6671 /* ??? As we have ni == number of latch executions + 1, ni could
6672 have overflown to zero. So avoid computing ratio based on ni
6673 but compute it using the fact that we know ratio will be at least
6674 one, thus via (ni - vf) >> log2(vf) + 1. */
6675 ratio_name
6676 = fold_build2 (PLUS_EXPR, TREE_TYPE (ni_name),
6677 fold_build2 (RSHIFT_EXPR, TREE_TYPE (ni_name),
6678 fold_build2 (MINUS_EXPR, TREE_TYPE (ni_name),
6679 ni_minus_gap_name,
6680 build_int_cst
6681 (TREE_TYPE (ni_name), vf)),
6682 log_vf),
6683 build_int_cst (TREE_TYPE (ni_name), 1));
6684 if (!is_gimple_val (ratio_name))
6686 var = create_tmp_var (TREE_TYPE (ni_name), "bnd");
6687 gimple *stmts = NULL;
6688 ratio_name = force_gimple_operand (ratio_name, &stmts, true, var);
6689 gsi_insert_seq_on_edge_immediate (pe, stmts);
6691 *ratio_name_ptr = ratio_name;
6693 /* Create: ratio_mult_vf = ratio << log2 (vf). */
6695 if (ratio_mult_vf_name_ptr)
6697 ratio_mult_vf_name = fold_build2 (LSHIFT_EXPR, TREE_TYPE (ratio_name),
6698 ratio_name, log_vf);
6699 if (!is_gimple_val (ratio_mult_vf_name))
6701 var = create_tmp_var (TREE_TYPE (ni_name), "ratio_mult_vf");
6702 gimple *stmts = NULL;
6703 ratio_mult_vf_name = force_gimple_operand (ratio_mult_vf_name, &stmts,
6704 true, var);
6705 gsi_insert_seq_on_edge_immediate (pe, stmts);
6707 *ratio_mult_vf_name_ptr = ratio_mult_vf_name;
6710 return;
6714 /* Function vect_transform_loop.
6716 The analysis phase has determined that the loop is vectorizable.
6717 Vectorize the loop - created vectorized stmts to replace the scalar
6718 stmts in the loop, and update the loop exit condition. */
6720 void
6721 vect_transform_loop (loop_vec_info loop_vinfo)
6723 struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
6724 basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
6725 int nbbs = loop->num_nodes;
6726 int i;
6727 tree ratio = NULL;
6728 int vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
6729 bool grouped_store;
6730 bool slp_scheduled = false;
6731 gimple *stmt, *pattern_stmt;
6732 gimple_seq pattern_def_seq = NULL;
6733 gimple_stmt_iterator pattern_def_si = gsi_none ();
6734 bool transform_pattern_stmt = false;
6735 bool check_profitability = false;
6736 int th;
6737 /* Record number of iterations before we started tampering with the profile. */
6738 gcov_type expected_iterations = expected_loop_iterations_unbounded (loop);
6740 if (dump_enabled_p ())
6741 dump_printf_loc (MSG_NOTE, vect_location, "=== vec_transform_loop ===\n");
6743 /* If profile is inprecise, we have chance to fix it up. */
6744 if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6745 expected_iterations = LOOP_VINFO_INT_NITERS (loop_vinfo);
6747 /* Use the more conservative vectorization threshold. If the number
6748 of iterations is constant assume the cost check has been performed
6749 by our caller. If the threshold makes all loops profitable that
6750 run at least the vectorization factor number of times checking
6751 is pointless, too. */
6752 th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
6753 if (th >= LOOP_VINFO_VECT_FACTOR (loop_vinfo) - 1
6754 && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6756 if (dump_enabled_p ())
6757 dump_printf_loc (MSG_NOTE, vect_location,
6758 "Profitability threshold is %d loop iterations.\n",
6759 th);
6760 check_profitability = true;
6763 /* Make sure there exists a single-predecessor exit bb. Do this before
6764 versioning. */
6765 edge e = single_exit (loop);
6766 if (! single_pred_p (e->dest))
6768 split_loop_exit_edge (e);
6769 if (dump_enabled_p ())
6770 dump_printf (MSG_NOTE, "split exit edge\n");
6773 /* Version the loop first, if required, so the profitability check
6774 comes first. */
6776 if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
6778 vect_loop_versioning (loop_vinfo, th, check_profitability);
6779 check_profitability = false;
6782 /* Make sure there exists a single-predecessor exit bb also on the
6783 scalar loop copy. Do this after versioning but before peeling
6784 so CFG structure is fine for both scalar and if-converted loop
6785 to make slpeel_duplicate_current_defs_from_edges face matched
6786 loop closed PHI nodes on the exit. */
6787 if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
6789 e = single_exit (LOOP_VINFO_SCALAR_LOOP (loop_vinfo));
6790 if (! single_pred_p (e->dest))
6792 split_loop_exit_edge (e);
6793 if (dump_enabled_p ())
6794 dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
6798 tree ni_name = vect_build_loop_niters (loop_vinfo);
6799 LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = ni_name;
6801 /* Peel the loop if there are data refs with unknown alignment.
6802 Only one data ref with unknown store is allowed. */
6804 if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
6806 vect_do_peeling_for_alignment (loop_vinfo, ni_name,
6807 th, check_profitability);
6808 check_profitability = false;
6809 /* The above adjusts LOOP_VINFO_NITERS, so cause ni_name to
6810 be re-computed. */
6811 ni_name = NULL_TREE;
6814 /* If the loop has a symbolic number of iterations 'n' (i.e. it's not a
6815 compile time constant), or it is a constant that doesn't divide by the
6816 vectorization factor, then an epilog loop needs to be created.
6817 We therefore duplicate the loop: the original loop will be vectorized,
6818 and will compute the first (n/VF) iterations. The second copy of the loop
6819 will remain scalar and will compute the remaining (n%VF) iterations.
6820 (VF is the vectorization factor). */
6822 if (LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
6823 || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
6825 tree ratio_mult_vf;
6826 if (!ni_name)
6827 ni_name = vect_build_loop_niters (loop_vinfo);
6828 vect_generate_tmps_on_preheader (loop_vinfo, ni_name, &ratio_mult_vf,
6829 &ratio);
6830 vect_do_peeling_for_loop_bound (loop_vinfo, ni_name, ratio_mult_vf,
6831 th, check_profitability);
6833 else if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
6834 ratio = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
6835 LOOP_VINFO_INT_NITERS (loop_vinfo) / vectorization_factor);
6836 else
6838 if (!ni_name)
6839 ni_name = vect_build_loop_niters (loop_vinfo);
6840 vect_generate_tmps_on_preheader (loop_vinfo, ni_name, NULL, &ratio);
6843 /* 1) Make sure the loop header has exactly two entries
6844 2) Make sure we have a preheader basic block. */
6846 gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
6848 split_edge (loop_preheader_edge (loop));
6850 /* FORNOW: the vectorizer supports only loops which body consist
6851 of one basic block (header + empty latch). When the vectorizer will
6852 support more involved loop forms, the order by which the BBs are
6853 traversed need to be reconsidered. */
6855 for (i = 0; i < nbbs; i++)
6857 basic_block bb = bbs[i];
6858 stmt_vec_info stmt_info;
6860 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
6861 gsi_next (&si))
6863 gphi *phi = si.phi ();
6864 if (dump_enabled_p ())
6866 dump_printf_loc (MSG_NOTE, vect_location,
6867 "------>vectorizing phi: ");
6868 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, phi, 0);
6870 stmt_info = vinfo_for_stmt (phi);
6871 if (!stmt_info)
6872 continue;
6874 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6875 vect_loop_kill_debug_uses (loop, phi);
6877 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6878 && !STMT_VINFO_LIVE_P (stmt_info))
6879 continue;
6881 if (STMT_VINFO_VECTYPE (stmt_info)
6882 && (TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info))
6883 != (unsigned HOST_WIDE_INT) vectorization_factor)
6884 && dump_enabled_p ())
6885 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
6887 if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_induction_def)
6889 if (dump_enabled_p ())
6890 dump_printf_loc (MSG_NOTE, vect_location, "transform phi.\n");
6891 vect_transform_stmt (phi, NULL, NULL, NULL, NULL);
6895 pattern_stmt = NULL;
6896 for (gimple_stmt_iterator si = gsi_start_bb (bb);
6897 !gsi_end_p (si) || transform_pattern_stmt;)
6899 bool is_store;
6901 if (transform_pattern_stmt)
6902 stmt = pattern_stmt;
6903 else
6905 stmt = gsi_stmt (si);
6906 /* During vectorization remove existing clobber stmts. */
6907 if (gimple_clobber_p (stmt))
6909 unlink_stmt_vdef (stmt);
6910 gsi_remove (&si, true);
6911 release_defs (stmt);
6912 continue;
6916 if (dump_enabled_p ())
6918 dump_printf_loc (MSG_NOTE, vect_location,
6919 "------>vectorizing statement: ");
6920 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
6923 stmt_info = vinfo_for_stmt (stmt);
6925 /* vector stmts created in the outer-loop during vectorization of
6926 stmts in an inner-loop may not have a stmt_info, and do not
6927 need to be vectorized. */
6928 if (!stmt_info)
6930 gsi_next (&si);
6931 continue;
6934 if (MAY_HAVE_DEBUG_STMTS && !STMT_VINFO_LIVE_P (stmt_info))
6935 vect_loop_kill_debug_uses (loop, stmt);
6937 if (!STMT_VINFO_RELEVANT_P (stmt_info)
6938 && !STMT_VINFO_LIVE_P (stmt_info))
6940 if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6941 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6942 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6943 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6945 stmt = pattern_stmt;
6946 stmt_info = vinfo_for_stmt (stmt);
6948 else
6950 gsi_next (&si);
6951 continue;
6954 else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
6955 && (pattern_stmt = STMT_VINFO_RELATED_STMT (stmt_info))
6956 && (STMT_VINFO_RELEVANT_P (vinfo_for_stmt (pattern_stmt))
6957 || STMT_VINFO_LIVE_P (vinfo_for_stmt (pattern_stmt))))
6958 transform_pattern_stmt = true;
6960 /* If pattern statement has def stmts, vectorize them too. */
6961 if (is_pattern_stmt_p (stmt_info))
6963 if (pattern_def_seq == NULL)
6965 pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info);
6966 pattern_def_si = gsi_start (pattern_def_seq);
6968 else if (!gsi_end_p (pattern_def_si))
6969 gsi_next (&pattern_def_si);
6970 if (pattern_def_seq != NULL)
6972 gimple *pattern_def_stmt = NULL;
6973 stmt_vec_info pattern_def_stmt_info = NULL;
6975 while (!gsi_end_p (pattern_def_si))
6977 pattern_def_stmt = gsi_stmt (pattern_def_si);
6978 pattern_def_stmt_info
6979 = vinfo_for_stmt (pattern_def_stmt);
6980 if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
6981 || STMT_VINFO_LIVE_P (pattern_def_stmt_info))
6982 break;
6983 gsi_next (&pattern_def_si);
6986 if (!gsi_end_p (pattern_def_si))
6988 if (dump_enabled_p ())
6990 dump_printf_loc (MSG_NOTE, vect_location,
6991 "==> vectorizing pattern def "
6992 "stmt: ");
6993 dump_gimple_stmt (MSG_NOTE, TDF_SLIM,
6994 pattern_def_stmt, 0);
6997 stmt = pattern_def_stmt;
6998 stmt_info = pattern_def_stmt_info;
7000 else
7002 pattern_def_si = gsi_none ();
7003 transform_pattern_stmt = false;
7006 else
7007 transform_pattern_stmt = false;
7010 if (STMT_VINFO_VECTYPE (stmt_info))
7012 unsigned int nunits
7013 = (unsigned int)
7014 TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
7015 if (!STMT_SLP_TYPE (stmt_info)
7016 && nunits != (unsigned int) vectorization_factor
7017 && dump_enabled_p ())
7018 /* For SLP VF is set according to unrolling factor, and not
7019 to vector size, hence for SLP this print is not valid. */
7020 dump_printf_loc (MSG_NOTE, vect_location, "multiple-types.\n");
7023 /* SLP. Schedule all the SLP instances when the first SLP stmt is
7024 reached. */
7025 if (STMT_SLP_TYPE (stmt_info))
7027 if (!slp_scheduled)
7029 slp_scheduled = true;
7031 if (dump_enabled_p ())
7032 dump_printf_loc (MSG_NOTE, vect_location,
7033 "=== scheduling SLP instances ===\n");
7035 vect_schedule_slp (loop_vinfo);
7038 /* Hybrid SLP stmts must be vectorized in addition to SLP. */
7039 if (!vinfo_for_stmt (stmt) || PURE_SLP_STMT (stmt_info))
7041 if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7043 pattern_def_seq = NULL;
7044 gsi_next (&si);
7046 continue;
7050 /* -------- vectorize statement ------------ */
7051 if (dump_enabled_p ())
7052 dump_printf_loc (MSG_NOTE, vect_location, "transform statement.\n");
7054 grouped_store = false;
7055 is_store = vect_transform_stmt (stmt, &si, &grouped_store, NULL, NULL);
7056 if (is_store)
7058 if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
7060 /* Interleaving. If IS_STORE is TRUE, the vectorization of the
7061 interleaving chain was completed - free all the stores in
7062 the chain. */
7063 gsi_next (&si);
7064 vect_remove_stores (GROUP_FIRST_ELEMENT (stmt_info));
7066 else
7068 /* Free the attached stmt_vec_info and remove the stmt. */
7069 gimple *store = gsi_stmt (si);
7070 free_stmt_vec_info (store);
7071 unlink_stmt_vdef (store);
7072 gsi_remove (&si, true);
7073 release_defs (store);
7076 /* Stores can only appear at the end of pattern statements. */
7077 gcc_assert (!transform_pattern_stmt);
7078 pattern_def_seq = NULL;
7080 else if (!transform_pattern_stmt && gsi_end_p (pattern_def_si))
7082 pattern_def_seq = NULL;
7083 gsi_next (&si);
7085 } /* stmts in BB */
7086 } /* BBs in loop */
7088 slpeel_make_loop_iterate_ntimes (loop, ratio);
7090 /* Reduce loop iterations by the vectorization factor. */
7091 scale_loop_profile (loop, GCOV_COMPUTE_SCALE (1, vectorization_factor),
7092 expected_iterations / vectorization_factor);
7093 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
7095 if (loop->nb_iterations_upper_bound != 0)
7096 loop->nb_iterations_upper_bound = loop->nb_iterations_upper_bound - 1;
7097 if (loop->nb_iterations_likely_upper_bound != 0)
7098 loop->nb_iterations_likely_upper_bound
7099 = loop->nb_iterations_likely_upper_bound - 1;
7101 loop->nb_iterations_upper_bound
7102 = wi::udiv_floor (loop->nb_iterations_upper_bound + 1,
7103 vectorization_factor) - 1;
7104 loop->nb_iterations_likely_upper_bound
7105 = wi::udiv_floor (loop->nb_iterations_likely_upper_bound + 1,
7106 vectorization_factor) - 1;
7108 if (loop->any_estimate)
7110 loop->nb_iterations_estimate
7111 = wi::udiv_floor (loop->nb_iterations_estimate, vectorization_factor);
7112 if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
7113 && loop->nb_iterations_estimate != 0)
7114 loop->nb_iterations_estimate = loop->nb_iterations_estimate - 1;
7117 if (dump_enabled_p ())
7119 dump_printf_loc (MSG_NOTE, vect_location,
7120 "LOOP VECTORIZED\n");
7121 if (loop->inner)
7122 dump_printf_loc (MSG_NOTE, vect_location,
7123 "OUTER LOOP VECTORIZED\n");
7124 dump_printf (MSG_NOTE, "\n");
7127 /* Free SLP instances here because otherwise stmt reference counting
7128 won't work. */
7129 slp_instance instance;
7130 FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
7131 vect_free_slp_instance (instance);
7132 LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
7133 /* Clear-up safelen field since its value is invalid after vectorization
7134 since vectorized loop can have loop-carried dependencies. */
7135 loop->safelen = 0;
7138 /* The code below is trying to perform simple optimization - revert
7139 if-conversion for masked stores, i.e. if the mask of a store is zero
7140 do not perform it and all stored value producers also if possible.
7141 For example,
7142 for (i=0; i<n; i++)
7143 if (c[i])
7145 p1[i] += 1;
7146 p2[i] = p3[i] +2;
7148 this transformation will produce the following semi-hammock:
7150 if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
7152 vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
7153 vect__12.22_172 = vect__11.19_170 + vect_cst__171;
7154 MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
7155 vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
7156 vect__19.28_184 = vect__18.25_182 + vect_cst__183;
7157 MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
7161 void
7162 optimize_mask_stores (struct loop *loop)
7164 basic_block *bbs = get_loop_body (loop);
7165 unsigned nbbs = loop->num_nodes;
7166 unsigned i;
7167 basic_block bb;
7168 gimple_stmt_iterator gsi;
7169 gimple *stmt;
7170 auto_vec<gimple *> worklist;
7172 vect_location = find_loop_location (loop);
7173 /* Pick up all masked stores in loop if any. */
7174 for (i = 0; i < nbbs; i++)
7176 bb = bbs[i];
7177 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7178 gsi_next (&gsi))
7180 stmt = gsi_stmt (gsi);
7181 if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
7182 worklist.safe_push (stmt);
7186 free (bbs);
7187 if (worklist.is_empty ())
7188 return;
7190 /* Loop has masked stores. */
7191 while (!worklist.is_empty ())
7193 gimple *last, *last_store;
7194 edge e, efalse;
7195 tree mask;
7196 basic_block store_bb, join_bb;
7197 gimple_stmt_iterator gsi_to;
7198 tree vdef, new_vdef;
7199 gphi *phi;
7200 tree vectype;
7201 tree zero;
7203 last = worklist.pop ();
7204 mask = gimple_call_arg (last, 2);
7205 bb = gimple_bb (last);
7206 /* Create new bb. */
7207 e = split_block (bb, last);
7208 join_bb = e->dest;
7209 store_bb = create_empty_bb (bb);
7210 add_bb_to_loop (store_bb, loop);
7211 e->flags = EDGE_TRUE_VALUE;
7212 efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
7213 /* Put STORE_BB to likely part. */
7214 efalse->probability = PROB_UNLIKELY;
7215 store_bb->frequency = PROB_ALWAYS - EDGE_FREQUENCY (efalse);
7216 make_edge (store_bb, join_bb, EDGE_FALLTHRU);
7217 if (dom_info_available_p (CDI_DOMINATORS))
7218 set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
7219 if (dump_enabled_p ())
7220 dump_printf_loc (MSG_NOTE, vect_location,
7221 "Create new block %d to sink mask stores.",
7222 store_bb->index);
7223 /* Create vector comparison with boolean result. */
7224 vectype = TREE_TYPE (mask);
7225 zero = build_zero_cst (vectype);
7226 stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
7227 gsi = gsi_last_bb (bb);
7228 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
7229 /* Create new PHI node for vdef of the last masked store:
7230 .MEM_2 = VDEF <.MEM_1>
7231 will be converted to
7232 .MEM.3 = VDEF <.MEM_1>
7233 and new PHI node will be created in join bb
7234 .MEM_2 = PHI <.MEM_1, .MEM_3>
7236 vdef = gimple_vdef (last);
7237 new_vdef = make_ssa_name (gimple_vop (cfun), last);
7238 gimple_set_vdef (last, new_vdef);
7239 phi = create_phi_node (vdef, join_bb);
7240 add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
7242 /* Put all masked stores with the same mask to STORE_BB if possible. */
7243 while (true)
7245 gimple_stmt_iterator gsi_from;
7246 gimple *stmt1 = NULL;
7248 /* Move masked store to STORE_BB. */
7249 last_store = last;
7250 gsi = gsi_for_stmt (last);
7251 gsi_from = gsi;
7252 /* Shift GSI to the previous stmt for further traversal. */
7253 gsi_prev (&gsi);
7254 gsi_to = gsi_start_bb (store_bb);
7255 gsi_move_before (&gsi_from, &gsi_to);
7256 /* Setup GSI_TO to the non-empty block start. */
7257 gsi_to = gsi_start_bb (store_bb);
7258 if (dump_enabled_p ())
7260 dump_printf_loc (MSG_NOTE, vect_location,
7261 "Move stmt to created bb\n");
7262 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, last, 0);
7264 /* Move all stored value producers if possible. */
7265 while (!gsi_end_p (gsi))
7267 tree lhs;
7268 imm_use_iterator imm_iter;
7269 use_operand_p use_p;
7270 bool res;
7272 /* Skip debug statements. */
7273 if (is_gimple_debug (gsi_stmt (gsi)))
7275 gsi_prev (&gsi);
7276 continue;
7278 stmt1 = gsi_stmt (gsi);
7279 /* Do not consider statements writing to memory or having
7280 volatile operand. */
7281 if (gimple_vdef (stmt1)
7282 || gimple_has_volatile_ops (stmt1))
7283 break;
7284 gsi_from = gsi;
7285 gsi_prev (&gsi);
7286 lhs = gimple_get_lhs (stmt1);
7287 if (!lhs)
7288 break;
7290 /* LHS of vectorized stmt must be SSA_NAME. */
7291 if (TREE_CODE (lhs) != SSA_NAME)
7292 break;
7294 if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
7296 /* Remove dead scalar statement. */
7297 if (has_zero_uses (lhs))
7299 gsi_remove (&gsi_from, true);
7300 continue;
7304 /* Check that LHS does not have uses outside of STORE_BB. */
7305 res = true;
7306 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
7308 gimple *use_stmt;
7309 use_stmt = USE_STMT (use_p);
7310 if (is_gimple_debug (use_stmt))
7311 continue;
7312 if (gimple_bb (use_stmt) != store_bb)
7314 res = false;
7315 break;
7318 if (!res)
7319 break;
7321 if (gimple_vuse (stmt1)
7322 && gimple_vuse (stmt1) != gimple_vuse (last_store))
7323 break;
7325 /* Can move STMT1 to STORE_BB. */
7326 if (dump_enabled_p ())
7328 dump_printf_loc (MSG_NOTE, vect_location,
7329 "Move stmt to created bb\n");
7330 dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt1, 0);
7332 gsi_move_before (&gsi_from, &gsi_to);
7333 /* Shift GSI_TO for further insertion. */
7334 gsi_prev (&gsi_to);
7336 /* Put other masked stores with the same mask to STORE_BB. */
7337 if (worklist.is_empty ()
7338 || gimple_call_arg (worklist.last (), 2) != mask
7339 || worklist.last () != stmt1)
7340 break;
7341 last = worklist.pop ();
7343 add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);