GCC Middle and Back End API Reference


static 
Function bb_in_loop_p Used as predicate for dfs order traversal of the loop bbs.
void destroy_loop_vec_info  (  ) 
Function destroy_loop_vec_info. Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the stmts in the loop.
We may have broken canonical form by moving a constant into RHS1 of a commutative op. Fix such occurrences.
Free stmt_vec_info.

static 
Function get_initial_def_for_induction Input: STMT  a stmt that performs an induction operation in the loop. IV_PHI  the initial value of the induction variable Output: Return a vector variable, initialized with the first VF values of the induction variable. E.g., for an iv with IV_PHI='X' and evolution S, for a vector of 4 units, we want to return: [X, X + S, X + 2*S, X + 3*S].
Is phi in an innerloop, while vectorizing an enclosing outerloop?
Find the first insertion point in the BB.
Create the vector that holds the initial_value of the induction.
iv_loop is nested in the loop to be vectorized. init_expr had already been created during vectorization of previous stmts. We obtain it from the STMT_VINFO_VEC_STMT of the defining stmt.
If the initial value is not of proper type, convert it.
iv_loop is the loop to be vectorized. Create: vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr)
Create: new_name_i = new_name + step_expr
Create a vector from [new_name_0, new_name_1, ..., new_name_nunits1]
Create the vector that holds the step of the induction.
iv_loop is nested in the loop to be vectorized. Generate: vec_step = [S, S, S, S]
iv_loop is the loop to be vectorized. Generate: vec_step = [VF*S, VF*S, VF*S, VF*S]
Create the following defuse cycle: loop prolog: vec_init = ... vec_step = ... loop: vec_iv = PHI <vec_init, vec_loop> ... STMT ... vec_loop = vec_iv + vec_step;
Create the inductionphi that defines the inductionoperand.
Create the iv update inside the loop
Set the arguments of the phi node:
In case that vectorization factor (VF) is bigger than the number of elements that we can fit in a vectype (nunits), we have to generate more than one vector stmt  i.e  we need to "unroll" the vector stmt by a factor VF/nunits. For more details see documentation in vectorizable_operation.
FORNOW. This restriction should be relaxed.
Create the vector that holds the step of the induction.
vec_i = vec_prev + vec_step
Find the loopclosed exitphi of the induction, and record the final vector of induction results:
FORNOW. Currently not supporting the case that an innerloop induction is not used in the outerloop (i.e. only outside the outerloop).
Function get_initial_def_for_reduction Input: STMT  a stmt that performs a reduction operation in the loop. INIT_VAL  the initial value of the reduction variable Output: ADJUSTMENT_DEF  a tree that holds a value to be added to the final result of the reduction (used for adjusting the epilog  see below). Return a vector variable, initialized according to the operation that STMT performs. This vector will be used as the initial value of the vector of partial results. Option1 (adjust in epilog): Initialize the vector as follows: add/bit or/xor: [0,0,...,0,0] mult/bit and: [1,1,...,1,1] min/max/cond_expr: [init_val,init_val,..,init_val,init_val] and when necessary (e.g. add/mult case) let the caller know that it needs to adjust the result by init_val. Option2: Initialize the vector as follows: add/bit or/xor: [init_val,0,0,...,0] mult/bit and: [init_val,1,1,...,1] min/max/cond_expr: [init_val,init_val,...,init_val] and no adjustments are needed. For example, for the following code: s = init_val; for (i=0;i<n;i++) s = s + a[i]; STMT is 's = s + a[i]', and the reduction variable is 's'. For a vector of 4 units, we want to return either [0,0,0,init_val], or [0,0,0,0] and let the caller know that it needs to adjust the result at the end by 'init_val'. FORNOW, we are using the 'adjust in epilog' scheme, because this way the initialization vector is simpler (same element in all entries), if ADJUSTMENT_DEF is not NULL, and Option2 otherwise. A cost model should help decide between these two schemes.
In case of double reduction we only create a vector variable to be put in the reduction phi node. The actual statement creation is done in vect_create_epilog_for_reduction.
ADJUSMENT_DEF is NULL when called from vect_create_epilog_for_reduction to vectorize double reduction.
Create a vector of '0' or '1' except the first element.
Option1: the first element is '0' or '1' as well.
Option2: the first element is INIT_VAL.
References add_phi_arg(), dump_enabled_p(), dump_gimple_stmt(), dump_printf(), dump_printf_loc(), get_gimple_rhs_class(), get_vectype_for_scalar_type(), gimple_assign_rhs1(), gimple_assign_rhs2(), gimple_assign_rhs_code(), GIMPLE_BINARY_RHS, gimple_op(), GIMPLE_SINGLE_RHS, GIMPLE_TERNARY_RHS, GIMPLE_UNARY_RHS, loop::inner, loop_latch_edge(), loop_preheader_edge(), nested_in_vect_loop_p(), reduction_phi(), ternary_op, vect_get_vec_def_for_operand(), vect_get_vec_def_for_stmt_copy(), vect_get_vec_defs(), vect_location, vect_unknown_def_type, vinfo_for_stmt(), and vNULL.

static 
Function new_loop_vec_info. Create and initialize a new loop_vec_info struct for LOOP, as well as stmt_vec_info structs for all the stmts in LOOP.
Create/Update stmt_info for all stmts in the loop.
BBs in a nested innerloop will have been already processed (because we will have called vect_analyze_loop_form for any nested innerloop). Therefore, for stmts in an innerloop we just want to update the STMT_VINFO_LOOP_VINFO field of their stmt_info to point to the new loop_info of the outerloop we are currently considering to vectorize (instead of the loop_info of the innerloop). For stmts in other BBs we need to create a stmt_info from scratch.
Innerloop bb.
bb in current nest.
CHECKME: We want to visit all BBs before their successors (except for latch blocks, for which this assertion wouldn't hold). In the simple case of the loop forms we allow, a dfs order of the BBs would the same as reversed postorder traversal, so we are safe.
References gsi_end_p(), gsi_next(), gsi_start_bb(), gsi_start_phis(), gsi_stmt(), loop::inner, basic_block_def::loop_father, and vinfo_for_stmt().

static 
Function reduction_code_for_scalar_code Input: CODE  tree_code of a reduction operations. Output: REDUC_CODE  the corresponding treecode to be used to reduce the vector of partial results into a single scalar result (which will also reside in a vector) or ERROR_MARK if the operation is a supported reduction operation, but does not have such treecode. Return FALSE if CODE currently cannot be vectorized as reduction.

static 
Error reporting helper for vect_is_simple_reduction below. GIMPLE statement STMT is printed with a message MSG.
loop_vec_info vect_analyze_loop  (  ) 
Function vect_analyze_loop. Apply a set of analyses on LOOP, and create a loop_vec_info struct for it. The different analyses will record information in the loop_vec_info struct.
Autodetect first vector size we try.
Check the CFG characteristics of the loop (nesting, entry/exit).
Try the next biggest vector size.

static 
Function vect_analyze_loop_1. Apply a set of analyses on LOOP, and create a loop_vec_info struct for it. The different analyses will record information in the loop_vec_info struct. This is a subset of the analyses applied in vect_analyze_loop, to be applied on an innerloop nested in the loop that is now considered for (outerloop) vectorization.
Check the CFG characteristics of the loop (nesting, entry/exit, etc.
References dump_enabled_p(), dump_printf_loc(), loop::inner, loop::num_nodes, and vect_location.

static 
Function vect_analyze_loop_2. Apply a set of analyses on LOOP, and create a loop_vec_info struct for it. The different analyses will record information in the loop_vec_info struct.
Find all data references in the loop (which correspond to vdefs/vuses) and analyze their evolution in the loop. Also adjust the minimal vectorization factor according to the loads and stores. FORNOW: Handle only simple, array references, which alignment can be forced, and aligned pointerreferences.
Analyze the access patterns of the datarefs in the loop (consecutive, complex, etc.). FORNOW: Only handle consecutive access pattern.
Classify all crossiteration scalar dataflow cycles. Crossiteration cycles caused by virtual phis are analyzed separately.
Dataflow analysis to detect stmts that do not need to be vectorized.
Analyze data dependences between the datarefs in the loop and adjust the maximum vectorization factor according to the dependences. FORNOW: fail at the first data dependence that we encounter.
Analyze the alignment of the datarefs in the loop. Fail if a data reference is found that cannot be vectorized.
Prune the list of ddrs to be tested at runtime by versioning for alias. It is important to call pruning after vect_analyze_data_ref_accesses, since we use grouping information gathered by interleaving analysis.
This pass will decide on using loop versioning and/or loop peeling in order to enhance the alignment of data references in the loop.
Check the SLP opportunities in the loop, analyze and build SLP trees.
Decide which possible SLP instances to SLP.
Find stmts that need to be both vectorized and SLPed.
Scan all the operations in the loop and make sure they are vectorizable.
loop_vec_info vect_analyze_loop_form  (  ) 
Function vect_analyze_loop_form. Verify that certain CFG restrictions hold, including:  the loop has a preheader  the loop has a single entry and exit  the loop exit condition is simple enough, and the number of iterations can be analyzed (a countable loop).
Different restrictions apply when we are considering an innermost loop, vs. an outer (nested) loop. (FORNOW. May want to relax some of these restrictions in the future).
Innermost loop. We currently require that the number of BBs is exactly 2 (the header and latch). Vectorizable innermost loops look like this: (preheader)  header <+     +> latch +  (exitbb)
Nested loop. We currently require that the loop is doublynested, contains a single inner loop, and the number of BBs is exactly 5. Vectorizable outerloops look like this: (preheader)  header <+   innerloop    tail +  (exitbb) The innerloop has the properties expected of innermost loops as described above.
Analyze the innerloop.
We assume that the loop exit condition is at the end of the loop. i.e, that the loop is represented as a dowhile (with a proper ifguard before the loop if needed), where the loop header contains all the executable statements, and the latch is empty.
Make sure there exists a singlepredecessor exit bb:
CHECKME: May want to keep it around it in the future.

static 
Function vect_analyze_loop_operations. Scan the loop stmts and make sure they are all vectorizable.
If all the stmts in the loop can be SLPed, we perform only SLP, and vectorization factor of the loop is the unrolling factor required by the SLP instances. If that unrolling factor is 1, we say, that we perform pure SLP on loop  cross iteration parallelism is not exploited.
STMT needs both SLP and loopbased vectorization.
Innerloop loopclosed exit phi in outerloop vectorization (i.e., a phi in the tail of the outerloop).
FORNOW: we currently don't support the case that these phis are not used in the outerloop (unless it is double reduction, i.e., this phi is vect_reduction_def), cause this case requires to actually do something here.
If PHI is used in the outer loop, we check that its operand is defined in the inner loop.
FORNOW: not yet supported.
A scalardependence cycle that we don't support.
All operations in the loop are either irrelevant (deal with loop control, or dead), or only used outside the loop and can be moved out of the loop (e.g. invariants, inductions). The loop can be optimized away by scalar optimizations. We're better off not touching this loop.
Analyze cost. Decide if worth while to vectorize.
Once VF is set, SLP costs should be updated since the number of created vector stmts depends on VF.
Use the cost model only if it is more conservative than user specified threshold.

static 
Function vect_analyze_scalar_cycles. Examine the cross iteration defuse cycles of scalar variables, by analyzing the loopheader PHIs of scalar variables. Classify each cycle as one of the following: invariant, induction, reduction, unknown. We do that for the loop represented by LOOP_VINFO, and also to its innerloop, if exists. Examples for scalar cycles: Example1: reduction: loop1: for (i=0; i<N; i++) sum += a[i]; Example2: induction: loop2: for (i=0; i<N; i++) a[i] = i;
When vectorizing an outerloop, the innerloop is executed sequentially. Reductions in such innerloop therefore have different properties than the reductions in the nest that gets vectorized: 1. When vectorized, they are executed in the same order as in the original scalar loop, so we can't change the order of computation when vectorizing them. 2. FIXME: Innerloop reductions can be used in the innerloop, so the current checks are too strict.
References chrec_dont_know, dump_enabled_p(), dump_generic_expr(), dump_printf(), dump_printf_loc(), number_of_exit_cond_executions(), and vect_location.

static 
Function vect_analyze_scalar_cycles_1. Examine the cross iteration defuse cycles of scalar variables in LOOP. LOOP_VINFO represents the loop that is now being considered for vectorization (can be LOOP, or an outerloop enclosing LOOP).
First  identify all inductions. Reduction detection assumes that all the inductions have been identified, therefore, this order must not be changed.
Skip virtual phi's. The data dependences that are associated with virtual defs/uses (i.e., memory accesses) are analyzed elsewhere.
Analyze the evolution function.
Second  identify all reductions and nested cycles.
Store the reduction cycles for possible vectorization in loopaware SLP.

static 
@verbatim
Function vect_create_epilog_for_reduction
Create code at the loopepilog to finalize the result of a reduction computation.
VECT_DEFS is list of vector of partial results, i.e., the lhs's of vector reduction statements. STMT is the scalar reduction stmt that is being vectorized. NCOPIES is > 1 in case the vectorization factor (VF) is bigger than the number of elements that we can fit in a vectype (nunits). In this case we have to generate more than one vector stmt  i.e  we need to "unroll" the vector stmt by a factor VF/nunits. For more details see documentation in vectorizable_operation. REDUC_CODE is the treecode for the epilog reduction. REDUCTION_PHIS is a list of the phinodes that carry the reduction computation. REDUC_INDEX is the index of the operand in the right hand side of the statement that is defined by REDUCTION_PHI. DOUBLE_REDUC is TRUE if double reduction phi nodes should be handled. SLP_NODE is an SLP node containing a group of reduction statements. The first one in this group is STMT.
This function:
"Reduces" each vector of partial results VECT_DEFS into a single result, by applying the operation specified by REDUC_CODE if available, or by other means (wholevector shifts or a scalar loop). The function also creates a new phi node at the loop exit to preserve loopclosed form, as illustrated below.
The flow at the entry to this function:
loop: vec_def = phi <null, null> # REDUCTION_PHI VECT_DEF = vector_stmt # vectorized form of STMT s_loop = scalar_stmt # (scalar) STMT loop_exit: s_out0 = phi <s_loop> # (scalar) EXIT_PHI use <s_out0> use <s_out0>
The above is transformed by this function into:
loop: vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI VECT_DEF = vector_stmt # vectorized form of STMT s_loop = scalar_stmt # (scalar) STMT loop_exit: s_out0 = phi <s_loop> # (scalar) EXIT_PHI v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI v_out2 = reduce <v_out1> s_out3 = extract_field <v_out2, 0> s_out4 = adjust_result <s_out3> use <s_out4> use <s_out4>
1. Create the reduction defuse cycle: Set the arguments of REDUCTION_PHIS, i.e., transform loop: vec_def = phi <null, null> # REDUCTION_PHI VECT_DEF = vector_stmt # vectorized form of STMT ... into: loop: vec_def = phi <vec_init, VECT_DEF> # REDUCTION_PHI VECT_DEF = vector_stmt # vectorized form of STMT ... (in case of SLP, do it for all the phis).
Get the loopentry arguments.
For the case of reduction, vect_get_vec_def_for_operand returns the scalar def before the loop, that defines the initial value of the reduction variable.
Set phi nodes arguments.
Set the loopentry arg of the reductionphi.
Set the looplatch arg for the reductionphi.
2. Create epilog code. The reduction epilog code operates across the elements of the vector of partial results computed by the vectorized loop. The reduction epilog code consists of: step 1: compute the scalar result in a vector (v_out2) step 2: extract the scalar result (s_out3) from the vector (v_out2) step 3: adjust the scalar result (s_out3) if needed. Step 1 can be accomplished using one the following three schemes: (scheme 1) using reduc_code, if available. (scheme 2) using wholevector shifts, if available. (scheme 3) using a scalar loop. In this case steps 1+2 above are combined. The overall epilog code looks like this: s_out0 = phi <s_loop> # original EXIT_PHI v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI v_out2 = reduce <v_out1> # step 1 s_out3 = extract_field <v_out2, 0> # step 2 s_out4 = adjust_result <s_out3> # step 3 (step 3 is optional, and steps 1 and 2 may be combined). Lastly, the uses of s_out0 are replaced by s_out4.
2.1 Create new loopexitphis to preserve loopclosed form: v_out1 = phi <VECT_DEF> Store them in NEW_PHIS.
The epilogue is created for the outerloop, i.e., for the loop being vectorized. Create exit phis for the outer loop.
2.2 Get the relevant treecode to use in the epilog for schemes 2,3 (i.e. when reduc_code is not available) and in the final adjustment code (if needed). Also get the original scalar reduction variable as defined in the loop. In case STMT is a "patternstmt" (i.e.  it represents a reduction pattern), the treecode and scalardef are taken from the original stmt that the patternstmt (STMT) replaces. Otherwise (it is a regular reduction)  the treecode and scalardef are taken from STMT.
Regular reduction
Reduction pattern
For MINUS_EXPR the initial vector is [init_val,0,...,0], therefore, partial results are added and not subtracted.
In case this is a reduction in an innerloop while vectorizing an outer loop  we don't need to extract a single scalar result at the end of the innerloop (unless it is double reduction, i.e., the use of reduction is outside the outerloop). The final vector of partial results will be used in the vectorized outerloop, or reduced to a scalar result at the end of the outerloop.
SLP reduction without reduction chain, e.g., # a1 = phi <a2, a0> # b1 = phi <b2, b0> a2 = operation (a1) b2 = operation (b1)
In case of reduction chain, e.g., # a1 = phi <a3, a0> a2 = operation (a1) a3 = operation (a2), we may end up with more than one vector result. Here we reduce them to one vector.
2.3 Create the reduction code, using one of the three schemes described above. In SLP we simply need to extract all the elements from the vector (without reducing them), so we use scalar shifts.
Case 1: Create: v_out2 = reduc_expr <v_out1>
Regardless of whether we have a whole vector shift, if we're emulating the operation via treevectgeneric, we don't want to use it. Only the first round of the reduction is likely to still be profitable via emulation.
??? It might be better to emit a reduction tree code here, so that treevectgeneric can expand the first round via bit tricks.
Case 2: Create: for (offset = VS/2; offset >= element_size; offset/=2) { Create: va' = vec_shift <va, offset> Create: va = vop <va, va'> }
Case 3: Create: s = extract_field <v_out2, 0> for (offset = element_size; offset < vector_size; offset += element_size;) { Create: s' = extract_field <v_out2, offset> Create: s = op <s, s'> // For non SLP cases }
In SLP we don't need to apply reduction operation, so we just collect s' values in SCALAR_RESULTS.
In SLP we don't need to apply reduction operation, so we just collect s' values in SCALAR_RESULTS.
The only case where we need to reduce scalar results in SLP, is unrolling. If the size of SCALAR_RESULTS is greater than GROUP_SIZE, we reduce them combining elements modulo GROUP_SIZE.
Reduce multiple scalar results in case of SLP unrolling.
Not SLP  we have one scalar to keep in SCALAR_RESULTS.
2.4 Extract the final scalar result. Create: s_out3 = extract_field <v_out2, bitpos>
2.5 Adjust the final result by the initial value of the reduction variable. (When such adjustment is not needed, then 'adjustment_def' is zero). For example, if code is PLUS we create: new_temp = loop_exit_def + adjustment_def
2.6 Handle the loopexit phis. Replace the uses of scalar loopexit phis with new adjusted scalar results, i.e., replace use <s_out0> with use <s_out4>. Transform: loop_exit: s_out0 = phi <s_loop> # (scalar) EXIT_PHI v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI v_out2 = reduce <v_out1> s_out3 = extract_field <v_out2, 0> s_out4 = adjust_result <s_out3> use <s_out0> use <s_out0> into: loop_exit: s_out0 = phi <s_loop> # (scalar) EXIT_PHI v_out1 = phi <VECT_DEF> # NEW_EXIT_PHI v_out2 = reduce <v_out1> s_out3 = extract_field <v_out2, 0> s_out4 = adjust_result <s_out3> use <s_out4> use <s_out4>
In SLP reduction chain we reduce vector results into one vector if necessary, hence we set here GROUP_SIZE to 1. SCALAR_DEST is the LHS of the last stmt in the reduction chain, since we are looking for the loop exit phi node.
In SLP we may have several statements in NEW_PHIS and REDUCTION_PHIS (in case that GROUP_SIZE is greater than vectorization factor). Therefore, we need to match SCALAR_RESULTS with corresponding statements. The first (GROUP_SIZE / number of new vector stmts) scalar results correspond to the first vector stmt, etc. (RATIO is equal to (GROUP_SIZE / number of new vector stmts)).
SLP statements can't participate in patterns.
Find the loopcloseduse at the loop exit of the original scalar result. (The reduction result is expected to have two immediate uses  one at the latch block, and one at the loop exit).
While we expect to have found an exit_phi because of loopclosedssa form we can end up without one if the scalar cycle is dead.
FORNOW. Currently not supporting the case that an innerloop reduction is not used in the outerloop (but only outside the outerloop), unless it is double reduction.
Handle double reduction: stmt1: s1 = phi <s0, s2>  double reduction phi (outer loop) stmt2: s3 = phi <s1, s4>  (regular) reduc phi (inner loop) stmt3: s4 = use (s3)  (regular) reduc stmt (inner loop) stmt4: s2 = phi <s4>  double reduction stmt (outer loop) At that point the regular reduction (stmt2 and stmt3) is already vectorized, as well as the exit phi node, stmt4. Here we vectorize the phi node of double reduction, stmt1, and update all relevant statements.
Go through all the uses of s2 to find double reduction phi node, i.e., stmt1 above.
Check that USE_STMT is really double reduction phi node.
Create vector phi node for double reduction: vs1 = phi <vs0, vs2> vs1 was created previously in this function by a call to vect_get_vec_def_for_operand and is stored in vec_initial_def; vs2 is defined by INNER_PHI, the vectorized EXIT_PHI; vs0 is created here.
Create vector phi node.
Create vs0  initial def of the double reduction phi.
Update phi node arguments with vs0 and vs2.
Replace the use, i.e., set the correct vs1 in the regular reduction phi node. FORNOW, NCOPIES is always 1, so the loop is redundant.
Find the loopcloseduse at the loop exit of the original scalar result. (The reduction result is expected to have two immediate uses, one at the latch block, and one at the loop exit). For double reductions we are looking for exit phis of the outer loop.
Replace the uses:
References copy_ssa_name(), create_phi_node(), new_stmt_vec_info(), set_vinfo_for_stmt(), single_exit(), vect_get_vec_def_for_stmt_copy(), and vinfo_for_stmt().

static 
@verbatim
Function vect_determine_vectorization_factor
Determine the vectorization factor (VF). VF is the number of data elements that are operated upon in parallel in a single iteration of the vectorized loop. For example, when vectorizing a loop that operates on 4byte elements, on a target with vector size (VS) 16byte, the VF is set to 4, since 4 elements can fit in a single vector register.
We currently support vectorization of loops in which all types operated upon are of the same size. Therefore this function currently sets VF according to the size of the types operated upon, and fails if there are multiple sizes in the loop.
VF is also the factor by which the loop iterations are stripmined, e.g.: original loop: for (i=0; i<N; i++){ a[i] = b[i] + c[i]; }
vectorized loop: for (i=0; i<N; i+=VF){ a[i:VF] = b[i:VF] + c[i:VF]; }
Skip stmts which do not need to be vectorized.
If a pattern statement has def stmts, analyze them too.
The only case when a vectype had been already set is for stmts that contain a dataref, or for "patternstmts" (stmts generated by the vectorizer to represent/replace a certain idiom).
The vectorization factor is according to the smallest scalar type (or the largest vector size, but we only support one vector size per loop).
TODO: Analyze cost. Decide if worth while to vectorize.

static 
@verbatim
Loop Vectorization Copyright (C) 20032013 Free Software Foundation, Inc. Contributed by Dorit Naishlos dorit and Ira Rosen @il. ibm.c omirar@ il.i bm.co m
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see http://www.gnu.org/licenses/.
Loop Vectorization Pass. This pass tries to vectorize loops. For example, the vectorizer transforms the following simple loop: short a[N]; short b[N]; short c[N]; int i; for (i=0; i<N; i++){ a[i] = b[i] + c[i]; } as if it was manually vectorized by rewriting the source code into: typedef int __attribute__((mode(V8HI))) v8hi; short a[N]; short b[N]; short c[N]; int i; v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c; v8hi va, vb, vc; for (i=0; i<N/8; i++){ vb = pb[i]; vc = pc[i]; va = vb + vc; pa[i] = va; } The main entry to this pass is vectorize_loops(), in which the vectorizer applies a set of analyses on a given set of loops, followed by the actual vectorization transformation for the loops that had successfully passed the analysis phase. Throughout this pass we make a distinction between two types of data: scalars (which are represented by SSA_NAMES), and memory references ("datarefs"). These two types of data require different handling both during analysis and transformation. The types of datarefs that the vectorizer currently supports are ARRAY_REFS which base is an array DECL (not a pointer), and INDIRECT_REFS through pointers; both array and pointer accesses are required to have a simple (consecutive) access pattern. Analysis phase: =============== The driver for the analysis phase is vect_analyze_loop(). It applies a set of analyses, some of which rely on the scalar evolution analyzer (scev) developed by Sebastian Pop. During the analysis phase the vectorizer records some information per stmt in a "stmt_vec_info" struct which is attached to each stmt in the loop, as well as general information about the loop as a whole, which is recorded in a "loop_vec_info" struct attached to each loop. Transformation phase: ===================== The loop transformation phase scans all the stmts in the loop, and creates a vector stmt (or a sequence of stmts) for each scalar stmt S in the loop that needs to be vectorized. It inserts the vector code sequence just before the scalar stmt S, and records a pointer to the vector code in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct attached to S). This pointer will be used for the vectorization of following stmts which use the def of stmt S. Stmt S is removed if it writes to memory; otherwise, we rely on dead code elimination for removing it. For example, say stmt S1 was vectorized into stmt VS1: VS1: vb = px[i]; S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1 S2: a = b; To vectorize stmt S2, the vectorizer first finds the stmt that defines the operand 'b' (S1), and gets the relevant vector def 'vb' from the vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)). The resulting sequence would be: VS1: vb = px[i]; S1: b = x[i]; STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1 VS2: va = vb; S2: a = b; STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2 Operands that are not SSA_NAMEs, are datarefs that appear in load/store operations (like 'x[i]' in S1), and are handled differently. Target modeling: ================= Currently the only target specific information that is used is the size of the vector (in bytes)  "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". Targets that can support different sizes of vectors, for now will need to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD". More flexibility will be added in the future. Since we only vectorize operations which vector form can be expressed using existing tree codes, to verify that an operation is supported, the vectorizer checks the relevant optab at the relevant machine_mode (e.g, optab_handler (add_optab, V8HImode)). If the value found is CODE_FOR_nothing, then there's no target support, and we can't vectorize the stmt. For additional information on this project see: http://gcc.gnu.org/projects/treessa/vectorization.html
Function vect_estimate_min_profitable_iters Return the number of iterations required for the vector version of the loop to be profitable relative to the cost of the scalar version of the loop.
Cost model disabled.
Requires loop versioning tests to handle misalignment.
FIXME: Make cost depend on complexity of individual check.
Requires loop versioning with alias checks.
FIXME: Make cost depend on complexity of individual check.
Count statements in scalar loop. Using this as scalar cost for a single iteration for now. TODO: Add outer loop support. TODO: Consider assigning different costs to different scalar statements.
Add additional cost for the peeled instructions in prologue and epilogue loop. FORNOW: If we don't know the value of peel_iters for prologue or epilogue at compiletime  we assume it's vf/2 (the worst would be vf1). TODO: Build an expression that represents peel_iters for prologue and epilogue to be used in a runtime test.
If peeling for alignment is unknown, loop bound of main loop becomes unknown.
If peeled iterations are unknown, count a taken branch and a not taken branch per peeled loop. Even if scalar loop iterations are known, vector iterations are not known since peeled prologue iterations are not known. Hence guards remain the same.
FORNOW: Don't attempt to pass individual scalar instructions to the model; just assume linear cost for scalar iterations.
FORNOW: The scalar outside cost is incremented in one of the following ways: 1. The vectorizer checks for alignment and aliasing and generates a condition that allows dynamic vectorization. A cost model check is ANDED with the versioning condition. Hence scalar code path now has the added cost of the versioning check. if (cost > th & versioning_check) jmp to vector code Hence runtime scalar is incremented by nottaken branch cost. 2. The vectorizer then checks if a prologue is required. If the cost model check was not done before during versioning, it has to be done before the prologue check. if (cost <= th) prologue = scalar_iters if (prologue == 0) jmp to vector code else execute prologue if (prologue == num_iters) go to exit Hence the runtime scalar cost is incremented by a taken branch, plus a nottaken branch, plus a taken branch cost. 3. The vectorizer then checks if an epilogue is required. If the cost model check was not done before during prologue check, it has to be done with the epilogue check. if (prologue == 0) jmp to vector code else execute prologue if (prologue == num_iters) go to exit vector code: if ((cost <= th)  (scalar_itersprologueepilogue == 0)) jmp to epilogue Hence the runtime scalar cost should be incremented by 2 taken branches. TODO: The back end may reorder the BBS's differently and reverse conditions/branch directions. Change the estimates below to something more reasonable.
If the number of iterations is known and we do not do versioning, we can decide whether to vectorize at compile time. Hence the scalar version do not carry cost model guard costs.
Cost model check occurs at versioning.
Cost model check occurs at prologue generation.
Cost model check occurs at epilogue generation.
Complete the targetspecific cost calculations.
Calculate number of iterations required to make the vector version profitable, relative to the loop bodies only. The following condition must hold true: SIC * niters + SOC > VIC * ((nitersPL_ITERSEP_ITERS)/VF) + VOC where SIC = scalar iteration cost, VIC = vector iteration cost, VOC = vector outside cost, VF = vectorization factor, PL_ITERS = prologue iterations, EP_ITERS= epilogue iterations SOC = scalar outside cost for run time cost model check.
vector version will never be profitable.
Because the condition we create is: if (niters <= min_profitable_iters) then skip the vectorized loop.
Calculate number of iterations required to make the vector version profitable, relative to the loop bodies only. Nonvectorized variant is SIC * niters and it must win over vector variant on the expected loop trip count. The following condition must hold true: SIC * niters > VIC * ((nitersPL_ITERSEP_ITERS)/VF) + VOC + SOC
References add_stmt_cost(), _stmt_info_for_cost::count, _stmt_info_for_cost::kind, _stmt_info_for_cost::misalign, si, _stmt_info_for_cost::stmt, vect_epilogue, vect_get_known_peeling_cost(), vect_prologue, and vinfo_for_stmt().
gimple vect_force_simple_reduction  (  loop_vec_info  loop_info, 
gimple  phi,  
bool  check_reduction,  
bool *  double_reduc  
) 
Wrapper around vect_is_simple_reduction_1, which will modify code inplace if it enables detection of more reductions. Arguments as there.
int vect_get_known_peeling_cost  (  loop_vec_info  loop_vinfo, 
int  peel_iters_prologue,  
int *  peel_iters_epilogue,  
int  scalar_single_iter_cost,  
stmt_vector_for_cost *  prologue_cost_vec,  
stmt_vector_for_cost *  epilogue_cost_vec  
) 
Calculate cost of peeling the loop PEEL_ITERS_PROLOGUE times.
If peeled iterations are known but number of scalar loop iterations are unknown, count a taken branch per peeled loop.
If we need to peel for gaps, but no peeling is required, we have to peel VF iterations.
Referenced by vect_estimate_min_profitable_iters().

static 
Function vect_get_loop_niters. Determine how many iterations the loop is executed. If an expression that represents the number of iterations can be constructed, place it in NUMBER_OF_ITERATIONS. Return the loop exit condition.
int vect_get_single_scalar_iteration_cost  (  ) 
Calculate the cost of one scalar iteration of the loop.
Count statements in scalar loop. Using this as scalar cost for a single iteration for now. TODO: Add outer loop support. TODO: Consider assigning different costs to different scalar statements.
FORNOW.
Skip stmts that are not vectorized inside the loop.

static 
Function vect_is_simple_iv_evolution. FORNOW: A simple evolution of an induction variables in the loop is considered a polynomial evolution.
When there is no evolution in this loop, the evolution function is not "simple".
When the evolution is a polynomial of degree >= 2 the evolution function is not "simple".

static 
Wrapper around vect_is_simple_reduction_1, that won't modify code inplace. Arguments as there.

static 
@verbatim
Function vect_is_simple_reduction_1
(1) Detect a crossiteration defuse cycle that represents a simple reduction computation. We look for the following pattern:
loop_header: a1 = phi < a0, a2 > a3 = ... a2 = operation (a3, a1)
or
a3 = ... loop_header: a1 = phi < a0, a2 > a2 = operation (a3, a1)
such that:
Conditions 1,4 are tested here. Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
(2) Detect a crossiteration defuse cycle in nested loops, i.e., nested cycles, if CHECK_REDUCTION is false.
(3) Detect cycles of phi nodes in outerloop vectorization, i.e., double reductions:
a1 = phi < a0, a2 > inner loop (def of a3) a2 = phi < a3 >
If MODIFY is true it tries also to rework the code inplace to enable detection of more reduction patterns. For the time being we rewrite "res = RHS" into "rhs += RHS" when it seems worthwhile.
If CHECK_REDUCTION is true, we assume innermost loop vectorization, otherwise, we assume outer loop vectorization.
If DEF_STMT is a phi node itself, we expect it to have a single argument defined in the inner loop.
We can handle "res = x[i]", which is nonassociative by simply rewriting this into "res += x[i]". Avoid changing gimple instruction for the first simple tests and only do this if we're allowed to change code at all.
Check that it's ok to change the order of the computation. Generally, when vectorizing a reduction we change the order of the computation. This may change the behavior of the program in some cases, so we need to check that this is ok. One exception is when vectorizing an outerloop: the innerloop is executed sequentially, and therefore vectorizing reductions in the innerloop during outerloop vectorization is safe.
CHECKME: check for !flag_finite_math_only too?
Changing the order of operations changes the semantics.
Changing the order of operations changes the semantics.
Changing the order of operations changes the semantics.
If we detected "res = x[i]" earlier, rewrite it into "res += x[i]" now. If this turns out to be useless reassoc will clean it up again.
Reduction is safe. We're dealing with one of the following: 1) integer arithmetic and no trapv 2) floating point arithmetic, and special flags permit this optimization 3) nested cycle (i.e., outer loop vectorization).
Check that one def is the reduction def, defined by PHI, the other def is either defined in the loop ("vect_internal_def"), or it's an induction (defined by a loopheader phinode).
Swap operands (just for simplicity  so that the rest of the code can assume that the reduction variable is always the last (second) argument).
Try to find SLP reduction chain.

static 
Detect SLP reduction of the form: #a1 = phi <a5, a0> a2 = operation (a1) a3 = operation (a2) a4 = operation (a3) a5 = operation (a4) #a = phi <a5> PHI is the reduction phi node (#a1 = phi <a5, a0> above) FIRST_STMT is the first reduction stmt in the chain (a2 = operation (a1)). Return TRUE if a reduction chain was detected.
Check if we got back to the reduction phi.
There are can be either a single use in the loop or two uses in phi nodes.
We reached a statement with no loop uses.
This is a loop exit phi, and we haven't reached the reduction phi.
Insert USE_STMT into reduction chain.
Swap the operands, if needed, to make the reduction operand be the second operand.
Check that the other def is either defined in the loop ("vect_internal_def"), or it's an induction (defined by a loopheader phinode).
Check that the other def is either defined in the loop ("vect_internal_def"), or it's an induction (defined by a loopheader phinode).
Save the chain for further analysis in SLP detection.

static 
Kill any debug uses outside LOOP of SSA names defined in STMT.
References dump_enabled_p(), dump_gimple_stmt(), dump_printf(), dump_printf_loc(), gsi_end_p(), gsi_next(), gsi_none(), gsi_stmt(), vect_location, and vinfo_for_stmt().
int vect_min_worthwhile_factor  (  ) 
Function vect_min_worthwhile_factor. For a loop where we could vectorize the operation indicated by CODE, return the minimum vectorization factor that makes it worthwhile to use generic vectors.
References dump_enabled_p(), dump_printf_loc(), gimple_debug_bind_p(), gimple_debug_bind_reset_value(), update_stmt(), and vect_location.

static 
Function vect_model_induction_cost. Models cost for induction operations.
loop cost for vec_loop.
prologue cost for vec_init and vec_step.

static 
TODO: Close dependency between vect_model_*_cost and vectorizable_* functions. Design better to avoid maintenance issues.
Function vect_model_reduction_cost. Models cost for a reduction operation, including the vector ops generated within the stripmine loop, the initial definition before the loop, and the epilogue code that must be generated.
Cost of reduction op inside loop.
Add in cost for initial definition.
Determine cost of epilogue code. We have a reduction operator that will reduce the vector in one statement. Also requires scalar extract.
We have a whole vector shift available.
Final reduction via vector shifts and the reduction operator. Also requires scalar extract.
Use extracts and reduction op for final reduction. For N elements, we have N extracts and N1 reduction ops.
References add_stmt_cost(), dump_enabled_p(), dump_printf_loc(), scalar_to_vec, vect_body, vect_location, vect_prologue, and vector_stmt.
void vect_transform_loop  (  ) 
Function vect_transform_loop. The analysis phase has determined that the loop is vectorizable. Vectorize the loop  created vectorized stmts to replace the scalar stmts in the loop, and update the loop exit condition.
Record number of iterations before we started tampering with the profile.
If profile is inprecise, we have chance to fix it up.
Use the more conservative vectorization threshold. If the number of iterations is constant assume the cost check has been performed by our caller. If the threshold makes all loops profitable that run at least the vectorization factor number of times checking is pointless, too.
Version the loop first, if required, so the profitability check comes first.
Peel the loop if there are data refs with unknown alignment. Only one data ref with unknown store is allowed.
If the loop has a symbolic number of iterations 'n' (i.e. it's not a compile time constant), or it is a constant that doesn't divide by the vectorization factor, then an epilog loop needs to be created. We therefore duplicate the loop: the original loop will be vectorized, and will compute the first (n/VF) iterations. The second copy of the loop will remain scalar and will compute the remaining (n%VF) iterations. (VF is the vectorization factor).
1) Make sure the loop header has exactly two entries 2) Make sure we have a preheader basic block.
FORNOW: the vectorizer supports only loops which body consist of one basic block (header + empty latch). When the vectorizer will support more involved loop forms, the order by which the BBs are traversed need to be reconsidered.
During vectorization remove existing clobber stmts.
vector stmts created in the outerloop during vectorization of stmts in an innerloop may not have a stmt_info, and do not need to be vectorized.
If pattern statement has def stmts, vectorize them too.
For SLP VF is set according to unrolling factor, and not to vector size, hence for SLP this print is not valid.
SLP. Schedule all the SLP instances when the first SLP stmt is reached.
Hybrid SLP stmts must be vectorized in addition to SLP.
 vectorize statement 
Interleaving. If IS_STORE is TRUE, the vectorization of the interleaving chain was completed  free all the stores in the chain.
Free the attached stmt_vec_info and remove the stmt.
Reduce loop iterations by the vectorization factor.
References dump_enabled_p(), dump_printf_loc(), gsi_end_p(), gsi_next(), vect_location, vect_schedule_slp(), and vinfo_for_stmt().
bool vectorizable_induction  (  gimple  phi, 
gimple_stmt_iterator *  gsi,  
gimple *  vec_stmt  
) 
Function vectorizable_induction Check if PHI performs an induction computation that can be vectorized. If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized phi to replace it, put it in VEC_STMT, and add it to the same basic block. Return FALSE if not a vectorizable STMT, TRUE otherwise.
FORNOW. These restrictions should be relaxed.
FORNOW: SLP not supported.
Transform.
Referenced by vect_analyze_stmt().
bool vectorizable_live_operation  (  gimple  stmt, 
gimple_stmt_iterator *  gsi,  
gimple *  vec_stmt  
) 
Function vectorizable_live_operation. STMT computes a value that is used outside the loop. Check if it can be supported.
FORNOW. CHECKME.
FORNOW: support only if all uses are invariant. This means that the scalar operations can remain in place, unvectorized. The original last scalar value that they compute will be used.
No transformation is required for the cases we currently support.
References dump_gimple_stmt(), dump_printf(), dump_printf_loc(), and vect_location.
bool vectorizable_reduction  (  gimple  stmt, 
gimple_stmt_iterator *  gsi,  
gimple *  vec_stmt,  
slp_tree  slp_node  
) 
Function vectorizable_reduction. Check if STMT performs a reduction operation that can be vectorized. If VEC_STMT is also passed, vectorize the STMT: create a vectorized stmt to replace it, put it in VEC_STMT, and insert it at GSI. Return FALSE if not a vectorizable STMT, TRUE otherwise. This function also handles reduction idioms (patterns) that have been recognized in advance during vect_pattern_recog. In this case, STMT may be of this form: X = pattern_expr (arg0, arg1, ..., X) and it's STMT_VINFO_RELATED_STMT points to the last stmt in the original sequence that had been detected and replaced by the patternstmt (STMT). In some cases of reduction patterns, the type of the reduction variable X is different than the type of the other arguments of STMT. In such cases, the vectype that is used when transforming STMT into a vector stmt is different than the vectype that is used to determine the vectorization factor, because it consists of a different number of elements than the actual number of elements that are being operated upon in parallel. For example, consider an accumulation of shorts into an int accumulator. On some targets it's possible to vectorize this pattern operating on 8 shorts at a time (hence, the vectype for purposes of determining the vectorization factor should be V8HI); on the other hand, the vectype that is used to create the vector form is actually V4SI (the type of the result). Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that indicates what is the actual level of parallelism (V8HI in the example), so that the right vectorization factor would be derived. This vectype corresponds to the type of arguments to the reduction stmt, and should *NOT* be used to create the vectorized stmt. The right vectype for the vectorized stmt is obtained from the type of the result X: get_vectype_for_scalar_type (TREE_TYPE (X)) This means that, contrary to "regular" reductions (or "regular" stmts in general), the following equation: STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (TREE_TYPE (X)) does *NOT* necessarily hold for reduction patterns.
The default is that the reduction variable is the last in statement.
In case of reduction chain we switch to the first stmt in the chain, but we don't update STMT_INFO, since only the last stmt is marked as reduction and has reduction properties.
1. Is vectorizable reduction?
Not supportable if the reduction variable is used in the loop, unless it's a reduction chain.
Reductions that are not used even in an enclosing outerloop, are expected to be "live" (used out of the loop).
Make sure it was already recognized as a reduction computation.
2. Has this been recognized as a reduction pattern? Check if STMT represents a pattern that has been recognized in earlier analysis stages. For stmts that represent a pattern, the STMT_VINFO_RELATED_STMT field records the last stmt in the original sequence that constitutes the pattern.
3. Check the operands of the operation. The first operands are defined inside the loop body. The last operand is the reduction variable, which is defined by the loopheaderphi.
Flatten RHS.
Do not try to vectorize bitprecision reductions.
All uses but the last are expected to be defined in the loop. The last use is the reduction variable. In case of nested cycle this assumption is not true: we use reduc_index to record the index of the reduction variable.
The condition of COND_EXPR is checked in vectorizable_condition().
For pattern recognized stmts, orig_stmt might be a reduction, but some helper statements for the pattern might not, or might be COND_EXPRs with reduction uses in the condition.
We changed STMT to be the first stmt in reduction chain, hence we check that in this case the first element in the chain is STMT.
4. Supportable by target?
Shifts and rotates are only supported by vectorizable_shifts, not vectorizable_reduction.
4.1. check support for the operation in the loop
Worthwhile without SIMD support?
4.2. Check support for the epilog operation. If STMT represents a reduction pattern, then the type of the reduction variable may be different than the type of the rest of the arguments. For example, consider the case of accumulation of shorts into an int accumulator; The original code: S1: int_a = (int) short_a; orig_stmt> S2: int_acc = plus <int_a ,int_acc>; was replaced with: STMT: int_acc = widen_sum <short_a, int_acc> This means that: 1. The treecode that is used to create the vector operation in the epilog code (that reduces the partial results) is not the treecode of STMT, but is rather the treecode of the original stmt from the pattern that STMT is replacing. I.e, in the example above we want to use 'widen_sum' in the loop, but 'plus' in the epilog. 2. The type (mode) we use to check available target support for the vector operation to be created in the *epilog*, is determined by the type of the reduction variable (in the example above we'd check this: optab_handler (plus_optab, vect_int_mode])). However the type (mode) we use to check available target support for the vector operation to be created *inside the loop*, is determined by the type of the other arguments to STMT (in the example we'd check this: optab_handler (widen_sum_optab, vect_short_mode)). This is contrary to "regular" reductions, in which the types of all the arguments are the same as the type of the reduction variable. For "regular" reductions we can therefore use the same vector type (and also the same treecode) when generating the epilog code and when generating the code inside the loop.
This is a reduction pattern: get the vectype from the type of the reduction variable, and get the treecode from orig_stmt.
Regular reduction: use the same vectype and treecode as used for the vector code inside the loop can be used for the epilog code.
In case of widenning multiplication by a constant, we update the type of the constant to be the type of the other operand. We check that the constant fits the type in the pattern recognition pass.
Transform.
FORNOW: Multiple types are not supported for condition.
Create the destination vector
In case the vectorization factor (VF) is bigger than the number of elements that we can fit in a vectype (nunits), we have to generate more than one vector stmt  i.e  we need to "unroll" the vector stmt by a factor VF/nunits. For more details see documentation in vectorizable_operation.
If the reduction is used in an outer loop we need to generate VF intermediate results, like so (e.g. for ncopies=2): r0 = phi (init, r0) r1 = phi (init, r1) r0 = x0 + r0; r1 = x1 + r1; (i.e. we generate VF results in 2 registers). In this case we have a separate defuse cycle for each copy, and therefore for each copy we get the vector def for the reduction variable from the respective phi node created for this copy. Otherwise (the reduction is unused in the loop nest), we can combine together intermediate results, like so (e.g. for ncopies=2): r = phi (init, r) r = x0 + r; r = x1 + r; (i.e. we generate VF/2 results in a single register). In this case for each copy we get the vector def for the reduction variable from the vectorized reduction operation generated in the previous iteration.
Create the reductionphi that defines the reduction operand.
Multiple types are not supported for condition.
Handle uses.
Finalize the reductionphi (set its arguments) and create the epilog reduction code.
Referenced by vect_analyze_stmt().