LoopVectorize.cpp revision 249423
1243789Sdim//===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2243789Sdim//
3243789Sdim//                     The LLVM Compiler Infrastructure
4243789Sdim//
5243789Sdim// This file is distributed under the University of Illinois Open Source
6243789Sdim// License. See LICENSE.TXT for details.
7243789Sdim//
8243789Sdim//===----------------------------------------------------------------------===//
9243789Sdim//
10243789Sdim// This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11243789Sdim// and generates target-independent LLVM-IR. Legalization of the IR is done
12249423Sdim// in the codegen. However, the vectorizer uses (will use) the codegen
13243789Sdim// interfaces to generate IR that is likely to result in an optimal binary.
14243789Sdim//
15249423Sdim// The loop vectorizer combines consecutive loop iterations into a single
16243789Sdim// 'wide' iteration. After this transformation the index is incremented
17243789Sdim// by the SIMD vector width, and not by one.
18243789Sdim//
19243789Sdim// This pass has three parts:
20243789Sdim// 1. The main loop pass that drives the different parts.
21243789Sdim// 2. LoopVectorizationLegality - A unit that checks for the legality
22243789Sdim//    of the vectorization.
23249423Sdim// 3. InnerLoopVectorizer - A unit that performs the actual
24243789Sdim//    widening of instructions.
25243789Sdim// 4. LoopVectorizationCostModel - A unit that checks for the profitability
26243789Sdim//    of vectorization. It decides on the optimal vector width, which
27243789Sdim//    can be one, if vectorization is not profitable.
28249423Sdim//
29243789Sdim//===----------------------------------------------------------------------===//
30243789Sdim//
31243789Sdim// The reduction-variable vectorization is based on the paper:
32243789Sdim//  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33243789Sdim//
34243789Sdim// Variable uniformity checks are inspired by:
35249423Sdim//  Karrenberg, R. and Hack, S. Whole Function Vectorization.
36243789Sdim//
37243789Sdim// Other ideas/concepts are from:
38243789Sdim//  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39243789Sdim//
40249423Sdim//  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41249423Sdim//  Vectorizing Compilers.
42249423Sdim//
43243789Sdim//===----------------------------------------------------------------------===//
44249423Sdim
45243789Sdim#define LV_NAME "loop-vectorize"
46243789Sdim#define DEBUG_TYPE LV_NAME
47249423Sdim
48249423Sdim#include "llvm/Transforms/Vectorize.h"
49249423Sdim#include "llvm/ADT/DenseMap.h"
50249423Sdim#include "llvm/ADT/MapVector.h"
51249423Sdim#include "llvm/ADT/SmallPtrSet.h"
52249423Sdim#include "llvm/ADT/SmallSet.h"
53243789Sdim#include "llvm/ADT/SmallVector.h"
54243789Sdim#include "llvm/ADT/StringExtras.h"
55243789Sdim#include "llvm/Analysis/AliasAnalysis.h"
56243789Sdim#include "llvm/Analysis/AliasSetTracker.h"
57249423Sdim#include "llvm/Analysis/Dominators.h"
58249423Sdim#include "llvm/Analysis/LoopInfo.h"
59249423Sdim#include "llvm/Analysis/LoopIterator.h"
60249423Sdim#include "llvm/Analysis/LoopPass.h"
61243789Sdim#include "llvm/Analysis/ScalarEvolution.h"
62249423Sdim#include "llvm/Analysis/ScalarEvolutionExpander.h"
63243789Sdim#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64249423Sdim#include "llvm/Analysis/TargetTransformInfo.h"
65243789Sdim#include "llvm/Analysis/ValueTracking.h"
66249423Sdim#include "llvm/Analysis/Verifier.h"
67249423Sdim#include "llvm/IR/Constants.h"
68249423Sdim#include "llvm/IR/DataLayout.h"
69249423Sdim#include "llvm/IR/DerivedTypes.h"
70249423Sdim#include "llvm/IR/Function.h"
71249423Sdim#include "llvm/IR/IRBuilder.h"
72249423Sdim#include "llvm/IR/Instructions.h"
73249423Sdim#include "llvm/IR/IntrinsicInst.h"
74249423Sdim#include "llvm/IR/LLVMContext.h"
75249423Sdim#include "llvm/IR/Module.h"
76249423Sdim#include "llvm/IR/Type.h"
77249423Sdim#include "llvm/IR/Value.h"
78249423Sdim#include "llvm/Pass.h"
79243789Sdim#include "llvm/Support/CommandLine.h"
80243789Sdim#include "llvm/Support/Debug.h"
81243789Sdim#include "llvm/Support/raw_ostream.h"
82249423Sdim#include "llvm/Target/TargetLibraryInfo.h"
83249423Sdim#include "llvm/Transforms/Scalar.h"
84249423Sdim#include "llvm/Transforms/Utils/BasicBlockUtils.h"
85243789Sdim#include "llvm/Transforms/Utils/Local.h"
86243789Sdim#include <algorithm>
87249423Sdim#include <map>
88249423Sdim
89243789Sdimusing namespace llvm;
90243789Sdim
91243789Sdimstatic cl::opt<unsigned>
92243789SdimVectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
93249423Sdim                    cl::desc("Sets the SIMD width. Zero is autoselect."));
94243789Sdim
95249423Sdimstatic cl::opt<unsigned>
96249423SdimVectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
97249423Sdim                    cl::desc("Sets the vectorization unroll count. "
98249423Sdim                             "Zero is autoselect."));
99249423Sdim
100249423Sdimstatic cl::opt<bool>
101249423SdimEnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
102249423Sdim                   cl::desc("Enable if-conversion during vectorization."));
103249423Sdim
104243789Sdim/// We don't vectorize loops with a known constant trip count below this number.
105249423Sdimstatic cl::opt<unsigned>
106249423SdimTinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
107249423Sdim                             cl::Hidden,
108249423Sdim                             cl::desc("Don't vectorize loops with a constant "
109249423Sdim                                      "trip count that is smaller than this "
110249423Sdim                                      "value."));
111243789Sdim
112249423Sdim/// We don't unroll loops with a known constant trip count below this number.
113249423Sdimstatic const unsigned TinyTripCountUnrollThreshold = 128;
114249423Sdim
115243789Sdim/// When performing a runtime memory check, do not check more than this
116243789Sdim/// number of pointers. Notice that the check is quadratic!
117249423Sdimstatic const unsigned RuntimeMemoryCheckThreshold = 4;
118243789Sdim
119249423Sdim/// We use a metadata with this name  to indicate that a scalar loop was
120249423Sdim/// vectorized and that we don't need to re-vectorize it if we run into it
121249423Sdim/// again.
122249423Sdimstatic const char*
123249423SdimAlreadyVectorizedMDName = "llvm.vectorizer.already_vectorized";
124249423Sdim
125243789Sdimnamespace {
126243789Sdim
127243789Sdim// Forward declarations.
128243789Sdimclass LoopVectorizationLegality;
129243789Sdimclass LoopVectorizationCostModel;
130243789Sdim
131249423Sdim/// InnerLoopVectorizer vectorizes loops which contain only one basic
132243789Sdim/// block to a specified vectorization factor (VF).
133243789Sdim/// This class performs the widening of scalars into vectors, or multiple
134243789Sdim/// scalars. This class also implements the following features:
135243789Sdim/// * It inserts an epilogue loop for handling loops that don't have iteration
136243789Sdim///   counts that are known to be a multiple of the vectorization factor.
137243789Sdim/// * It handles the code generation for reduction variables.
138243789Sdim/// * Scalarization (implementation using scalars) of un-vectorizable
139243789Sdim///   instructions.
140249423Sdim/// InnerLoopVectorizer does not perform any vectorization-legality
141243789Sdim/// checks, and relies on the caller to check for the different legality
142249423Sdim/// aspects. The InnerLoopVectorizer relies on the
143243789Sdim/// LoopVectorizationLegality class to provide information about the induction
144243789Sdim/// and reduction variables that were found to a given vectorization factor.
145249423Sdimclass InnerLoopVectorizer {
146243789Sdimpublic:
147249423Sdim  InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
148249423Sdim                      DominatorTree *DT, DataLayout *DL,
149249423Sdim                      const TargetLibraryInfo *TLI, unsigned VecWidth,
150249423Sdim                      unsigned UnrollFactor)
151249423Sdim      : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
152249423Sdim        VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
153249423Sdim        OldInduction(0), WidenMap(UnrollFactor) {}
154243789Sdim
155243789Sdim  // Perform the actual loop widening (vectorization).
156243789Sdim  void vectorize(LoopVectorizationLegality *Legal) {
157249423Sdim    // Create a new empty loop. Unlink the old loop and connect the new one.
158243789Sdim    createEmptyLoop(Legal);
159249423Sdim    // Widen each instruction in the old loop to a new one in the new loop.
160249423Sdim    // Use the Legality module to find the induction and reduction variables.
161243789Sdim    vectorizeLoop(Legal);
162243789Sdim    // Register the new loop and update the analysis passes.
163243789Sdim    updateAnalysis();
164249423Sdim  }
165243789Sdim
166243789Sdimprivate:
167249423Sdim  /// A small list of PHINodes.
168249423Sdim  typedef SmallVector<PHINode*, 4> PhiVector;
169249423Sdim  /// When we unroll loops we have multiple vector values for each scalar.
170249423Sdim  /// This data structure holds the unrolled and vectorized values that
171249423Sdim  /// originated from one scalar instruction.
172249423Sdim  typedef SmallVector<Value*, 2> VectorParts;
173249423Sdim
174249423Sdim  /// Add code that checks at runtime if the accessed arrays overlap.
175249423Sdim  /// Returns the comparator value or NULL if no check is needed.
176249423Sdim  Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
177249423Sdim                               Instruction *Loc);
178243789Sdim  /// Create an empty loop, based on the loop ranges of the old loop.
179243789Sdim  void createEmptyLoop(LoopVectorizationLegality *Legal);
180243789Sdim  /// Copy and widen the instructions from the old loop.
181243789Sdim  void vectorizeLoop(LoopVectorizationLegality *Legal);
182249423Sdim
183249423Sdim  /// A helper function that computes the predicate of the block BB, assuming
184249423Sdim  /// that the header block of the loop is set to True. It returns the *entry*
185249423Sdim  /// mask for the block BB.
186249423Sdim  VectorParts createBlockInMask(BasicBlock *BB);
187249423Sdim  /// A helper function that computes the predicate of the edge between SRC
188249423Sdim  /// and DST.
189249423Sdim  VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
190249423Sdim
191249423Sdim  /// A helper function to vectorize a single BB within the innermost loop.
192249423Sdim  void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
193249423Sdim                            PhiVector *PV);
194249423Sdim
195243789Sdim  /// Insert the new loop to the loop hierarchy and pass manager
196243789Sdim  /// and update the analysis passes.
197243789Sdim  void updateAnalysis();
198243789Sdim
199243789Sdim  /// This instruction is un-vectorizable. Implement it as a sequence
200243789Sdim  /// of scalars.
201243789Sdim  void scalarizeInstruction(Instruction *Instr);
202243789Sdim
203249423Sdim  /// Vectorize Load and Store instructions,
204249423Sdim  void vectorizeMemoryInstruction(Instruction *Instr,
205249423Sdim                                  LoopVectorizationLegality *Legal);
206249423Sdim
207243789Sdim  /// Create a broadcast instruction. This method generates a broadcast
208243789Sdim  /// instruction (shuffle) for loop invariant values and for the induction
209243789Sdim  /// value. If this is the induction variable then we extend it to N, N+1, ...
210243789Sdim  /// this is needed because each iteration in the loop corresponds to a SIMD
211243789Sdim  /// element.
212243789Sdim  Value *getBroadcastInstrs(Value *V);
213243789Sdim
214249423Sdim  /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
215249423Sdim  /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
216249423Sdim  /// The sequence starts at StartIndex.
217249423Sdim  Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
218243789Sdim
219243789Sdim  /// When we go over instructions in the basic block we rely on previous
220243789Sdim  /// values within the current basic block or on loop invariant values.
221243789Sdim  /// When we widen (vectorize) values we place them in the map. If the values
222243789Sdim  /// are not within the map, they have to be loop invariant, so we simply
223243789Sdim  /// broadcast them into a vector.
224249423Sdim  VectorParts &getVectorValue(Value *V);
225243789Sdim
226249423Sdim  /// Generate a shuffle sequence that will reverse the vector Vec.
227249423Sdim  Value *reverseVector(Value *Vec);
228243789Sdim
229249423Sdim  /// This is a helper class that holds the vectorizer state. It maps scalar
230249423Sdim  /// instructions to vector instructions. When the code is 'unrolled' then
231249423Sdim  /// then a single scalar value is mapped to multiple vector parts. The parts
232249423Sdim  /// are stored in the VectorPart type.
233249423Sdim  struct ValueMap {
234249423Sdim    /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
235249423Sdim    /// are mapped.
236249423Sdim    ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
237243789Sdim
238249423Sdim    /// \return True if 'Key' is saved in the Value Map.
239249423Sdim    bool has(Value *Key) const { return MapStorage.count(Key); }
240249423Sdim
241249423Sdim    /// Initializes a new entry in the map. Sets all of the vector parts to the
242249423Sdim    /// save value in 'Val'.
243249423Sdim    /// \return A reference to a vector with splat values.
244249423Sdim    VectorParts &splat(Value *Key, Value *Val) {
245249423Sdim      VectorParts &Entry = MapStorage[Key];
246249423Sdim      Entry.assign(UF, Val);
247249423Sdim      return Entry;
248249423Sdim    }
249249423Sdim
250249423Sdim    ///\return A reference to the value that is stored at 'Key'.
251249423Sdim    VectorParts &get(Value *Key) {
252249423Sdim      VectorParts &Entry = MapStorage[Key];
253249423Sdim      if (Entry.empty())
254249423Sdim        Entry.resize(UF);
255249423Sdim      assert(Entry.size() == UF);
256249423Sdim      return Entry;
257249423Sdim    }
258249423Sdim
259249423Sdim  private:
260249423Sdim    /// The unroll factor. Each entry in the map stores this number of vector
261249423Sdim    /// elements.
262249423Sdim    unsigned UF;
263249423Sdim
264249423Sdim    /// Map storage. We use std::map and not DenseMap because insertions to a
265249423Sdim    /// dense map invalidates its iterators.
266249423Sdim    std::map<Value *, VectorParts> MapStorage;
267249423Sdim  };
268249423Sdim
269243789Sdim  /// The original loop.
270243789Sdim  Loop *OrigLoop;
271249423Sdim  /// Scev analysis to use.
272243789Sdim  ScalarEvolution *SE;
273249423Sdim  /// Loop Info.
274243789Sdim  LoopInfo *LI;
275249423Sdim  /// Dominator Tree.
276243789Sdim  DominatorTree *DT;
277249423Sdim  /// Data Layout.
278249423Sdim  DataLayout *DL;
279249423Sdim  /// Target Library Info.
280249423Sdim  const TargetLibraryInfo *TLI;
281249423Sdim
282249423Sdim  /// The vectorization SIMD factor to use. Each vector will have this many
283249423Sdim  /// vector elements.
284243789Sdim  unsigned VF;
285249423Sdim  /// The vectorization unroll factor to use. Each scalar is vectorized to this
286249423Sdim  /// many different vector instructions.
287249423Sdim  unsigned UF;
288243789Sdim
289249423Sdim  /// The builder that we use
290243789Sdim  IRBuilder<> Builder;
291243789Sdim
292243789Sdim  // --- Vectorization state ---
293243789Sdim
294243789Sdim  /// The vector-loop preheader.
295243789Sdim  BasicBlock *LoopVectorPreHeader;
296243789Sdim  /// The scalar-loop preheader.
297243789Sdim  BasicBlock *LoopScalarPreHeader;
298243789Sdim  /// Middle Block between the vector and the scalar.
299243789Sdim  BasicBlock *LoopMiddleBlock;
300243789Sdim  ///The ExitBlock of the scalar loop.
301243789Sdim  BasicBlock *LoopExitBlock;
302243789Sdim  ///The vector loop body.
303243789Sdim  BasicBlock *LoopVectorBody;
304243789Sdim  ///The scalar loop body.
305243789Sdim  BasicBlock *LoopScalarBody;
306249423Sdim  /// A list of all bypass blocks. The first block is the entry of the loop.
307249423Sdim  SmallVector<BasicBlock *, 4> LoopBypassBlocks;
308243789Sdim
309243789Sdim  /// The new Induction variable which was added to the new block.
310243789Sdim  PHINode *Induction;
311243789Sdim  /// The induction variable of the old basic block.
312243789Sdim  PHINode *OldInduction;
313249423Sdim  /// Maps scalars to widened vectors.
314243789Sdim  ValueMap WidenMap;
315243789Sdim};
316243789Sdim
317243789Sdim/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
318243789Sdim/// to what vectorization factor.
319243789Sdim/// This class does not look at the profitability of vectorization, only the
320243789Sdim/// legality. This class has two main kinds of checks:
321243789Sdim/// * Memory checks - The code in canVectorizeMemory checks if vectorization
322243789Sdim///   will change the order of memory accesses in a way that will change the
323243789Sdim///   correctness of the program.
324249423Sdim/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
325249423Sdim/// checks for a number of different conditions, such as the availability of a
326249423Sdim/// single induction variable, that all types are supported and vectorize-able,
327249423Sdim/// etc. This code reflects the capabilities of InnerLoopVectorizer.
328249423Sdim/// This class is also used by InnerLoopVectorizer for identifying
329243789Sdim/// induction variable and the different reduction variables.
330243789Sdimclass LoopVectorizationLegality {
331243789Sdimpublic:
332249423Sdim  LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
333249423Sdim                            DominatorTree *DT, TargetTransformInfo* TTI,
334249423Sdim                            AliasAnalysis *AA, TargetLibraryInfo *TLI)
335249423Sdim      : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
336249423Sdim        Induction(0) {}
337243789Sdim
338249423Sdim  /// This enum represents the kinds of reductions that we support.
339243789Sdim  enum ReductionKind {
340249423Sdim    RK_NoReduction, ///< Not a reduction.
341249423Sdim    RK_IntegerAdd,  ///< Sum of integers.
342249423Sdim    RK_IntegerMult, ///< Product of integers.
343249423Sdim    RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
344249423Sdim    RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
345249423Sdim    RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
346249423Sdim    RK_FloatAdd,    ///< Sum of floats.
347249423Sdim    RK_FloatMult    ///< Product of floats.
348243789Sdim  };
349243789Sdim
350249423Sdim  /// This enum represents the kinds of inductions that we support.
351249423Sdim  enum InductionKind {
352249423Sdim    IK_NoInduction,         ///< Not an induction variable.
353249423Sdim    IK_IntInduction,        ///< Integer induction variable. Step = 1.
354249423Sdim    IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
355249423Sdim    IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
356249423Sdim    IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
357249423Sdim  };
358249423Sdim
359243789Sdim  /// This POD struct holds information about reduction variables.
360243789Sdim  struct ReductionDescriptor {
361249423Sdim    ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
362249423Sdim      Kind(RK_NoReduction) {}
363243789Sdim
364249423Sdim    ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
365249423Sdim        : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
366243789Sdim
367243789Sdim    // The starting value of the reduction.
368243789Sdim    // It does not have to be zero!
369243789Sdim    Value *StartValue;
370243789Sdim    // The instruction who's value is used outside the loop.
371243789Sdim    Instruction *LoopExitInstr;
372243789Sdim    // The kind of the reduction.
373243789Sdim    ReductionKind Kind;
374243789Sdim  };
375243789Sdim
376243789Sdim  // This POD struct holds information about the memory runtime legality
377243789Sdim  // check that a group of pointers do not overlap.
378243789Sdim  struct RuntimePointerCheck {
379249423Sdim    RuntimePointerCheck() : Need(false) {}
380249423Sdim
381249423Sdim    /// Reset the state of the pointer runtime information.
382249423Sdim    void reset() {
383249423Sdim      Need = false;
384249423Sdim      Pointers.clear();
385249423Sdim      Starts.clear();
386249423Sdim      Ends.clear();
387249423Sdim    }
388249423Sdim
389249423Sdim    /// Insert a pointer and calculate the start and end SCEVs.
390249423Sdim    void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
391249423Sdim
392243789Sdim    /// This flag indicates if we need to add the runtime check.
393243789Sdim    bool Need;
394243789Sdim    /// Holds the pointers that we need to check.
395243789Sdim    SmallVector<Value*, 2> Pointers;
396249423Sdim    /// Holds the pointer value at the beginning of the loop.
397249423Sdim    SmallVector<const SCEV*, 2> Starts;
398249423Sdim    /// Holds the pointer value at the end of the loop.
399249423Sdim    SmallVector<const SCEV*, 2> Ends;
400243789Sdim  };
401243789Sdim
402249423Sdim  /// A POD for saving information about induction variables.
403249423Sdim  struct InductionInfo {
404249423Sdim    InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
405249423Sdim    InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
406249423Sdim    /// Start value.
407249423Sdim    Value *StartValue;
408249423Sdim    /// Induction kind.
409249423Sdim    InductionKind IK;
410249423Sdim  };
411249423Sdim
412243789Sdim  /// ReductionList contains the reduction descriptors for all
413243789Sdim  /// of the reductions that were found in the loop.
414243789Sdim  typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
415243789Sdim
416249423Sdim  /// InductionList saves induction variables and maps them to the
417249423Sdim  /// induction descriptor.
418249423Sdim  typedef MapVector<PHINode*, InductionInfo> InductionList;
419249423Sdim
420249423Sdim  /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
421249423Sdim  /// respective Store/Load instruction(s) to calculate aliasing.
422249423Sdim  typedef MapVector<Value*, Instruction* > AliasMap;
423249423Sdim  typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
424249423Sdim
425243789Sdim  /// Returns true if it is legal to vectorize this loop.
426243789Sdim  /// This does not mean that it is profitable to vectorize this
427243789Sdim  /// loop, only that it is legal to do so.
428243789Sdim  bool canVectorize();
429243789Sdim
430243789Sdim  /// Returns the Induction variable.
431249423Sdim  PHINode *getInduction() { return Induction; }
432243789Sdim
433243789Sdim  /// Returns the reduction variables found in the loop.
434243789Sdim  ReductionList *getReductionVars() { return &Reductions; }
435243789Sdim
436249423Sdim  /// Returns the induction variables found in the loop.
437249423Sdim  InductionList *getInductionVars() { return &Inductions; }
438249423Sdim
439249423Sdim  /// Returns True if V is an induction variable in this loop.
440249423Sdim  bool isInductionVariable(const Value *V);
441249423Sdim
442249423Sdim  /// Return true if the block BB needs to be predicated in order for the loop
443249423Sdim  /// to be vectorized.
444249423Sdim  bool blockNeedsPredication(BasicBlock *BB);
445249423Sdim
446249423Sdim  /// Check if this  pointer is consecutive when vectorizing. This happens
447249423Sdim  /// when the last index of the GEP is the induction variable, or that the
448249423Sdim  /// pointer itself is an induction variable.
449243789Sdim  /// This check allows us to vectorize A[idx] into a wide load/store.
450249423Sdim  /// Returns:
451249423Sdim  /// 0 - Stride is unknown or non consecutive.
452249423Sdim  /// 1 - Address is consecutive.
453249423Sdim  /// -1 - Address is consecutive, and decreasing.
454249423Sdim  int isConsecutivePtr(Value *Ptr);
455243789Sdim
456243789Sdim  /// Returns true if the value V is uniform within the loop.
457243789Sdim  bool isUniform(Value *V);
458243789Sdim
459243789Sdim  /// Returns true if this instruction will remain scalar after vectorization.
460249423Sdim  bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
461243789Sdim
462243789Sdim  /// Returns the information that we collected about runtime memory check.
463249423Sdim  RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
464243789Sdimprivate:
465243789Sdim  /// Check if a single basic block loop is vectorizable.
466243789Sdim  /// At this point we know that this is a loop with a constant trip count
467243789Sdim  /// and we only need to check individual instructions.
468249423Sdim  bool canVectorizeInstrs();
469243789Sdim
470243789Sdim  /// When we vectorize loops we may change the order in which
471243789Sdim  /// we read and write from memory. This method checks if it is
472243789Sdim  /// legal to vectorize the code, considering only memory constrains.
473249423Sdim  /// Returns true if the loop is vectorizable
474249423Sdim  bool canVectorizeMemory();
475243789Sdim
476249423Sdim  /// Return true if we can vectorize this loop using the IF-conversion
477249423Sdim  /// transformation.
478249423Sdim  bool canVectorizeWithIfConvert();
479249423Sdim
480249423Sdim  /// Collect the variables that need to stay uniform after vectorization.
481249423Sdim  void collectLoopUniforms();
482249423Sdim
483249423Sdim  /// Return true if all of the instructions in the block can be speculatively
484249423Sdim  /// executed.
485249423Sdim  bool blockCanBePredicated(BasicBlock *BB);
486249423Sdim
487243789Sdim  /// Returns True, if 'Phi' is the kind of reduction variable for type
488243789Sdim  /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
489243789Sdim  bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
490243789Sdim  /// Returns true if the instruction I can be a reduction variable of type
491243789Sdim  /// 'Kind'.
492243789Sdim  bool isReductionInstr(Instruction *I, ReductionKind Kind);
493249423Sdim  /// Returns the induction kind of Phi. This function may return NoInduction
494249423Sdim  /// if the PHI is not an induction variable.
495249423Sdim  InductionKind isInductionVariable(PHINode *Phi);
496243789Sdim  /// Return true if can compute the address bounds of Ptr within the loop.
497243789Sdim  bool hasComputableBounds(Value *Ptr);
498249423Sdim  /// Return true if there is the chance of write reorder.
499249423Sdim  bool hasPossibleGlobalWriteReorder(Value *Object,
500249423Sdim                                     Instruction *Inst,
501249423Sdim                                     AliasMultiMap &WriteObjects,
502249423Sdim                                     unsigned MaxByteWidth);
503249423Sdim  /// Return the AA location for a load or a store.
504249423Sdim  AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
505243789Sdim
506249423Sdim
507243789Sdim  /// The loop that we evaluate.
508243789Sdim  Loop *TheLoop;
509243789Sdim  /// Scev analysis.
510243789Sdim  ScalarEvolution *SE;
511243789Sdim  /// DataLayout analysis.
512243789Sdim  DataLayout *DL;
513249423Sdim  /// Dominators.
514249423Sdim  DominatorTree *DT;
515249423Sdim  /// Target Info.
516249423Sdim  TargetTransformInfo *TTI;
517249423Sdim  /// Alias Analysis.
518249423Sdim  AliasAnalysis *AA;
519249423Sdim  /// Target Library Info.
520249423Sdim  TargetLibraryInfo *TLI;
521243789Sdim
522243789Sdim  //  ---  vectorization state --- //
523243789Sdim
524249423Sdim  /// Holds the integer induction variable. This is the counter of the
525249423Sdim  /// loop.
526243789Sdim  PHINode *Induction;
527243789Sdim  /// Holds the reduction variables.
528243789Sdim  ReductionList Reductions;
529249423Sdim  /// Holds all of the induction variables that we found in the loop.
530249423Sdim  /// Notice that inductions don't need to start at zero and that induction
531249423Sdim  /// variables can be pointers.
532249423Sdim  InductionList Inductions;
533249423Sdim
534243789Sdim  /// Allowed outside users. This holds the reduction
535243789Sdim  /// vars which can be accessed from outside the loop.
536243789Sdim  SmallPtrSet<Value*, 4> AllowedExit;
537243789Sdim  /// This set holds the variables which are known to be uniform after
538243789Sdim  /// vectorization.
539243789Sdim  SmallPtrSet<Instruction*, 4> Uniforms;
540243789Sdim  /// We need to check that all of the pointers in this list are disjoint
541243789Sdim  /// at runtime.
542243789Sdim  RuntimePointerCheck PtrRtCheck;
543243789Sdim};
544243789Sdim
545243789Sdim/// LoopVectorizationCostModel - estimates the expected speedups due to
546243789Sdim/// vectorization.
547249423Sdim/// In many cases vectorization is not profitable. This can happen because of
548249423Sdim/// a number of reasons. In this class we mainly attempt to predict the
549249423Sdim/// expected speedup/slowdowns due to the supported instruction set. We use the
550249423Sdim/// TargetTransformInfo to query the different backends for the cost of
551249423Sdim/// different operations.
552243789Sdimclass LoopVectorizationCostModel {
553243789Sdimpublic:
554249423Sdim  LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
555249423Sdim                             LoopVectorizationLegality *Legal,
556249423Sdim                             const TargetTransformInfo &TTI,
557249423Sdim                             DataLayout *DL, const TargetLibraryInfo *TLI)
558249423Sdim      : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
559243789Sdim
560249423Sdim  /// Information about vectorization costs
561249423Sdim  struct VectorizationFactor {
562249423Sdim    unsigned Width; // Vector width with best cost
563249423Sdim    unsigned Cost; // Cost of the loop with that width
564249423Sdim  };
565249423Sdim  /// \return The most profitable vectorization factor and the cost of that VF.
566249423Sdim  /// This method checks every power of two up to VF. If UserVF is not ZERO
567249423Sdim  /// then this vectorization factor will be selected if vectorization is
568249423Sdim  /// possible.
569249423Sdim  VectorizationFactor selectVectorizationFactor(bool OptForSize,
570249423Sdim                                                unsigned UserVF);
571243789Sdim
572249423Sdim  /// \return The size (in bits) of the widest type in the code that
573249423Sdim  /// needs to be vectorized. We ignore values that remain scalar such as
574249423Sdim  /// 64 bit loop indices.
575249423Sdim  unsigned getWidestType();
576249423Sdim
577249423Sdim  /// \return The most profitable unroll factor.
578249423Sdim  /// If UserUF is non-zero then this method finds the best unroll-factor
579249423Sdim  /// based on register pressure and other parameters.
580249423Sdim  /// VF and LoopCost are the selected vectorization factor and the cost of the
581249423Sdim  /// selected VF.
582249423Sdim  unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
583249423Sdim                              unsigned LoopCost);
584249423Sdim
585249423Sdim  /// \brief A struct that represents some properties of the register usage
586249423Sdim  /// of a loop.
587249423Sdim  struct RegisterUsage {
588249423Sdim    /// Holds the number of loop invariant values that are used in the loop.
589249423Sdim    unsigned LoopInvariantRegs;
590249423Sdim    /// Holds the maximum number of concurrent live intervals in the loop.
591249423Sdim    unsigned MaxLocalUsers;
592249423Sdim    /// Holds the number of instructions in the loop.
593249423Sdim    unsigned NumInstructions;
594249423Sdim  };
595249423Sdim
596249423Sdim  /// \return  information about the register usage of the loop.
597249423Sdim  RegisterUsage calculateRegisterUsage();
598249423Sdim
599243789Sdimprivate:
600243789Sdim  /// Returns the expected execution cost. The unit of the cost does
601243789Sdim  /// not matter because we use the 'cost' units to compare different
602243789Sdim  /// vector widths. The cost that is returned is *not* normalized by
603243789Sdim  /// the factor width.
604243789Sdim  unsigned expectedCost(unsigned VF);
605243789Sdim
606243789Sdim  /// Returns the execution time cost of an instruction for a given vector
607243789Sdim  /// width. Vector width of one means scalar.
608243789Sdim  unsigned getInstructionCost(Instruction *I, unsigned VF);
609243789Sdim
610243789Sdim  /// A helper function for converting Scalar types to vector types.
611243789Sdim  /// If the incoming type is void, we return void. If the VF is 1, we return
612243789Sdim  /// the scalar type.
613243789Sdim  static Type* ToVectorTy(Type *Scalar, unsigned VF);
614243789Sdim
615249423Sdim  /// Returns whether the instruction is a load or store and will be a emitted
616249423Sdim  /// as a vector operation.
617249423Sdim  bool isConsecutiveLoadOrStore(Instruction *I);
618249423Sdim
619243789Sdim  /// The loop that we evaluate.
620243789Sdim  Loop *TheLoop;
621243789Sdim  /// Scev analysis.
622243789Sdim  ScalarEvolution *SE;
623249423Sdim  /// Loop Info analysis.
624249423Sdim  LoopInfo *LI;
625243789Sdim  /// Vectorization legality.
626243789Sdim  LoopVectorizationLegality *Legal;
627243789Sdim  /// Vector target information.
628249423Sdim  const TargetTransformInfo &TTI;
629249423Sdim  /// Target data layout information.
630249423Sdim  DataLayout *DL;
631249423Sdim  /// Target Library Info.
632249423Sdim  const TargetLibraryInfo *TLI;
633243789Sdim};
634243789Sdim
635249423Sdim/// The LoopVectorize Pass.
636243789Sdimstruct LoopVectorize : public LoopPass {
637249423Sdim  /// Pass identification, replacement for typeid
638249423Sdim  static char ID;
639243789Sdim
640249423Sdim  explicit LoopVectorize() : LoopPass(ID) {
641243789Sdim    initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
642243789Sdim  }
643243789Sdim
644243789Sdim  ScalarEvolution *SE;
645243789Sdim  DataLayout *DL;
646243789Sdim  LoopInfo *LI;
647243789Sdim  TargetTransformInfo *TTI;
648243789Sdim  DominatorTree *DT;
649249423Sdim  AliasAnalysis *AA;
650249423Sdim  TargetLibraryInfo *TLI;
651243789Sdim
652243789Sdim  virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
653243789Sdim    // We only vectorize innermost loops.
654243789Sdim    if (!L->empty())
655243789Sdim      return false;
656243789Sdim
657243789Sdim    SE = &getAnalysis<ScalarEvolution>();
658243789Sdim    DL = getAnalysisIfAvailable<DataLayout>();
659243789Sdim    LI = &getAnalysis<LoopInfo>();
660249423Sdim    TTI = &getAnalysis<TargetTransformInfo>();
661243789Sdim    DT = &getAnalysis<DominatorTree>();
662249423Sdim    AA = getAnalysisIfAvailable<AliasAnalysis>();
663249423Sdim    TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
664243789Sdim
665243789Sdim    DEBUG(dbgs() << "LV: Checking a loop in \"" <<
666243789Sdim          L->getHeader()->getParent()->getName() << "\"\n");
667243789Sdim
668243789Sdim    // Check if it is legal to vectorize the loop.
669249423Sdim    LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
670243789Sdim    if (!LVL.canVectorize()) {
671243789Sdim      DEBUG(dbgs() << "LV: Not vectorizing.\n");
672243789Sdim      return false;
673243789Sdim    }
674243789Sdim
675249423Sdim    // Use the cost model.
676249423Sdim    LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
677243789Sdim
678249423Sdim    // Check the function attributes to find out if this function should be
679249423Sdim    // optimized for size.
680249423Sdim    Function *F = L->getHeader()->getParent();
681249423Sdim    Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
682249423Sdim    Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
683249423Sdim    unsigned FnIndex = AttributeSet::FunctionIndex;
684249423Sdim    bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
685249423Sdim    bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
686243789Sdim
687249423Sdim    if (NoFloat) {
688249423Sdim      DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
689249423Sdim            "attribute is used.\n");
690249423Sdim      return false;
691243789Sdim    }
692243789Sdim
693249423Sdim    // Select the optimal vectorization factor.
694249423Sdim    LoopVectorizationCostModel::VectorizationFactor VF;
695249423Sdim    VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
696249423Sdim    // Select the unroll factor.
697249423Sdim    unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
698249423Sdim                                        VF.Width, VF.Cost);
699243789Sdim
700249423Sdim    if (VF.Width == 1) {
701249423Sdim      DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
702249423Sdim      return false;
703249423Sdim    }
704249423Sdim
705249423Sdim    DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
706249423Sdim          F->getParent()->getModuleIdentifier()<<"\n");
707249423Sdim    DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
708249423Sdim
709249423Sdim    // If we decided that it is *legal* to vectorize the loop then do it.
710249423Sdim    InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
711243789Sdim    LB.vectorize(&LVL);
712243789Sdim
713243789Sdim    DEBUG(verifyFunction(*L->getHeader()->getParent()));
714243789Sdim    return true;
715243789Sdim  }
716243789Sdim
717243789Sdim  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
718243789Sdim    LoopPass::getAnalysisUsage(AU);
719243789Sdim    AU.addRequiredID(LoopSimplifyID);
720243789Sdim    AU.addRequiredID(LCSSAID);
721249423Sdim    AU.addRequired<DominatorTree>();
722243789Sdim    AU.addRequired<LoopInfo>();
723243789Sdim    AU.addRequired<ScalarEvolution>();
724249423Sdim    AU.addRequired<TargetTransformInfo>();
725243789Sdim    AU.addPreserved<LoopInfo>();
726243789Sdim    AU.addPreserved<DominatorTree>();
727243789Sdim  }
728243789Sdim
729243789Sdim};
730243789Sdim
731249423Sdim} // end anonymous namespace
732249423Sdim
733249423Sdim//===----------------------------------------------------------------------===//
734249423Sdim// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
735249423Sdim// LoopVectorizationCostModel.
736249423Sdim//===----------------------------------------------------------------------===//
737249423Sdim
738249423Sdimvoid
739249423SdimLoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
740249423Sdim                                                       Loop *Lp, Value *Ptr) {
741249423Sdim  const SCEV *Sc = SE->getSCEV(Ptr);
742249423Sdim  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
743249423Sdim  assert(AR && "Invalid addrec expression");
744249423Sdim  const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
745249423Sdim  const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
746249423Sdim  Pointers.push_back(Ptr);
747249423Sdim  Starts.push_back(AR->getStart());
748249423Sdim  Ends.push_back(ScEnd);
749249423Sdim}
750249423Sdim
751249423SdimValue *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
752249423Sdim  // Save the current insertion location.
753249423Sdim  Instruction *Loc = Builder.GetInsertPoint();
754249423Sdim
755249423Sdim  // We need to place the broadcast of invariant variables outside the loop.
756249423Sdim  Instruction *Instr = dyn_cast<Instruction>(V);
757249423Sdim  bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
758249423Sdim  bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
759249423Sdim
760249423Sdim  // Place the code for broadcasting invariant variables in the new preheader.
761249423Sdim  if (Invariant)
762249423Sdim    Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
763249423Sdim
764243789Sdim  // Broadcast the scalar into all locations in the vector.
765249423Sdim  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
766249423Sdim
767249423Sdim  // Restore the builder insertion point.
768249423Sdim  if (Invariant)
769249423Sdim    Builder.SetInsertPoint(Loc);
770249423Sdim
771243789Sdim  return Shuf;
772243789Sdim}
773243789Sdim
774249423SdimValue *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
775249423Sdim                                                 bool Negate) {
776243789Sdim  assert(Val->getType()->isVectorTy() && "Must be a vector");
777243789Sdim  assert(Val->getType()->getScalarType()->isIntegerTy() &&
778243789Sdim         "Elem must be an integer");
779243789Sdim  // Create the types.
780243789Sdim  Type *ITy = Val->getType()->getScalarType();
781243789Sdim  VectorType *Ty = cast<VectorType>(Val->getType());
782249423Sdim  int VLen = Ty->getNumElements();
783243789Sdim  SmallVector<Constant*, 8> Indices;
784243789Sdim
785243789Sdim  // Create a vector of consecutive numbers from zero to VF.
786249423Sdim  for (int i = 0; i < VLen; ++i) {
787249423Sdim    int Idx = Negate ? (-i): i;
788249423Sdim    Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
789249423Sdim  }
790243789Sdim
791243789Sdim  // Add the consecutive indices to the vector value.
792243789Sdim  Constant *Cv = ConstantVector::get(Indices);
793243789Sdim  assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
794243789Sdim  return Builder.CreateAdd(Val, Cv, "induction");
795243789Sdim}
796243789Sdim
797249423Sdimint LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
798249423Sdim  assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
799249423Sdim  // Make sure that the pointer does not point to structs.
800249423Sdim  if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
801249423Sdim    return 0;
802249423Sdim
803249423Sdim  // If this value is a pointer induction variable we know it is consecutive.
804249423Sdim  PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
805249423Sdim  if (Phi && Inductions.count(Phi)) {
806249423Sdim    InductionInfo II = Inductions[Phi];
807249423Sdim    if (IK_PtrInduction == II.IK)
808249423Sdim      return 1;
809249423Sdim    else if (IK_ReversePtrInduction == II.IK)
810249423Sdim      return -1;
811249423Sdim  }
812249423Sdim
813243789Sdim  GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
814243789Sdim  if (!Gep)
815249423Sdim    return 0;
816243789Sdim
817243789Sdim  unsigned NumOperands = Gep->getNumOperands();
818243789Sdim  Value *LastIndex = Gep->getOperand(NumOperands - 1);
819243789Sdim
820249423Sdim  Value *GpPtr = Gep->getPointerOperand();
821249423Sdim  // If this GEP value is a consecutive pointer induction variable and all of
822249423Sdim  // the indices are constant then we know it is consecutive. We can
823249423Sdim  Phi = dyn_cast<PHINode>(GpPtr);
824249423Sdim  if (Phi && Inductions.count(Phi)) {
825249423Sdim
826249423Sdim    // Make sure that the pointer does not point to structs.
827249423Sdim    PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
828249423Sdim    if (GepPtrType->getElementType()->isAggregateType())
829249423Sdim      return 0;
830249423Sdim
831249423Sdim    // Make sure that all of the index operands are loop invariant.
832249423Sdim    for (unsigned i = 1; i < NumOperands; ++i)
833249423Sdim      if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
834249423Sdim        return 0;
835249423Sdim
836249423Sdim    InductionInfo II = Inductions[Phi];
837249423Sdim    if (IK_PtrInduction == II.IK)
838249423Sdim      return 1;
839249423Sdim    else if (IK_ReversePtrInduction == II.IK)
840249423Sdim      return -1;
841249423Sdim  }
842249423Sdim
843243789Sdim  // Check that all of the gep indices are uniform except for the last.
844243789Sdim  for (unsigned i = 0; i < NumOperands - 1; ++i)
845243789Sdim    if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
846249423Sdim      return 0;
847243789Sdim
848249423Sdim  // We can emit wide load/stores only if the last index is the induction
849243789Sdim  // variable.
850243789Sdim  const SCEV *Last = SE->getSCEV(LastIndex);
851243789Sdim  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
852243789Sdim    const SCEV *Step = AR->getStepRecurrence(*SE);
853243789Sdim
854243789Sdim    // The memory is consecutive because the last index is consecutive
855243789Sdim    // and all other indices are loop invariant.
856243789Sdim    if (Step->isOne())
857249423Sdim      return 1;
858249423Sdim    if (Step->isAllOnesValue())
859249423Sdim      return -1;
860243789Sdim  }
861243789Sdim
862249423Sdim  return 0;
863243789Sdim}
864243789Sdim
865243789Sdimbool LoopVectorizationLegality::isUniform(Value *V) {
866243789Sdim  return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
867243789Sdim}
868243789Sdim
869249423SdimInnerLoopVectorizer::VectorParts&
870249423SdimInnerLoopVectorizer::getVectorValue(Value *V) {
871249423Sdim  assert(V != Induction && "The new induction variable should not be used.");
872243789Sdim  assert(!V->getType()->isVectorTy() && "Can't widen a vector");
873243789Sdim
874249423Sdim  // If we have this scalar in the map, return it.
875249423Sdim  if (WidenMap.has(V))
876249423Sdim    return WidenMap.get(V);
877249423Sdim
878249423Sdim  // If this scalar is unknown, assume that it is a constant or that it is
879249423Sdim  // loop invariant. Broadcast V and save the value for future uses.
880243789Sdim  Value *B = getBroadcastInstrs(V);
881249423Sdim  return WidenMap.splat(V, B);
882243789Sdim}
883243789Sdim
884249423SdimValue *InnerLoopVectorizer::reverseVector(Value *Vec) {
885249423Sdim  assert(Vec->getType()->isVectorTy() && "Invalid type");
886249423Sdim  SmallVector<Constant*, 8> ShuffleMask;
887243789Sdim  for (unsigned i = 0; i < VF; ++i)
888249423Sdim    ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
889243789Sdim
890249423Sdim  return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
891249423Sdim                                     ConstantVector::get(ShuffleMask),
892249423Sdim                                     "reverse");
893243789Sdim}
894243789Sdim
895249423Sdim
896249423Sdimvoid InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
897249423Sdim                                             LoopVectorizationLegality *Legal) {
898249423Sdim  // Attempt to issue a wide load.
899249423Sdim  LoadInst *LI = dyn_cast<LoadInst>(Instr);
900249423Sdim  StoreInst *SI = dyn_cast<StoreInst>(Instr);
901249423Sdim
902249423Sdim  assert((LI || SI) && "Invalid Load/Store instruction");
903249423Sdim
904249423Sdim  Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
905249423Sdim  Type *DataTy = VectorType::get(ScalarDataTy, VF);
906249423Sdim  Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
907249423Sdim  unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
908249423Sdim
909249423Sdim  // If the pointer is loop invariant or if it is non consecutive,
910249423Sdim  // scalarize the load.
911249423Sdim  int Stride = Legal->isConsecutivePtr(Ptr);
912249423Sdim  bool Reverse = Stride < 0;
913249423Sdim  bool UniformLoad = LI && Legal->isUniform(Ptr);
914249423Sdim  if (Stride == 0 || UniformLoad)
915249423Sdim    return scalarizeInstruction(Instr);
916249423Sdim
917249423Sdim  Constant *Zero = Builder.getInt32(0);
918249423Sdim  VectorParts &Entry = WidenMap.get(Instr);
919249423Sdim
920249423Sdim  // Handle consecutive loads/stores.
921249423Sdim  GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
922249423Sdim  if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
923249423Sdim    Value *PtrOperand = Gep->getPointerOperand();
924249423Sdim    Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
925249423Sdim    FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
926249423Sdim
927249423Sdim    // Create the new GEP with the new induction variable.
928249423Sdim    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
929249423Sdim    Gep2->setOperand(0, FirstBasePtr);
930249423Sdim    Gep2->setName("gep.indvar.base");
931249423Sdim    Ptr = Builder.Insert(Gep2);
932249423Sdim  } else if (Gep) {
933249423Sdim    assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
934249423Sdim                               OrigLoop) && "Base ptr must be invariant");
935249423Sdim
936249423Sdim    // The last index does not have to be the induction. It can be
937249423Sdim    // consecutive and be a function of the index. For example A[I+1];
938249423Sdim    unsigned NumOperands = Gep->getNumOperands();
939249423Sdim
940249423Sdim    Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
941249423Sdim    VectorParts &GEPParts = getVectorValue(LastGepOperand);
942249423Sdim    Value *LastIndex = GEPParts[0];
943249423Sdim    LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
944249423Sdim
945249423Sdim    // Create the new GEP with the new induction variable.
946249423Sdim    GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
947249423Sdim    Gep2->setOperand(NumOperands - 1, LastIndex);
948249423Sdim    Gep2->setName("gep.indvar.idx");
949249423Sdim    Ptr = Builder.Insert(Gep2);
950249423Sdim  } else {
951249423Sdim    // Use the induction element ptr.
952249423Sdim    assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
953249423Sdim    VectorParts &PtrVal = getVectorValue(Ptr);
954249423Sdim    Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
955249423Sdim  }
956249423Sdim
957249423Sdim  // Handle Stores:
958249423Sdim  if (SI) {
959249423Sdim    assert(!Legal->isUniform(SI->getPointerOperand()) &&
960249423Sdim           "We do not allow storing to uniform addresses");
961249423Sdim
962249423Sdim    VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
963249423Sdim    for (unsigned Part = 0; Part < UF; ++Part) {
964249423Sdim      // Calculate the pointer for the specific unroll-part.
965249423Sdim      Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
966249423Sdim
967249423Sdim      if (Reverse) {
968249423Sdim        // If we store to reverse consecutive memory locations then we need
969249423Sdim        // to reverse the order of elements in the stored value.
970249423Sdim        StoredVal[Part] = reverseVector(StoredVal[Part]);
971249423Sdim        // If the address is consecutive but reversed, then the
972249423Sdim        // wide store needs to start at the last vector element.
973249423Sdim        PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
974249423Sdim        PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
975249423Sdim      }
976249423Sdim
977249423Sdim      Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
978249423Sdim      Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
979249423Sdim    }
980249423Sdim  }
981249423Sdim
982249423Sdim  for (unsigned Part = 0; Part < UF; ++Part) {
983249423Sdim    // Calculate the pointer for the specific unroll-part.
984249423Sdim    Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
985249423Sdim
986249423Sdim    if (Reverse) {
987249423Sdim      // If the address is consecutive but reversed, then the
988249423Sdim      // wide store needs to start at the last vector element.
989249423Sdim      PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
990249423Sdim      PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
991249423Sdim    }
992249423Sdim
993249423Sdim    Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
994249423Sdim    Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
995249423Sdim    cast<LoadInst>(LI)->setAlignment(Alignment);
996249423Sdim    Entry[Part] = Reverse ? reverseVector(LI) :  LI;
997249423Sdim  }
998249423Sdim}
999249423Sdim
1000249423Sdimvoid InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1001243789Sdim  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1002243789Sdim  // Holds vector parameters or scalars, in case of uniform vals.
1003249423Sdim  SmallVector<VectorParts, 4> Params;
1004243789Sdim
1005243789Sdim  // Find all of the vectorized parameters.
1006243789Sdim  for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1007243789Sdim    Value *SrcOp = Instr->getOperand(op);
1008243789Sdim
1009243789Sdim    // If we are accessing the old induction variable, use the new one.
1010243789Sdim    if (SrcOp == OldInduction) {
1011249423Sdim      Params.push_back(getVectorValue(SrcOp));
1012243789Sdim      continue;
1013243789Sdim    }
1014243789Sdim
1015243789Sdim    // Try using previously calculated values.
1016243789Sdim    Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1017243789Sdim
1018243789Sdim    // If the src is an instruction that appeared earlier in the basic block
1019243789Sdim    // then it should already be vectorized.
1020249423Sdim    if (SrcInst && OrigLoop->contains(SrcInst)) {
1021249423Sdim      assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1022243789Sdim      // The parameter is a vector value from earlier.
1023249423Sdim      Params.push_back(WidenMap.get(SrcInst));
1024243789Sdim    } else {
1025243789Sdim      // The parameter is a scalar from outside the loop. Maybe even a constant.
1026249423Sdim      VectorParts Scalars;
1027249423Sdim      Scalars.append(UF, SrcOp);
1028249423Sdim      Params.push_back(Scalars);
1029243789Sdim    }
1030243789Sdim  }
1031243789Sdim
1032243789Sdim  assert(Params.size() == Instr->getNumOperands() &&
1033243789Sdim         "Invalid number of operands");
1034243789Sdim
1035243789Sdim  // Does this instruction return a value ?
1036243789Sdim  bool IsVoidRetTy = Instr->getType()->isVoidTy();
1037243789Sdim
1038249423Sdim  Value *UndefVec = IsVoidRetTy ? 0 :
1039249423Sdim    UndefValue::get(VectorType::get(Instr->getType(), VF));
1040249423Sdim  // Create a new entry in the WidenMap and initialize it to Undef or Null.
1041249423Sdim  VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1042243789Sdim
1043243789Sdim  // For each scalar that we create:
1044249423Sdim  for (unsigned Width = 0; Width < VF; ++Width) {
1045249423Sdim    // For each vector unroll 'part':
1046249423Sdim    for (unsigned Part = 0; Part < UF; ++Part) {
1047249423Sdim      Instruction *Cloned = Instr->clone();
1048249423Sdim      if (!IsVoidRetTy)
1049249423Sdim        Cloned->setName(Instr->getName() + ".cloned");
1050249423Sdim      // Replace the operands of the cloned instrucions with extracted scalars.
1051249423Sdim      for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1052249423Sdim        Value *Op = Params[op][Part];
1053249423Sdim        // Param is a vector. Need to extract the right lane.
1054249423Sdim        if (Op->getType()->isVectorTy())
1055249423Sdim          Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1056249423Sdim        Cloned->setOperand(op, Op);
1057249423Sdim      }
1058249423Sdim
1059249423Sdim      // Place the cloned scalar in the new loop.
1060249423Sdim      Builder.Insert(Cloned);
1061249423Sdim
1062249423Sdim      // If the original scalar returns a value we need to place it in a vector
1063249423Sdim      // so that future users will be able to use it.
1064249423Sdim      if (!IsVoidRetTy)
1065249423Sdim        VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1066249423Sdim                                                       Builder.getInt32(Width));
1067243789Sdim    }
1068249423Sdim  }
1069249423Sdim}
1070243789Sdim
1071249423SdimInstruction *
1072249423SdimInnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1073249423Sdim                                     Instruction *Loc) {
1074249423Sdim  LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1075249423Sdim  Legal->getRuntimePointerCheck();
1076243789Sdim
1077249423Sdim  if (!PtrRtCheck->Need)
1078249423Sdim    return NULL;
1079249423Sdim
1080249423Sdim  Instruction *MemoryRuntimeCheck = 0;
1081249423Sdim  unsigned NumPointers = PtrRtCheck->Pointers.size();
1082249423Sdim  SmallVector<Value* , 2> Starts;
1083249423Sdim  SmallVector<Value* , 2> Ends;
1084249423Sdim
1085249423Sdim  SCEVExpander Exp(*SE, "induction");
1086249423Sdim
1087249423Sdim  // Use this type for pointer arithmetic.
1088249423Sdim  Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1089249423Sdim
1090249423Sdim  for (unsigned i = 0; i < NumPointers; ++i) {
1091249423Sdim    Value *Ptr = PtrRtCheck->Pointers[i];
1092249423Sdim    const SCEV *Sc = SE->getSCEV(Ptr);
1093249423Sdim
1094249423Sdim    if (SE->isLoopInvariant(Sc, OrigLoop)) {
1095249423Sdim      DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1096249423Sdim            *Ptr <<"\n");
1097249423Sdim      Starts.push_back(Ptr);
1098249423Sdim      Ends.push_back(Ptr);
1099249423Sdim    } else {
1100249423Sdim      DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1101249423Sdim
1102249423Sdim      Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1103249423Sdim      Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1104249423Sdim      Starts.push_back(Start);
1105249423Sdim      Ends.push_back(End);
1106249423Sdim    }
1107243789Sdim  }
1108243789Sdim
1109249423Sdim  IRBuilder<> ChkBuilder(Loc);
1110249423Sdim
1111249423Sdim  for (unsigned i = 0; i < NumPointers; ++i) {
1112249423Sdim    for (unsigned j = i+1; j < NumPointers; ++j) {
1113249423Sdim      Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1114249423Sdim      Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1115249423Sdim      Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1116249423Sdim      Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1117249423Sdim
1118249423Sdim      Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1119249423Sdim      Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1120249423Sdim      Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1121249423Sdim      if (MemoryRuntimeCheck)
1122249423Sdim        IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1123249423Sdim                                         "conflict.rdx");
1124249423Sdim
1125249423Sdim      MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1126249423Sdim    }
1127249423Sdim  }
1128249423Sdim
1129249423Sdim  return MemoryRuntimeCheck;
1130243789Sdim}
1131243789Sdim
1132243789Sdimvoid
1133249423SdimInnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1134243789Sdim  /*
1135243789Sdim   In this function we generate a new loop. The new loop will contain
1136243789Sdim   the vectorized instructions while the old loop will continue to run the
1137243789Sdim   scalar remainder.
1138243789Sdim
1139249423Sdim       [ ] <-- vector loop bypass (may consist of multiple blocks).
1140249423Sdim     /  |
1141249423Sdim    /   v
1142249423Sdim   |   [ ]     <-- vector pre header.
1143249423Sdim   |    |
1144249423Sdim   |    v
1145249423Sdim   |   [  ] \
1146249423Sdim   |   [  ]_|   <-- vector loop.
1147249423Sdim   |    |
1148249423Sdim    \   v
1149249423Sdim      >[ ]   <--- middle-block.
1150249423Sdim     /  |
1151249423Sdim    /   v
1152249423Sdim   |   [ ]     <--- new preheader.
1153249423Sdim   |    |
1154249423Sdim   |    v
1155249423Sdim   |   [ ] \
1156249423Sdim   |   [ ]_|   <-- old scalar loop to handle remainder.
1157249423Sdim    \   |
1158249423Sdim     \  v
1159249423Sdim      >[ ]     <-- exit block.
1160243789Sdim   ...
1161243789Sdim   */
1162243789Sdim
1163249423Sdim  BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1164249423Sdim  BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1165249423Sdim  BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1166249423Sdim  assert(ExitBlock && "Must have an exit block");
1167249423Sdim
1168249423Sdim  // Mark the old scalar loop with metadata that tells us not to vectorize this
1169249423Sdim  // loop again if we run into it.
1170249423Sdim  MDNode *MD = MDNode::get(OldBasicBlock->getContext(), ArrayRef<Value*>());
1171249423Sdim  OldBasicBlock->getTerminator()->setMetadata(AlreadyVectorizedMDName, MD);
1172249423Sdim
1173249423Sdim  // Some loops have a single integer induction variable, while other loops
1174249423Sdim  // don't. One example is c++ iterators that often have multiple pointer
1175249423Sdim  // induction variables. In the code below we also support a case where we
1176249423Sdim  // don't have a single induction variable.
1177243789Sdim  OldInduction = Legal->getInduction();
1178249423Sdim  Type *IdxTy = OldInduction ? OldInduction->getType() :
1179249423Sdim  DL->getIntPtrType(SE->getContext());
1180243789Sdim
1181243789Sdim  // Find the loop boundaries.
1182249423Sdim  const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1183243789Sdim  assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1184243789Sdim
1185243789Sdim  // Get the total trip count from the count by adding 1.
1186243789Sdim  ExitCount = SE->getAddExpr(ExitCount,
1187243789Sdim                             SE->getConstant(ExitCount->getType(), 1));
1188243789Sdim
1189249423Sdim  // Expand the trip count and place the new instructions in the preheader.
1190249423Sdim  // Notice that the pre-header does not change, only the loop body.
1191249423Sdim  SCEVExpander Exp(*SE, "induction");
1192243789Sdim
1193249423Sdim  // Count holds the overall loop count (N).
1194249423Sdim  Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1195249423Sdim                                   BypassBlock->getTerminator());
1196243789Sdim
1197249423Sdim  // The loop index does not have to start at Zero. Find the original start
1198249423Sdim  // value from the induction PHI node. If we don't have an induction variable
1199249423Sdim  // then we know that it starts at zero.
1200249423Sdim  Value *StartIdx = OldInduction ?
1201249423Sdim  OldInduction->getIncomingValueForBlock(BypassBlock):
1202249423Sdim  ConstantInt::get(IdxTy, 0);
1203249423Sdim
1204243789Sdim  assert(BypassBlock && "Invalid loop structure");
1205249423Sdim  LoopBypassBlocks.push_back(BypassBlock);
1206243789Sdim
1207249423Sdim  // Split the single block loop into the two loop structure described above.
1208243789Sdim  BasicBlock *VectorPH =
1209249423Sdim  BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1210249423Sdim  BasicBlock *VecBody =
1211249423Sdim  VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1212249423Sdim  BasicBlock *MiddleBlock =
1213249423Sdim  VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1214243789Sdim  BasicBlock *ScalarPH =
1215249423Sdim  MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1216243789Sdim
1217243789Sdim  // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1218243789Sdim  // inside the loop.
1219243789Sdim  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1220243789Sdim
1221243789Sdim  // Generate the induction variable.
1222243789Sdim  Induction = Builder.CreatePHI(IdxTy, 2, "index");
1223249423Sdim  // The loop step is equal to the vectorization factor (num of SIMD elements)
1224249423Sdim  // times the unroll factor (num of SIMD instructions).
1225249423Sdim  Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1226243789Sdim
1227249423Sdim  // This is the IR builder that we use to add all of the logic for bypassing
1228249423Sdim  // the new vector loop.
1229249423Sdim  IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1230243789Sdim
1231249423Sdim  // We may need to extend the index in case there is a type mismatch.
1232249423Sdim  // We know that the count starts at zero and does not overflow.
1233249423Sdim  if (Count->getType() != IdxTy) {
1234249423Sdim    // The exit count can be of pointer type. Convert it to the correct
1235249423Sdim    // integer type.
1236249423Sdim    if (ExitCount->getType()->isPointerTy())
1237249423Sdim      Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1238249423Sdim    else
1239249423Sdim      Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1240249423Sdim  }
1241243789Sdim
1242243789Sdim  // Add the start index to the loop count to get the new end index.
1243249423Sdim  Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1244243789Sdim
1245243789Sdim  // Now we need to generate the expression for N - (N % VF), which is
1246243789Sdim  // the part that the vectorized body will execute.
1247249423Sdim  Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1248249423Sdim  Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1249249423Sdim  Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1250249423Sdim                                                     "end.idx.rnd.down");
1251243789Sdim
1252249423Sdim  // Now, compare the new count to zero. If it is zero skip the vector loop and
1253249423Sdim  // jump to the scalar loop.
1254249423Sdim  Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1255249423Sdim                                          "cmp.zero");
1256243789Sdim
1257249423Sdim  BasicBlock *LastBypassBlock = BypassBlock;
1258243789Sdim
1259249423Sdim  // Generate the code that checks in runtime if arrays overlap. We put the
1260249423Sdim  // checks into a separate block to make the more common case of few elements
1261249423Sdim  // faster.
1262249423Sdim  Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1263249423Sdim                                                 BypassBlock->getTerminator());
1264249423Sdim  if (MemRuntimeCheck) {
1265249423Sdim    // Create a new block containing the memory check.
1266249423Sdim    BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1267249423Sdim                                                          "vector.memcheck");
1268249423Sdim    LoopBypassBlocks.push_back(CheckBlock);
1269243789Sdim
1270249423Sdim    // Replace the branch into the memory check block with a conditional branch
1271249423Sdim    // for the "few elements case".
1272249423Sdim    Instruction *OldTerm = BypassBlock->getTerminator();
1273249423Sdim    BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1274249423Sdim    OldTerm->eraseFromParent();
1275243789Sdim
1276249423Sdim    Cmp = MemRuntimeCheck;
1277249423Sdim    LastBypassBlock = CheckBlock;
1278249423Sdim  }
1279243789Sdim
1280249423Sdim  LastBypassBlock->getTerminator()->eraseFromParent();
1281249423Sdim  BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1282249423Sdim                     LastBypassBlock);
1283249423Sdim
1284249423Sdim  // We are going to resume the execution of the scalar loop.
1285249423Sdim  // Go over all of the induction variables that we found and fix the
1286249423Sdim  // PHIs that are left in the scalar version of the loop.
1287249423Sdim  // The starting values of PHI nodes depend on the counter of the last
1288249423Sdim  // iteration in the vectorized loop.
1289249423Sdim  // If we come from a bypass edge then we need to start from the original
1290249423Sdim  // start value.
1291249423Sdim
1292249423Sdim  // This variable saves the new starting index for the scalar loop.
1293249423Sdim  PHINode *ResumeIndex = 0;
1294249423Sdim  LoopVectorizationLegality::InductionList::iterator I, E;
1295249423Sdim  LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1296249423Sdim  for (I = List->begin(), E = List->end(); I != E; ++I) {
1297249423Sdim    PHINode *OrigPhi = I->first;
1298249423Sdim    LoopVectorizationLegality::InductionInfo II = I->second;
1299249423Sdim    PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1300249423Sdim                                         MiddleBlock->getTerminator());
1301249423Sdim    Value *EndValue = 0;
1302249423Sdim    switch (II.IK) {
1303249423Sdim    case LoopVectorizationLegality::IK_NoInduction:
1304249423Sdim      llvm_unreachable("Unknown induction");
1305249423Sdim    case LoopVectorizationLegality::IK_IntInduction: {
1306249423Sdim      // Handle the integer induction counter:
1307249423Sdim      assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1308249423Sdim      assert(OrigPhi == OldInduction && "Unknown integer PHI");
1309249423Sdim      // We know what the end value is.
1310249423Sdim      EndValue = IdxEndRoundDown;
1311249423Sdim      // We also know which PHI node holds it.
1312249423Sdim      ResumeIndex = ResumeVal;
1313249423Sdim      break;
1314243789Sdim    }
1315249423Sdim    case LoopVectorizationLegality::IK_ReverseIntInduction: {
1316249423Sdim      // Convert the CountRoundDown variable to the PHI size.
1317249423Sdim      unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1318249423Sdim      unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1319249423Sdim      Value *CRD = CountRoundDown;
1320249423Sdim      if (CRDSize > IISize)
1321249423Sdim        CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1322249423Sdim                               II.StartValue->getType(), "tr.crd",
1323249423Sdim                               LoopBypassBlocks.back()->getTerminator());
1324249423Sdim      else if (CRDSize < IISize)
1325249423Sdim        CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1326249423Sdim                               II.StartValue->getType(),
1327249423Sdim                               "sext.crd",
1328249423Sdim                               LoopBypassBlocks.back()->getTerminator());
1329249423Sdim      // Handle reverse integer induction counter:
1330249423Sdim      EndValue =
1331249423Sdim        BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1332249423Sdim                                  LoopBypassBlocks.back()->getTerminator());
1333249423Sdim      break;
1334249423Sdim    }
1335249423Sdim    case LoopVectorizationLegality::IK_PtrInduction: {
1336249423Sdim      // For pointer induction variables, calculate the offset using
1337249423Sdim      // the end index.
1338249423Sdim      EndValue =
1339249423Sdim        GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1340249423Sdim                                  LoopBypassBlocks.back()->getTerminator());
1341249423Sdim      break;
1342249423Sdim    }
1343249423Sdim    case LoopVectorizationLegality::IK_ReversePtrInduction: {
1344249423Sdim      // The value at the end of the loop for the reverse pointer is calculated
1345249423Sdim      // by creating a GEP with a negative index starting from the start value.
1346249423Sdim      Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1347249423Sdim      Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1348249423Sdim                                  "rev.ind.end",
1349249423Sdim                                  LoopBypassBlocks.back()->getTerminator());
1350249423Sdim      EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1351249423Sdim                                  "rev.ptr.ind.end",
1352249423Sdim                                  LoopBypassBlocks.back()->getTerminator());
1353249423Sdim      break;
1354249423Sdim    }
1355249423Sdim    }// end of case
1356243789Sdim
1357249423Sdim    // The new PHI merges the original incoming value, in case of a bypass,
1358249423Sdim    // or the value at the end of the vectorized loop.
1359249423Sdim    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1360249423Sdim      ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1361249423Sdim    ResumeVal->addIncoming(EndValue, VecBody);
1362249423Sdim
1363249423Sdim    // Fix the scalar body counter (PHI node).
1364249423Sdim    unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1365249423Sdim    OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1366243789Sdim  }
1367243789Sdim
1368249423Sdim  // If we are generating a new induction variable then we also need to
1369249423Sdim  // generate the code that calculates the exit value. This value is not
1370249423Sdim  // simply the end of the counter because we may skip the vectorized body
1371249423Sdim  // in case of a runtime check.
1372249423Sdim  if (!OldInduction){
1373249423Sdim    assert(!ResumeIndex && "Unexpected resume value found");
1374249423Sdim    ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1375249423Sdim                                  MiddleBlock->getTerminator());
1376249423Sdim    for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1377249423Sdim      ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1378249423Sdim    ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1379249423Sdim  }
1380243789Sdim
1381249423Sdim  // Make sure that we found the index where scalar loop needs to continue.
1382249423Sdim  assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1383249423Sdim         "Invalid resume Index");
1384243789Sdim
1385243789Sdim  // Add a check in the middle block to see if we have completed
1386243789Sdim  // all of the iterations in the first vector loop.
1387243789Sdim  // If (N - N%VF) == N, then we *don't* need to run the remainder.
1388243789Sdim  Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1389243789Sdim                                ResumeIndex, "cmp.n",
1390243789Sdim                                MiddleBlock->getTerminator());
1391243789Sdim
1392243789Sdim  BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1393243789Sdim  // Remove the old terminator.
1394243789Sdim  MiddleBlock->getTerminator()->eraseFromParent();
1395243789Sdim
1396243789Sdim  // Create i+1 and fill the PHINode.
1397243789Sdim  Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1398243789Sdim  Induction->addIncoming(StartIdx, VectorPH);
1399243789Sdim  Induction->addIncoming(NextIdx, VecBody);
1400243789Sdim  // Create the compare.
1401243789Sdim  Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1402243789Sdim  Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1403243789Sdim
1404243789Sdim  // Now we have two terminators. Remove the old one from the block.
1405243789Sdim  VecBody->getTerminator()->eraseFromParent();
1406243789Sdim
1407243789Sdim  // Get ready to start creating new instructions into the vectorized body.
1408243789Sdim  Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1409243789Sdim
1410249423Sdim  // Create and register the new vector loop.
1411243789Sdim  Loop* Lp = new Loop();
1412249423Sdim  Loop *ParentLoop = OrigLoop->getParentLoop();
1413243789Sdim
1414249423Sdim  // Insert the new loop into the loop nest and register the new basic blocks.
1415243789Sdim  if (ParentLoop) {
1416249423Sdim    ParentLoop->addChildLoop(Lp);
1417249423Sdim    for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1418249423Sdim      ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1419243789Sdim    ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1420243789Sdim    ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1421243789Sdim    ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1422249423Sdim  } else {
1423249423Sdim    LI->addTopLevelLoop(Lp);
1424243789Sdim  }
1425243789Sdim
1426249423Sdim  Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1427249423Sdim
1428243789Sdim  // Save the state.
1429243789Sdim  LoopVectorPreHeader = VectorPH;
1430243789Sdim  LoopScalarPreHeader = ScalarPH;
1431243789Sdim  LoopMiddleBlock = MiddleBlock;
1432243789Sdim  LoopExitBlock = ExitBlock;
1433243789Sdim  LoopVectorBody = VecBody;
1434243789Sdim  LoopScalarBody = OldBasicBlock;
1435243789Sdim}
1436243789Sdim
1437243789Sdim/// This function returns the identity element (or neutral element) for
1438243789Sdim/// the operation K.
1439249423Sdimstatic Constant*
1440249423SdimgetReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1441243789Sdim  switch (K) {
1442249423Sdim  case LoopVectorizationLegality:: RK_IntegerXor:
1443249423Sdim  case LoopVectorizationLegality:: RK_IntegerAdd:
1444249423Sdim  case LoopVectorizationLegality:: RK_IntegerOr:
1445243789Sdim    // Adding, Xoring, Oring zero to a number does not change it.
1446249423Sdim    return ConstantInt::get(Tp, 0);
1447249423Sdim  case LoopVectorizationLegality:: RK_IntegerMult:
1448243789Sdim    // Multiplying a number by 1 does not change it.
1449249423Sdim    return ConstantInt::get(Tp, 1);
1450249423Sdim  case LoopVectorizationLegality:: RK_IntegerAnd:
1451243789Sdim    // AND-ing a number with an all-1 value does not change it.
1452249423Sdim    return ConstantInt::get(Tp, -1, true);
1453249423Sdim  case LoopVectorizationLegality:: RK_FloatMult:
1454249423Sdim    // Multiplying a number by 1 does not change it.
1455249423Sdim    return ConstantFP::get(Tp, 1.0L);
1456249423Sdim  case LoopVectorizationLegality:: RK_FloatAdd:
1457249423Sdim    // Adding zero to a number does not change it.
1458249423Sdim    return ConstantFP::get(Tp, 0.0L);
1459243789Sdim  default:
1460243789Sdim    llvm_unreachable("Unknown reduction kind");
1461243789Sdim  }
1462243789Sdim}
1463243789Sdim
1464249423Sdimstatic Intrinsic::ID
1465249423SdimgetIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1466249423Sdim  // If we have an intrinsic call, check if it is trivially vectorizable.
1467249423Sdim  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1468249423Sdim    switch (II->getIntrinsicID()) {
1469249423Sdim    case Intrinsic::sqrt:
1470249423Sdim    case Intrinsic::sin:
1471249423Sdim    case Intrinsic::cos:
1472249423Sdim    case Intrinsic::exp:
1473249423Sdim    case Intrinsic::exp2:
1474249423Sdim    case Intrinsic::log:
1475249423Sdim    case Intrinsic::log10:
1476249423Sdim    case Intrinsic::log2:
1477249423Sdim    case Intrinsic::fabs:
1478249423Sdim    case Intrinsic::floor:
1479249423Sdim    case Intrinsic::ceil:
1480249423Sdim    case Intrinsic::trunc:
1481249423Sdim    case Intrinsic::rint:
1482249423Sdim    case Intrinsic::nearbyint:
1483249423Sdim    case Intrinsic::pow:
1484249423Sdim    case Intrinsic::fma:
1485249423Sdim    case Intrinsic::fmuladd:
1486249423Sdim      return II->getIntrinsicID();
1487249423Sdim    default:
1488249423Sdim      return Intrinsic::not_intrinsic;
1489249423Sdim    }
1490249423Sdim  }
1491249423Sdim
1492249423Sdim  if (!TLI)
1493249423Sdim    return Intrinsic::not_intrinsic;
1494249423Sdim
1495249423Sdim  LibFunc::Func Func;
1496249423Sdim  Function *F = CI->getCalledFunction();
1497249423Sdim  // We're going to make assumptions on the semantics of the functions, check
1498249423Sdim  // that the target knows that it's available in this environment.
1499249423Sdim  if (!F || !TLI->getLibFunc(F->getName(), Func))
1500249423Sdim    return Intrinsic::not_intrinsic;
1501249423Sdim
1502249423Sdim  // Otherwise check if we have a call to a function that can be turned into a
1503249423Sdim  // vector intrinsic.
1504249423Sdim  switch (Func) {
1505249423Sdim  default:
1506249423Sdim    break;
1507249423Sdim  case LibFunc::sin:
1508249423Sdim  case LibFunc::sinf:
1509249423Sdim  case LibFunc::sinl:
1510249423Sdim    return Intrinsic::sin;
1511249423Sdim  case LibFunc::cos:
1512249423Sdim  case LibFunc::cosf:
1513249423Sdim  case LibFunc::cosl:
1514249423Sdim    return Intrinsic::cos;
1515249423Sdim  case LibFunc::exp:
1516249423Sdim  case LibFunc::expf:
1517249423Sdim  case LibFunc::expl:
1518249423Sdim    return Intrinsic::exp;
1519249423Sdim  case LibFunc::exp2:
1520249423Sdim  case LibFunc::exp2f:
1521249423Sdim  case LibFunc::exp2l:
1522249423Sdim    return Intrinsic::exp2;
1523249423Sdim  case LibFunc::log:
1524249423Sdim  case LibFunc::logf:
1525249423Sdim  case LibFunc::logl:
1526249423Sdim    return Intrinsic::log;
1527249423Sdim  case LibFunc::log10:
1528249423Sdim  case LibFunc::log10f:
1529249423Sdim  case LibFunc::log10l:
1530249423Sdim    return Intrinsic::log10;
1531249423Sdim  case LibFunc::log2:
1532249423Sdim  case LibFunc::log2f:
1533249423Sdim  case LibFunc::log2l:
1534249423Sdim    return Intrinsic::log2;
1535249423Sdim  case LibFunc::fabs:
1536249423Sdim  case LibFunc::fabsf:
1537249423Sdim  case LibFunc::fabsl:
1538249423Sdim    return Intrinsic::fabs;
1539249423Sdim  case LibFunc::floor:
1540249423Sdim  case LibFunc::floorf:
1541249423Sdim  case LibFunc::floorl:
1542249423Sdim    return Intrinsic::floor;
1543249423Sdim  case LibFunc::ceil:
1544249423Sdim  case LibFunc::ceilf:
1545249423Sdim  case LibFunc::ceill:
1546249423Sdim    return Intrinsic::ceil;
1547249423Sdim  case LibFunc::trunc:
1548249423Sdim  case LibFunc::truncf:
1549249423Sdim  case LibFunc::truncl:
1550249423Sdim    return Intrinsic::trunc;
1551249423Sdim  case LibFunc::rint:
1552249423Sdim  case LibFunc::rintf:
1553249423Sdim  case LibFunc::rintl:
1554249423Sdim    return Intrinsic::rint;
1555249423Sdim  case LibFunc::nearbyint:
1556249423Sdim  case LibFunc::nearbyintf:
1557249423Sdim  case LibFunc::nearbyintl:
1558249423Sdim    return Intrinsic::nearbyint;
1559249423Sdim  case LibFunc::pow:
1560249423Sdim  case LibFunc::powf:
1561249423Sdim  case LibFunc::powl:
1562249423Sdim    return Intrinsic::pow;
1563249423Sdim  }
1564249423Sdim
1565249423Sdim  return Intrinsic::not_intrinsic;
1566249423Sdim}
1567249423Sdim
1568249423Sdim/// This function translates the reduction kind to an LLVM binary operator.
1569249423Sdimstatic Instruction::BinaryOps
1570249423SdimgetReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1571249423Sdim  switch (Kind) {
1572249423Sdim    case LoopVectorizationLegality::RK_IntegerAdd:
1573249423Sdim      return Instruction::Add;
1574249423Sdim    case LoopVectorizationLegality::RK_IntegerMult:
1575249423Sdim      return Instruction::Mul;
1576249423Sdim    case LoopVectorizationLegality::RK_IntegerOr:
1577249423Sdim      return Instruction::Or;
1578249423Sdim    case LoopVectorizationLegality::RK_IntegerAnd:
1579249423Sdim      return Instruction::And;
1580249423Sdim    case LoopVectorizationLegality::RK_IntegerXor:
1581249423Sdim      return Instruction::Xor;
1582249423Sdim    case LoopVectorizationLegality::RK_FloatMult:
1583249423Sdim      return Instruction::FMul;
1584249423Sdim    case LoopVectorizationLegality::RK_FloatAdd:
1585249423Sdim      return Instruction::FAdd;
1586249423Sdim    default:
1587249423Sdim      llvm_unreachable("Unknown reduction operation");
1588249423Sdim  }
1589249423Sdim}
1590249423Sdim
1591243789Sdimvoid
1592249423SdimInnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1593243789Sdim  //===------------------------------------------------===//
1594243789Sdim  //
1595243789Sdim  // Notice: any optimization or new instruction that go
1596243789Sdim  // into the code below should be also be implemented in
1597243789Sdim  // the cost-model.
1598243789Sdim  //
1599243789Sdim  //===------------------------------------------------===//
1600249423Sdim  Constant *Zero = Builder.getInt32(0);
1601243789Sdim
1602243789Sdim  // In order to support reduction variables we need to be able to vectorize
1603243789Sdim  // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1604249423Sdim  // stages. First, we create a new vector PHI node with no incoming edges.
1605243789Sdim  // We use this value when we vectorize all of the instructions that use the
1606243789Sdim  // PHI. Next, after all of the instructions in the block are complete we
1607243789Sdim  // add the new incoming edges to the PHI. At this point all of the
1608243789Sdim  // instructions in the basic block are vectorized, so we can use them to
1609243789Sdim  // construct the PHI.
1610249423Sdim  PhiVector RdxPHIsToFix;
1611243789Sdim
1612249423Sdim  // Scan the loop in a topological order to ensure that defs are vectorized
1613249423Sdim  // before users.
1614249423Sdim  LoopBlocksDFS DFS(OrigLoop);
1615249423Sdim  DFS.perform(LI);
1616243789Sdim
1617249423Sdim  // Vectorize all of the blocks in the original loop.
1618249423Sdim  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1619249423Sdim       be = DFS.endRPO(); bb != be; ++bb)
1620249423Sdim    vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1621243789Sdim
1622249423Sdim  // At this point every instruction in the original loop is widened to
1623243789Sdim  // a vector form. We are almost done. Now, we need to fix the PHI nodes
1624243789Sdim  // that we vectorized. The PHI nodes are currently empty because we did
1625243789Sdim  // not want to introduce cycles. Notice that the remaining PHI nodes
1626243789Sdim  // that we need to fix are reduction variables.
1627243789Sdim
1628243789Sdim  // Create the 'reduced' values for each of the induction vars.
1629243789Sdim  // The reduced values are the vector values that we scalarize and combine
1630243789Sdim  // after the loop is finished.
1631249423Sdim  for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1632243789Sdim       it != e; ++it) {
1633243789Sdim    PHINode *RdxPhi = *it;
1634243789Sdim    assert(RdxPhi && "Unable to recover vectorized PHI");
1635243789Sdim
1636243789Sdim    // Find the reduction variable descriptor.
1637243789Sdim    assert(Legal->getReductionVars()->count(RdxPhi) &&
1638243789Sdim           "Unable to find the reduction variable");
1639243789Sdim    LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1640249423Sdim    (*Legal->getReductionVars())[RdxPhi];
1641243789Sdim
1642243789Sdim    // We need to generate a reduction vector from the incoming scalar.
1643243789Sdim    // To do so, we need to generate the 'identity' vector and overide
1644243789Sdim    // one of the elements with the incoming scalar reduction. We need
1645243789Sdim    // to do it in the vector-loop preheader.
1646249423Sdim    Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1647243789Sdim
1648243789Sdim    // This is the vector-clone of the value that leaves the loop.
1649249423Sdim    VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1650249423Sdim    Type *VecTy = VectorExit[0]->getType();
1651243789Sdim
1652243789Sdim    // Find the reduction identity variable. Zero for addition, or, xor,
1653243789Sdim    // one for multiplication, -1 for And.
1654249423Sdim    Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1655249423Sdim    Constant *Identity = ConstantVector::getSplat(VF, Iden);
1656243789Sdim
1657243789Sdim    // This vector is the Identity vector where the first element is the
1658243789Sdim    // incoming scalar reduction.
1659243789Sdim    Value *VectorStart = Builder.CreateInsertElement(Identity,
1660249423Sdim                                                     RdxDesc.StartValue, Zero);
1661243789Sdim
1662243789Sdim    // Fix the vector-loop phi.
1663243789Sdim    // We created the induction variable so we know that the
1664243789Sdim    // preheader is the first entry.
1665243789Sdim    BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1666243789Sdim
1667243789Sdim    // Reductions do not have to start at zero. They can start with
1668243789Sdim    // any loop invariant values.
1669249423Sdim    VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1670249423Sdim    BasicBlock *Latch = OrigLoop->getLoopLatch();
1671249423Sdim    Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1672249423Sdim    VectorParts &Val = getVectorValue(LoopVal);
1673249423Sdim    for (unsigned part = 0; part < UF; ++part) {
1674249423Sdim      // Make sure to add the reduction stat value only to the
1675249423Sdim      // first unroll part.
1676249423Sdim      Value *StartVal = (part == 0) ? VectorStart : Identity;
1677249423Sdim      cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1678249423Sdim      cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1679249423Sdim    }
1680243789Sdim
1681243789Sdim    // Before each round, move the insertion point right between
1682243789Sdim    // the PHIs and the values we are going to write.
1683243789Sdim    // This allows us to write both PHINodes and the extractelement
1684243789Sdim    // instructions.
1685243789Sdim    Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1686243789Sdim
1687249423Sdim    VectorParts RdxParts;
1688249423Sdim    for (unsigned part = 0; part < UF; ++part) {
1689249423Sdim      // This PHINode contains the vectorized reduction variable, or
1690249423Sdim      // the initial value vector, if we bypass the vector loop.
1691249423Sdim      VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1692249423Sdim      PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1693249423Sdim      Value *StartVal = (part == 0) ? VectorStart : Identity;
1694249423Sdim      for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1695249423Sdim        NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1696249423Sdim      NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1697249423Sdim      RdxParts.push_back(NewPhi);
1698249423Sdim    }
1699243789Sdim
1700249423Sdim    // Reduce all of the unrolled parts into a single vector.
1701249423Sdim    Value *ReducedPartRdx = RdxParts[0];
1702249423Sdim    for (unsigned part = 1; part < UF; ++part) {
1703249423Sdim      Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1704249423Sdim      ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1705249423Sdim                                           "bin.rdx");
1706243789Sdim    }
1707243789Sdim
1708249423Sdim    // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1709249423Sdim    // and vector ops, reducing the set of values being computed by half each
1710249423Sdim    // round.
1711249423Sdim    assert(isPowerOf2_32(VF) &&
1712249423Sdim           "Reduction emission only supported for pow2 vectors!");
1713249423Sdim    Value *TmpVec = ReducedPartRdx;
1714249423Sdim    SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1715249423Sdim    for (unsigned i = VF; i != 1; i >>= 1) {
1716249423Sdim      // Move the upper half of the vector to the lower half.
1717249423Sdim      for (unsigned j = 0; j != i/2; ++j)
1718249423Sdim        ShuffleMask[j] = Builder.getInt32(i/2 + j);
1719249423Sdim
1720249423Sdim      // Fill the rest of the mask with undef.
1721249423Sdim      std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1722249423Sdim                UndefValue::get(Builder.getInt32Ty()));
1723249423Sdim
1724249423Sdim      Value *Shuf =
1725249423Sdim        Builder.CreateShuffleVector(TmpVec,
1726249423Sdim                                    UndefValue::get(TmpVec->getType()),
1727249423Sdim                                    ConstantVector::get(ShuffleMask),
1728249423Sdim                                    "rdx.shuf");
1729249423Sdim
1730249423Sdim      Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1731249423Sdim      TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1732249423Sdim    }
1733249423Sdim
1734249423Sdim    // The result is in the first element of the vector.
1735249423Sdim    Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1736249423Sdim
1737243789Sdim    // Now, we need to fix the users of the reduction variable
1738243789Sdim    // inside and outside of the scalar remainder loop.
1739243789Sdim    // We know that the loop is in LCSSA form. We need to update the
1740243789Sdim    // PHI nodes in the exit blocks.
1741243789Sdim    for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1742243789Sdim         LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1743243789Sdim      PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1744243789Sdim      if (!LCSSAPhi) continue;
1745243789Sdim
1746243789Sdim      // All PHINodes need to have a single entry edge, or two if
1747243789Sdim      // we already fixed them.
1748243789Sdim      assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1749243789Sdim
1750243789Sdim      // We found our reduction value exit-PHI. Update it with the
1751243789Sdim      // incoming bypass edge.
1752243789Sdim      if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1753243789Sdim        // Add an edge coming from the bypass.
1754243789Sdim        LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1755243789Sdim        break;
1756243789Sdim      }
1757243789Sdim    }// end of the LCSSA phi scan.
1758243789Sdim
1759243789Sdim    // Fix the scalar loop reduction variable with the incoming reduction sum
1760243789Sdim    // from the vector body and from the backedge value.
1761249423Sdim    int IncomingEdgeBlockIdx =
1762249423Sdim    (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1763249423Sdim    assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1764249423Sdim    // Pick the other block.
1765249423Sdim    int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1766243789Sdim    (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1767243789Sdim    (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1768243789Sdim  }// end of for each redux variable.
1769249423Sdim
1770249423Sdim  // The Loop exit block may have single value PHI nodes where the incoming
1771249423Sdim  // value is 'undef'. While vectorizing we only handled real values that
1772249423Sdim  // were defined inside the loop. Here we handle the 'undef case'.
1773249423Sdim  // See PR14725.
1774249423Sdim  for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1775249423Sdim       LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1776249423Sdim    PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1777249423Sdim    if (!LCSSAPhi) continue;
1778249423Sdim    if (LCSSAPhi->getNumIncomingValues() == 1)
1779249423Sdim      LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1780249423Sdim                            LoopMiddleBlock);
1781249423Sdim  }
1782243789Sdim}
1783243789Sdim
1784249423SdimInnerLoopVectorizer::VectorParts
1785249423SdimInnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1786249423Sdim  assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1787249423Sdim         "Invalid edge");
1788249423Sdim
1789249423Sdim  VectorParts SrcMask = createBlockInMask(Src);
1790249423Sdim
1791249423Sdim  // The terminator has to be a branch inst!
1792249423Sdim  BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1793249423Sdim  assert(BI && "Unexpected terminator found");
1794249423Sdim
1795249423Sdim  if (BI->isConditional()) {
1796249423Sdim    VectorParts EdgeMask = getVectorValue(BI->getCondition());
1797249423Sdim
1798249423Sdim    if (BI->getSuccessor(0) != Dst)
1799249423Sdim      for (unsigned part = 0; part < UF; ++part)
1800249423Sdim        EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1801249423Sdim
1802249423Sdim    for (unsigned part = 0; part < UF; ++part)
1803249423Sdim      EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1804249423Sdim    return EdgeMask;
1805249423Sdim  }
1806249423Sdim
1807249423Sdim  return SrcMask;
1808249423Sdim}
1809249423Sdim
1810249423SdimInnerLoopVectorizer::VectorParts
1811249423SdimInnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1812249423Sdim  assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1813249423Sdim
1814249423Sdim  // Loop incoming mask is all-one.
1815249423Sdim  if (OrigLoop->getHeader() == BB) {
1816249423Sdim    Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1817249423Sdim    return getVectorValue(C);
1818249423Sdim  }
1819249423Sdim
1820249423Sdim  // This is the block mask. We OR all incoming edges, and with zero.
1821249423Sdim  Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1822249423Sdim  VectorParts BlockMask = getVectorValue(Zero);
1823249423Sdim
1824249423Sdim  // For each pred:
1825249423Sdim  for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1826249423Sdim    VectorParts EM = createEdgeMask(*it, BB);
1827249423Sdim    for (unsigned part = 0; part < UF; ++part)
1828249423Sdim      BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1829249423Sdim  }
1830249423Sdim
1831249423Sdim  return BlockMask;
1832249423Sdim}
1833249423Sdim
1834249423Sdimvoid
1835249423SdimInnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1836249423Sdim                                          BasicBlock *BB, PhiVector *PV) {
1837249423Sdim  // For each instruction in the old loop.
1838249423Sdim  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1839249423Sdim    VectorParts &Entry = WidenMap.get(it);
1840249423Sdim    switch (it->getOpcode()) {
1841249423Sdim    case Instruction::Br:
1842249423Sdim      // Nothing to do for PHIs and BR, since we already took care of the
1843249423Sdim      // loop control flow instructions.
1844249423Sdim      continue;
1845249423Sdim    case Instruction::PHI:{
1846249423Sdim      PHINode* P = cast<PHINode>(it);
1847249423Sdim      // Handle reduction variables:
1848249423Sdim      if (Legal->getReductionVars()->count(P)) {
1849249423Sdim        for (unsigned part = 0; part < UF; ++part) {
1850249423Sdim          // This is phase one of vectorizing PHIs.
1851249423Sdim          Type *VecTy = VectorType::get(it->getType(), VF);
1852249423Sdim          Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1853249423Sdim                                        LoopVectorBody-> getFirstInsertionPt());
1854249423Sdim        }
1855249423Sdim        PV->push_back(P);
1856249423Sdim        continue;
1857249423Sdim      }
1858249423Sdim
1859249423Sdim      // Check for PHI nodes that are lowered to vector selects.
1860249423Sdim      if (P->getParent() != OrigLoop->getHeader()) {
1861249423Sdim        // We know that all PHIs in non header blocks are converted into
1862249423Sdim        // selects, so we don't have to worry about the insertion order and we
1863249423Sdim        // can just use the builder.
1864249423Sdim
1865249423Sdim        // At this point we generate the predication tree. There may be
1866249423Sdim        // duplications since this is a simple recursive scan, but future
1867249423Sdim        // optimizations will clean it up.
1868249423Sdim        VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1869249423Sdim                                               P->getParent());
1870249423Sdim
1871249423Sdim        for (unsigned part = 0; part < UF; ++part) {
1872249423Sdim        VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1873249423Sdim        VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1874249423Sdim          Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1875249423Sdim                                             "predphi");
1876249423Sdim        }
1877249423Sdim        continue;
1878249423Sdim      }
1879249423Sdim
1880249423Sdim      // This PHINode must be an induction variable.
1881249423Sdim      // Make sure that we know about it.
1882249423Sdim      assert(Legal->getInductionVars()->count(P) &&
1883249423Sdim             "Not an induction variable");
1884249423Sdim
1885249423Sdim      LoopVectorizationLegality::InductionInfo II =
1886249423Sdim        Legal->getInductionVars()->lookup(P);
1887249423Sdim
1888249423Sdim      switch (II.IK) {
1889249423Sdim      case LoopVectorizationLegality::IK_NoInduction:
1890249423Sdim        llvm_unreachable("Unknown induction");
1891249423Sdim      case LoopVectorizationLegality::IK_IntInduction: {
1892249423Sdim        assert(P == OldInduction && "Unexpected PHI");
1893249423Sdim        Value *Broadcasted = getBroadcastInstrs(Induction);
1894249423Sdim        // After broadcasting the induction variable we need to make the
1895249423Sdim        // vector consecutive by adding 0, 1, 2 ...
1896249423Sdim        for (unsigned part = 0; part < UF; ++part)
1897249423Sdim          Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1898249423Sdim        continue;
1899249423Sdim      }
1900249423Sdim      case LoopVectorizationLegality::IK_ReverseIntInduction:
1901249423Sdim      case LoopVectorizationLegality::IK_PtrInduction:
1902249423Sdim      case LoopVectorizationLegality::IK_ReversePtrInduction:
1903249423Sdim        // Handle reverse integer and pointer inductions.
1904249423Sdim        Value *StartIdx = 0;
1905249423Sdim        // If we have a single integer induction variable then use it.
1906249423Sdim        // Otherwise, start counting at zero.
1907249423Sdim        if (OldInduction) {
1908249423Sdim          LoopVectorizationLegality::InductionInfo OldII =
1909249423Sdim            Legal->getInductionVars()->lookup(OldInduction);
1910249423Sdim          StartIdx = OldII.StartValue;
1911249423Sdim        } else {
1912249423Sdim          StartIdx = ConstantInt::get(Induction->getType(), 0);
1913249423Sdim        }
1914249423Sdim        // This is the normalized GEP that starts counting at zero.
1915249423Sdim        Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1916249423Sdim                                                 "normalized.idx");
1917249423Sdim
1918249423Sdim        // Handle the reverse integer induction variable case.
1919249423Sdim        if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1920249423Sdim          IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1921249423Sdim          Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1922249423Sdim                                                 "resize.norm.idx");
1923249423Sdim          Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1924249423Sdim                                                 "reverse.idx");
1925249423Sdim
1926249423Sdim          // This is a new value so do not hoist it out.
1927249423Sdim          Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1928249423Sdim          // After broadcasting the induction variable we need to make the
1929249423Sdim          // vector consecutive by adding  ... -3, -2, -1, 0.
1930249423Sdim          for (unsigned part = 0; part < UF; ++part)
1931249423Sdim            Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1932249423Sdim          continue;
1933249423Sdim        }
1934249423Sdim
1935249423Sdim        // Handle the pointer induction variable case.
1936249423Sdim        assert(P->getType()->isPointerTy() && "Unexpected type.");
1937249423Sdim
1938249423Sdim        // Is this a reverse induction ptr or a consecutive induction ptr.
1939249423Sdim        bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1940249423Sdim                        II.IK);
1941249423Sdim
1942249423Sdim        // This is the vector of results. Notice that we don't generate
1943249423Sdim        // vector geps because scalar geps result in better code.
1944249423Sdim        for (unsigned part = 0; part < UF; ++part) {
1945249423Sdim          Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1946249423Sdim          for (unsigned int i = 0; i < VF; ++i) {
1947249423Sdim            int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1948249423Sdim            Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1949249423Sdim            Value *GlobalIdx;
1950249423Sdim            if (!Reverse)
1951249423Sdim              GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1952249423Sdim            else
1953249423Sdim              GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1954249423Sdim
1955249423Sdim            Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1956249423Sdim                                               "next.gep");
1957249423Sdim            VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1958249423Sdim                                                 Builder.getInt32(i),
1959249423Sdim                                                 "insert.gep");
1960249423Sdim          }
1961249423Sdim          Entry[part] = VecVal;
1962249423Sdim        }
1963249423Sdim        continue;
1964249423Sdim      }
1965249423Sdim
1966249423Sdim    }// End of PHI.
1967249423Sdim
1968249423Sdim    case Instruction::Add:
1969249423Sdim    case Instruction::FAdd:
1970249423Sdim    case Instruction::Sub:
1971249423Sdim    case Instruction::FSub:
1972249423Sdim    case Instruction::Mul:
1973249423Sdim    case Instruction::FMul:
1974249423Sdim    case Instruction::UDiv:
1975249423Sdim    case Instruction::SDiv:
1976249423Sdim    case Instruction::FDiv:
1977249423Sdim    case Instruction::URem:
1978249423Sdim    case Instruction::SRem:
1979249423Sdim    case Instruction::FRem:
1980249423Sdim    case Instruction::Shl:
1981249423Sdim    case Instruction::LShr:
1982249423Sdim    case Instruction::AShr:
1983249423Sdim    case Instruction::And:
1984249423Sdim    case Instruction::Or:
1985249423Sdim    case Instruction::Xor: {
1986249423Sdim      // Just widen binops.
1987249423Sdim      BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1988249423Sdim      VectorParts &A = getVectorValue(it->getOperand(0));
1989249423Sdim      VectorParts &B = getVectorValue(it->getOperand(1));
1990249423Sdim
1991249423Sdim      // Use this vector value for all users of the original instruction.
1992249423Sdim      for (unsigned Part = 0; Part < UF; ++Part) {
1993249423Sdim        Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1994249423Sdim
1995249423Sdim        // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1996249423Sdim        BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1997249423Sdim        if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1998249423Sdim          VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1999249423Sdim          VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2000249423Sdim        }
2001249423Sdim        if (VecOp && isa<PossiblyExactOperator>(VecOp))
2002249423Sdim          VecOp->setIsExact(BinOp->isExact());
2003249423Sdim
2004249423Sdim        Entry[Part] = V;
2005249423Sdim      }
2006249423Sdim      break;
2007249423Sdim    }
2008249423Sdim    case Instruction::Select: {
2009249423Sdim      // Widen selects.
2010249423Sdim      // If the selector is loop invariant we can create a select
2011249423Sdim      // instruction with a scalar condition. Otherwise, use vector-select.
2012249423Sdim      bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2013249423Sdim                                               OrigLoop);
2014249423Sdim
2015249423Sdim      // The condition can be loop invariant  but still defined inside the
2016249423Sdim      // loop. This means that we can't just use the original 'cond' value.
2017249423Sdim      // We have to take the 'vectorized' value and pick the first lane.
2018249423Sdim      // Instcombine will make this a no-op.
2019249423Sdim      VectorParts &Cond = getVectorValue(it->getOperand(0));
2020249423Sdim      VectorParts &Op0  = getVectorValue(it->getOperand(1));
2021249423Sdim      VectorParts &Op1  = getVectorValue(it->getOperand(2));
2022249423Sdim      Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2023249423Sdim                                                       Builder.getInt32(0));
2024249423Sdim      for (unsigned Part = 0; Part < UF; ++Part) {
2025249423Sdim        Entry[Part] = Builder.CreateSelect(
2026249423Sdim          InvariantCond ? ScalarCond : Cond[Part],
2027249423Sdim          Op0[Part],
2028249423Sdim          Op1[Part]);
2029249423Sdim      }
2030249423Sdim      break;
2031249423Sdim    }
2032249423Sdim
2033249423Sdim    case Instruction::ICmp:
2034249423Sdim    case Instruction::FCmp: {
2035249423Sdim      // Widen compares. Generate vector compares.
2036249423Sdim      bool FCmp = (it->getOpcode() == Instruction::FCmp);
2037249423Sdim      CmpInst *Cmp = dyn_cast<CmpInst>(it);
2038249423Sdim      VectorParts &A = getVectorValue(it->getOperand(0));
2039249423Sdim      VectorParts &B = getVectorValue(it->getOperand(1));
2040249423Sdim      for (unsigned Part = 0; Part < UF; ++Part) {
2041249423Sdim        Value *C = 0;
2042249423Sdim        if (FCmp)
2043249423Sdim          C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2044249423Sdim        else
2045249423Sdim          C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2046249423Sdim        Entry[Part] = C;
2047249423Sdim      }
2048249423Sdim      break;
2049249423Sdim    }
2050249423Sdim
2051249423Sdim    case Instruction::Store:
2052249423Sdim    case Instruction::Load:
2053249423Sdim        vectorizeMemoryInstruction(it, Legal);
2054249423Sdim        break;
2055249423Sdim    case Instruction::ZExt:
2056249423Sdim    case Instruction::SExt:
2057249423Sdim    case Instruction::FPToUI:
2058249423Sdim    case Instruction::FPToSI:
2059249423Sdim    case Instruction::FPExt:
2060249423Sdim    case Instruction::PtrToInt:
2061249423Sdim    case Instruction::IntToPtr:
2062249423Sdim    case Instruction::SIToFP:
2063249423Sdim    case Instruction::UIToFP:
2064249423Sdim    case Instruction::Trunc:
2065249423Sdim    case Instruction::FPTrunc:
2066249423Sdim    case Instruction::BitCast: {
2067249423Sdim      CastInst *CI = dyn_cast<CastInst>(it);
2068249423Sdim      /// Optimize the special case where the source is the induction
2069249423Sdim      /// variable. Notice that we can only optimize the 'trunc' case
2070249423Sdim      /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2071249423Sdim      /// c. other casts depend on pointer size.
2072249423Sdim      if (CI->getOperand(0) == OldInduction &&
2073249423Sdim          it->getOpcode() == Instruction::Trunc) {
2074249423Sdim        Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2075249423Sdim                                               CI->getType());
2076249423Sdim        Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2077249423Sdim        for (unsigned Part = 0; Part < UF; ++Part)
2078249423Sdim          Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2079249423Sdim        break;
2080249423Sdim      }
2081249423Sdim      /// Vectorize casts.
2082249423Sdim      Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2083249423Sdim
2084249423Sdim      VectorParts &A = getVectorValue(it->getOperand(0));
2085249423Sdim      for (unsigned Part = 0; Part < UF; ++Part)
2086249423Sdim        Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2087249423Sdim      break;
2088249423Sdim    }
2089249423Sdim
2090249423Sdim    case Instruction::Call: {
2091249423Sdim      // Ignore dbg intrinsics.
2092249423Sdim      if (isa<DbgInfoIntrinsic>(it))
2093249423Sdim        break;
2094249423Sdim
2095249423Sdim      Module *M = BB->getParent()->getParent();
2096249423Sdim      CallInst *CI = cast<CallInst>(it);
2097249423Sdim      Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2098249423Sdim      assert(ID && "Not an intrinsic call!");
2099249423Sdim      for (unsigned Part = 0; Part < UF; ++Part) {
2100249423Sdim        SmallVector<Value*, 4> Args;
2101249423Sdim        for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2102249423Sdim          VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2103249423Sdim          Args.push_back(Arg[Part]);
2104249423Sdim        }
2105249423Sdim        Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2106249423Sdim        Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2107249423Sdim        Entry[Part] = Builder.CreateCall(F, Args);
2108249423Sdim      }
2109249423Sdim      break;
2110249423Sdim    }
2111249423Sdim
2112249423Sdim    default:
2113249423Sdim      // All other instructions are unsupported. Scalarize them.
2114249423Sdim      scalarizeInstruction(it);
2115249423Sdim      break;
2116249423Sdim    }// end of switch.
2117249423Sdim  }// end of for_each instr.
2118249423Sdim}
2119249423Sdim
2120249423Sdimvoid InnerLoopVectorizer::updateAnalysis() {
2121249423Sdim  // Forget the original basic block.
2122243789Sdim  SE->forgetLoop(OrigLoop);
2123243789Sdim
2124243789Sdim  // Update the dominator tree information.
2125249423Sdim  assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2126243789Sdim         "Entry does not dominate exit.");
2127243789Sdim
2128249423Sdim  for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2129249423Sdim    DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2130249423Sdim  DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2131243789Sdim  DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2132249423Sdim  DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2133243789Sdim  DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2134243789Sdim  DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2135243789Sdim  DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2136243789Sdim
2137243789Sdim  DEBUG(DT->verifyAnalysis());
2138243789Sdim}
2139243789Sdim
2140249423Sdimbool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2141249423Sdim  if (!EnableIfConversion)
2142249423Sdim    return false;
2143249423Sdim
2144249423Sdim  assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2145249423Sdim  std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2146249423Sdim
2147249423Sdim  // Collect the blocks that need predication.
2148249423Sdim  for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2149249423Sdim    BasicBlock *BB = LoopBlocks[i];
2150249423Sdim
2151249423Sdim    // We don't support switch statements inside loops.
2152249423Sdim    if (!isa<BranchInst>(BB->getTerminator()))
2153249423Sdim      return false;
2154249423Sdim
2155249423Sdim    // We must have at most two predecessors because we need to convert
2156249423Sdim    // all PHIs to selects.
2157249423Sdim    unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2158249423Sdim    if (Preds > 2)
2159249423Sdim      return false;
2160249423Sdim
2161249423Sdim    // We must be able to predicate all blocks that need to be predicated.
2162249423Sdim    if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2163249423Sdim      return false;
2164243789Sdim  }
2165243789Sdim
2166249423Sdim  // We can if-convert this loop.
2167249423Sdim  return true;
2168249423Sdim}
2169249423Sdim
2170249423Sdimbool LoopVectorizationLegality::canVectorize() {
2171249423Sdim  assert(TheLoop->getLoopPreheader() && "No preheader!!");
2172249423Sdim
2173249423Sdim  // We can only vectorize innermost loops.
2174249423Sdim  if (TheLoop->getSubLoopsVector().size())
2175249423Sdim    return false;
2176249423Sdim
2177249423Sdim  // We must have a single backedge.
2178249423Sdim  if (TheLoop->getNumBackEdges() != 1)
2179249423Sdim    return false;
2180249423Sdim
2181249423Sdim  // We must have a single exiting block.
2182249423Sdim  if (!TheLoop->getExitingBlock())
2183249423Sdim    return false;
2184249423Sdim
2185243789Sdim  unsigned NumBlocks = TheLoop->getNumBlocks();
2186249423Sdim
2187249423Sdim  // Check if we can if-convert non single-bb loops.
2188249423Sdim  if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2189249423Sdim    DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2190243789Sdim    return false;
2191243789Sdim  }
2192243789Sdim
2193243789Sdim  // We need to have a loop header.
2194249423Sdim  BasicBlock *Latch = TheLoop->getLoopLatch();
2195249423Sdim  DEBUG(dbgs() << "LV: Found a loop: " <<
2196249423Sdim        TheLoop->getHeader()->getName() << "\n");
2197243789Sdim
2198243789Sdim  // ScalarEvolution needs to be able to find the exit count.
2199249423Sdim  const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2200243789Sdim  if (ExitCount == SE->getCouldNotCompute()) {
2201243789Sdim    DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2202243789Sdim    return false;
2203243789Sdim  }
2204243789Sdim
2205243789Sdim  // Do not loop-vectorize loops with a tiny trip count.
2206249423Sdim  unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2207249423Sdim  if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2208243789Sdim    DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2209243789Sdim          "This loop is not worth vectorizing.\n");
2210243789Sdim    return false;
2211243789Sdim  }
2212243789Sdim
2213249423Sdim  // Check if we can vectorize the instructions and CFG in this loop.
2214249423Sdim  if (!canVectorizeInstrs()) {
2215249423Sdim    DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2216249423Sdim    return false;
2217249423Sdim  }
2218249423Sdim
2219243789Sdim  // Go over each instruction and look at memory deps.
2220249423Sdim  if (!canVectorizeMemory()) {
2221249423Sdim    DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2222243789Sdim    return false;
2223243789Sdim  }
2224243789Sdim
2225249423Sdim  // Collect all of the variables that remain uniform after vectorization.
2226249423Sdim  collectLoopUniforms();
2227249423Sdim
2228243789Sdim  DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2229243789Sdim        (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2230243789Sdim        <<"!\n");
2231243789Sdim
2232243789Sdim  // Okay! We can vectorize. At this point we don't have any other mem analysis
2233243789Sdim  // which may limit our maximum vectorization factor, so just return true with
2234243789Sdim  // no restrictions.
2235243789Sdim  return true;
2236243789Sdim}
2237243789Sdim
2238249423Sdimbool LoopVectorizationLegality::canVectorizeInstrs() {
2239249423Sdim  BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2240249423Sdim  BasicBlock *Header = TheLoop->getHeader();
2241243789Sdim
2242249423Sdim  // If we marked the scalar loop as "already vectorized" then no need
2243249423Sdim  // to vectorize it again.
2244249423Sdim  if (Header->getTerminator()->getMetadata(AlreadyVectorizedMDName)) {
2245249423Sdim    DEBUG(dbgs() << "LV: This loop was vectorized before\n");
2246249423Sdim    return false;
2247249423Sdim  }
2248249423Sdim
2249249423Sdim  // For each block in the loop.
2250249423Sdim  for (Loop::block_iterator bb = TheLoop->block_begin(),
2251249423Sdim       be = TheLoop->block_end(); bb != be; ++bb) {
2252249423Sdim
2253249423Sdim    // Scan the instructions in the block and look for hazards.
2254249423Sdim    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2255249423Sdim         ++it) {
2256249423Sdim
2257249423Sdim      if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2258249423Sdim        // This should not happen because the loop should be normalized.
2259249423Sdim        if (Phi->getNumIncomingValues() != 2) {
2260249423Sdim          DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2261249423Sdim          return false;
2262249423Sdim        }
2263249423Sdim
2264249423Sdim        // Check that this PHI type is allowed.
2265249423Sdim        if (!Phi->getType()->isIntegerTy() &&
2266249423Sdim            !Phi->getType()->isFloatingPointTy() &&
2267249423Sdim            !Phi->getType()->isPointerTy()) {
2268249423Sdim          DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2269249423Sdim          return false;
2270249423Sdim        }
2271249423Sdim
2272249423Sdim        // If this PHINode is not in the header block, then we know that we
2273249423Sdim        // can convert it to select during if-conversion. No need to check if
2274249423Sdim        // the PHIs in this block are induction or reduction variables.
2275249423Sdim        if (*bb != Header)
2276249423Sdim          continue;
2277249423Sdim
2278249423Sdim        // This is the value coming from the preheader.
2279249423Sdim        Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2280249423Sdim        // Check if this is an induction variable.
2281249423Sdim        InductionKind IK = isInductionVariable(Phi);
2282249423Sdim
2283249423Sdim        if (IK_NoInduction != IK) {
2284249423Sdim          // Int inductions are special because we only allow one IV.
2285249423Sdim          if (IK == IK_IntInduction) {
2286249423Sdim            if (Induction) {
2287249423Sdim              DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2288249423Sdim              return false;
2289249423Sdim            }
2290249423Sdim            Induction = Phi;
2291249423Sdim          }
2292249423Sdim
2293249423Sdim          DEBUG(dbgs() << "LV: Found an induction variable.\n");
2294249423Sdim          Inductions[Phi] = InductionInfo(StartValue, IK);
2295249423Sdim          continue;
2296249423Sdim        }
2297249423Sdim
2298249423Sdim        if (AddReductionVar(Phi, RK_IntegerAdd)) {
2299249423Sdim          DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2300249423Sdim          continue;
2301249423Sdim        }
2302249423Sdim        if (AddReductionVar(Phi, RK_IntegerMult)) {
2303249423Sdim          DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2304249423Sdim          continue;
2305249423Sdim        }
2306249423Sdim        if (AddReductionVar(Phi, RK_IntegerOr)) {
2307249423Sdim          DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2308249423Sdim          continue;
2309249423Sdim        }
2310249423Sdim        if (AddReductionVar(Phi, RK_IntegerAnd)) {
2311249423Sdim          DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2312249423Sdim          continue;
2313249423Sdim        }
2314249423Sdim        if (AddReductionVar(Phi, RK_IntegerXor)) {
2315249423Sdim          DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2316249423Sdim          continue;
2317249423Sdim        }
2318249423Sdim        if (AddReductionVar(Phi, RK_FloatMult)) {
2319249423Sdim          DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2320249423Sdim          continue;
2321249423Sdim        }
2322249423Sdim        if (AddReductionVar(Phi, RK_FloatAdd)) {
2323249423Sdim          DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2324249423Sdim          continue;
2325249423Sdim        }
2326249423Sdim
2327249423Sdim        DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2328243789Sdim        return false;
2329249423Sdim      }// end of PHI handling
2330249423Sdim
2331249423Sdim      // We still don't handle functions. However, we can ignore dbg intrinsic
2332249423Sdim      // calls and we do handle certain intrinsic and libm functions.
2333249423Sdim      CallInst *CI = dyn_cast<CallInst>(it);
2334249423Sdim      if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2335249423Sdim        DEBUG(dbgs() << "LV: Found a call site.\n");
2336249423Sdim        return false;
2337243789Sdim      }
2338249423Sdim
2339249423Sdim      // Check that the instruction return type is vectorizable.
2340249423Sdim      if (!VectorType::isValidElementType(it->getType()) &&
2341249423Sdim          !it->getType()->isVoidTy()) {
2342249423Sdim        DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2343243789Sdim        return false;
2344243789Sdim      }
2345243789Sdim
2346249423Sdim      // Check that the stored type is vectorizable.
2347249423Sdim      if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2348249423Sdim        Type *T = ST->getValueOperand()->getType();
2349249423Sdim        if (!VectorType::isValidElementType(T))
2350243789Sdim          return false;
2351243789Sdim      }
2352243789Sdim
2353249423Sdim      // Reduction instructions are allowed to have exit users.
2354249423Sdim      // All other instructions must not have external users.
2355249423Sdim      if (!AllowedExit.count(it))
2356249423Sdim        //Check that all of the users of the loop are inside the BB.
2357249423Sdim        for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2358249423Sdim             I != E; ++I) {
2359249423Sdim          Instruction *U = cast<Instruction>(*I);
2360249423Sdim          // This user may be a reduction exit value.
2361249423Sdim          if (!TheLoop->contains(U)) {
2362249423Sdim            DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2363249423Sdim            return false;
2364249423Sdim          }
2365249423Sdim        }
2366249423Sdim    } // next instr.
2367243789Sdim
2368249423Sdim  }
2369243789Sdim
2370243789Sdim  if (!Induction) {
2371249423Sdim    DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2372249423Sdim    assert(getInductionVars()->size() && "No induction variables");
2373243789Sdim  }
2374243789Sdim
2375249423Sdim  return true;
2376249423Sdim}
2377243789Sdim
2378249423Sdimvoid LoopVectorizationLegality::collectLoopUniforms() {
2379243789Sdim  // We now know that the loop is vectorizable!
2380243789Sdim  // Collect variables that will remain uniform after vectorization.
2381243789Sdim  std::vector<Value*> Worklist;
2382249423Sdim  BasicBlock *Latch = TheLoop->getLoopLatch();
2383243789Sdim
2384243789Sdim  // Start with the conditional branch and walk up the block.
2385249423Sdim  Worklist.push_back(Latch->getTerminator()->getOperand(0));
2386243789Sdim
2387243789Sdim  while (Worklist.size()) {
2388243789Sdim    Instruction *I = dyn_cast<Instruction>(Worklist.back());
2389243789Sdim    Worklist.pop_back();
2390243789Sdim
2391249423Sdim    // Look at instructions inside this loop.
2392243789Sdim    // Stop when reaching PHI nodes.
2393249423Sdim    // TODO: we need to follow values all over the loop, not only in this block.
2394249423Sdim    if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2395249423Sdim      continue;
2396243789Sdim
2397243789Sdim    // This is a known uniform.
2398243789Sdim    Uniforms.insert(I);
2399243789Sdim
2400243789Sdim    // Insert all operands.
2401249423Sdim    for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2402243789Sdim      Worklist.push_back(I->getOperand(i));
2403243789Sdim    }
2404243789Sdim  }
2405249423Sdim}
2406243789Sdim
2407249423SdimAliasAnalysis::Location
2408249423SdimLoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2409249423Sdim  if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2410249423Sdim    return AA->getLocation(Store);
2411249423Sdim  else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2412249423Sdim    return AA->getLocation(Load);
2413249423Sdim
2414249423Sdim  llvm_unreachable("Should be either load or store instruction");
2415243789Sdim}
2416243789Sdim
2417249423Sdimbool
2418249423SdimLoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2419249423Sdim                                                Value *Object,
2420249423Sdim                                                Instruction *Inst,
2421249423Sdim                                                AliasMultiMap& WriteObjects,
2422249423Sdim                                                unsigned MaxByteWidth) {
2423249423Sdim
2424249423Sdim  AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2425249423Sdim
2426249423Sdim  std::vector<Instruction*>::iterator
2427249423Sdim              it = WriteObjects[Object].begin(),
2428249423Sdim              end = WriteObjects[Object].end();
2429249423Sdim
2430249423Sdim  for (; it != end; ++it) {
2431249423Sdim    Instruction* I = *it;
2432249423Sdim    if (I == Inst)
2433249423Sdim      continue;
2434249423Sdim
2435249423Sdim    AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2436249423Sdim    if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2437249423Sdim                  ThatLoc.getWithNewSize(MaxByteWidth)))
2438249423Sdim      return true;
2439249423Sdim  }
2440249423Sdim  return false;
2441249423Sdim}
2442249423Sdim
2443249423Sdimbool LoopVectorizationLegality::canVectorizeMemory() {
2444249423Sdim
2445249423Sdim  if (TheLoop->isAnnotatedParallel()) {
2446249423Sdim    DEBUG(dbgs()
2447249423Sdim          << "LV: A loop annotated parallel, ignore memory dependency "
2448249423Sdim          << "checks.\n");
2449249423Sdim    return true;
2450249423Sdim  }
2451249423Sdim
2452243789Sdim  typedef SmallVector<Value*, 16> ValueVector;
2453243789Sdim  typedef SmallPtrSet<Value*, 16> ValueSet;
2454243789Sdim  // Holds the Load and Store *instructions*.
2455243789Sdim  ValueVector Loads;
2456243789Sdim  ValueVector Stores;
2457243789Sdim  PtrRtCheck.Pointers.clear();
2458243789Sdim  PtrRtCheck.Need = false;
2459243789Sdim
2460249423Sdim  // For each block.
2461249423Sdim  for (Loop::block_iterator bb = TheLoop->block_begin(),
2462249423Sdim       be = TheLoop->block_end(); bb != be; ++bb) {
2463243789Sdim
2464249423Sdim    // Scan the BB and collect legal loads and stores.
2465249423Sdim    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2466249423Sdim         ++it) {
2467249423Sdim
2468249423Sdim      // If this is a load, save it. If this instruction can read from memory
2469249423Sdim      // but is not a load, then we quit. Notice that we don't handle function
2470249423Sdim      // calls that read or write.
2471249423Sdim      if (it->mayReadFromMemory()) {
2472249423Sdim        LoadInst *Ld = dyn_cast<LoadInst>(it);
2473249423Sdim        if (!Ld) return false;
2474249423Sdim        if (!Ld->isSimple()) {
2475249423Sdim          DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2476249423Sdim          return false;
2477249423Sdim        }
2478249423Sdim        Loads.push_back(Ld);
2479249423Sdim        continue;
2480243789Sdim      }
2481243789Sdim
2482249423Sdim      // Save 'store' instructions. Abort if other instructions write to memory.
2483249423Sdim      if (it->mayWriteToMemory()) {
2484249423Sdim        StoreInst *St = dyn_cast<StoreInst>(it);
2485249423Sdim        if (!St) return false;
2486249423Sdim        if (!St->isSimple()) {
2487249423Sdim          DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2488249423Sdim          return false;
2489249423Sdim        }
2490249423Sdim        Stores.push_back(St);
2491243789Sdim      }
2492249423Sdim    } // next instr.
2493249423Sdim  } // next block.
2494243789Sdim
2495243789Sdim  // Now we have two lists that hold the loads and the stores.
2496243789Sdim  // Next, we find the pointers that they use.
2497243789Sdim
2498243789Sdim  // Check if we see any stores. If there are no stores, then we don't
2499243789Sdim  // care if the pointers are *restrict*.
2500243789Sdim  if (!Stores.size()) {
2501249423Sdim    DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2502249423Sdim    return true;
2503243789Sdim  }
2504243789Sdim
2505249423Sdim  // Holds the read and read-write *pointers* that we find. These maps hold
2506249423Sdim  // unique values for pointers (so no need for multi-map).
2507249423Sdim  AliasMap Reads;
2508249423Sdim  AliasMap ReadWrites;
2509243789Sdim
2510243789Sdim  // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2511243789Sdim  // multiple times on the same object. If the ptr is accessed twice, once
2512243789Sdim  // for read and once for write, it will only appear once (on the write
2513243789Sdim  // list). This is okay, since we are going to check for conflicts between
2514243789Sdim  // writes and between reads and writes, but not between reads and reads.
2515243789Sdim  ValueSet Seen;
2516243789Sdim
2517243789Sdim  ValueVector::iterator I, IE;
2518243789Sdim  for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2519249423Sdim    StoreInst *ST = cast<StoreInst>(*I);
2520243789Sdim    Value* Ptr = ST->getPointerOperand();
2521243789Sdim
2522243789Sdim    if (isUniform(Ptr)) {
2523243789Sdim      DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2524243789Sdim      return false;
2525243789Sdim    }
2526243789Sdim
2527243789Sdim    // If we did *not* see this pointer before, insert it to
2528243789Sdim    // the read-write list. At this phase it is only a 'write' list.
2529243789Sdim    if (Seen.insert(Ptr))
2530249423Sdim      ReadWrites.insert(std::make_pair(Ptr, ST));
2531243789Sdim  }
2532243789Sdim
2533243789Sdim  for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2534249423Sdim    LoadInst *LD = cast<LoadInst>(*I);
2535243789Sdim    Value* Ptr = LD->getPointerOperand();
2536243789Sdim    // If we did *not* see this pointer before, insert it to the
2537243789Sdim    // read list. If we *did* see it before, then it is already in
2538243789Sdim    // the read-write list. This allows us to vectorize expressions
2539243789Sdim    // such as A[i] += x;  Because the address of A[i] is a read-write
2540243789Sdim    // pointer. This only works if the index of A[i] is consecutive.
2541243789Sdim    // If the address of i is unknown (for example A[B[i]]) then we may
2542243789Sdim    // read a few words, modify, and write a few words, and some of the
2543243789Sdim    // words may be written to the same address.
2544249423Sdim    if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2545249423Sdim      Reads.insert(std::make_pair(Ptr, LD));
2546243789Sdim  }
2547243789Sdim
2548243789Sdim  // If we write (or read-write) to a single destination and there are no
2549243789Sdim  // other reads in this loop then is it safe to vectorize.
2550243789Sdim  if (ReadWrites.size() == 1 && Reads.size() == 0) {
2551243789Sdim    DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2552243789Sdim    return true;
2553243789Sdim  }
2554243789Sdim
2555243789Sdim  // Find pointers with computable bounds. We are going to use this information
2556243789Sdim  // to place a runtime bound check.
2557249423Sdim  bool CanDoRT = true;
2558249423Sdim  AliasMap::iterator MI, ME;
2559249423Sdim  for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2560249423Sdim    Value *V = (*MI).first;
2561249423Sdim    if (hasComputableBounds(V)) {
2562249423Sdim      PtrRtCheck.insert(SE, TheLoop, V);
2563249423Sdim      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2564243789Sdim    } else {
2565249423Sdim      CanDoRT = false;
2566243789Sdim      break;
2567243789Sdim    }
2568249423Sdim  }
2569249423Sdim  for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2570249423Sdim    Value *V = (*MI).first;
2571249423Sdim    if (hasComputableBounds(V)) {
2572249423Sdim      PtrRtCheck.insert(SE, TheLoop, V);
2573249423Sdim      DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2574243789Sdim    } else {
2575249423Sdim      CanDoRT = false;
2576243789Sdim      break;
2577243789Sdim    }
2578249423Sdim  }
2579243789Sdim
2580243789Sdim  // Check that we did not collect too many pointers or found a
2581243789Sdim  // unsizeable pointer.
2582249423Sdim  if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2583249423Sdim    PtrRtCheck.reset();
2584249423Sdim    CanDoRT = false;
2585243789Sdim  }
2586243789Sdim
2587249423Sdim  if (CanDoRT) {
2588243789Sdim    DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2589243789Sdim  }
2590243789Sdim
2591249423Sdim  bool NeedRTCheck = false;
2592249423Sdim
2593249423Sdim  // Biggest vectorized access possible, vector width * unroll factor.
2594249423Sdim  // TODO: We're being very pessimistic here, find a way to know the
2595249423Sdim  // real access width before getting here.
2596249423Sdim  unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2597249423Sdim                           TTI->getMaximumUnrollFactor();
2598243789Sdim  // Now that the pointers are in two lists (Reads and ReadWrites), we
2599243789Sdim  // can check that there are no conflicts between each of the writes and
2600243789Sdim  // between the writes to the reads.
2601249423Sdim  // Note that WriteObjects duplicates the stores (indexed now by underlying
2602249423Sdim  // objects) to avoid pointing to elements inside ReadWrites.
2603249423Sdim  // TODO: Maybe create a new type where they can interact without duplication.
2604249423Sdim  AliasMultiMap WriteObjects;
2605243789Sdim  ValueVector TempObjects;
2606243789Sdim
2607243789Sdim  // Check that the read-writes do not conflict with other read-write
2608243789Sdim  // pointers.
2609249423Sdim  bool AllWritesIdentified = true;
2610249423Sdim  for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2611249423Sdim    Value *Val = (*MI).first;
2612249423Sdim    Instruction *Inst = (*MI).second;
2613249423Sdim
2614249423Sdim    GetUnderlyingObjects(Val, TempObjects, DL);
2615249423Sdim    for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2616249423Sdim         UI != UE; ++UI) {
2617249423Sdim      if (!isIdentifiedObject(*UI)) {
2618249423Sdim        DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2619249423Sdim        NeedRTCheck = true;
2620249423Sdim        AllWritesIdentified = false;
2621243789Sdim      }
2622249423Sdim
2623249423Sdim      // Never seen it before, can't alias.
2624249423Sdim      if (WriteObjects[*UI].empty()) {
2625249423Sdim        DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2626249423Sdim        WriteObjects[*UI].push_back(Inst);
2627249423Sdim        continue;
2628249423Sdim      }
2629249423Sdim      // Direct alias found.
2630249423Sdim      if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2631243789Sdim        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2632249423Sdim              << **UI <<"\n");
2633249423Sdim        return false;
2634243789Sdim      }
2635249423Sdim      DEBUG(dbgs() << "LV: Found a conflicting global value:"
2636249423Sdim            << **UI <<"\n");
2637249423Sdim      DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2638249423Sdim      DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2639249423Sdim
2640249423Sdim      // If global alias, make sure they do alias.
2641249423Sdim      if (hasPossibleGlobalWriteReorder(*UI,
2642249423Sdim                                        Inst,
2643249423Sdim                                        WriteObjects,
2644249423Sdim                                        MaxByteWidth)) {
2645249423Sdim        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2646249423Sdim              << *UI <<"\n");
2647249423Sdim        return false;
2648249423Sdim      }
2649249423Sdim
2650249423Sdim      // Didn't alias, insert into map for further reference.
2651249423Sdim      WriteObjects[*UI].push_back(Inst);
2652243789Sdim    }
2653243789Sdim    TempObjects.clear();
2654243789Sdim  }
2655243789Sdim
2656243789Sdim  /// Check that the reads don't conflict with the read-writes.
2657249423Sdim  for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2658249423Sdim    Value *Val = (*MI).first;
2659249423Sdim    GetUnderlyingObjects(Val, TempObjects, DL);
2660249423Sdim    for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2661249423Sdim         UI != UE; ++UI) {
2662249423Sdim      // If all of the writes are identified then we don't care if the read
2663249423Sdim      // pointer is identified or not.
2664249423Sdim      if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2665249423Sdim        DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2666249423Sdim        NeedRTCheck = true;
2667243789Sdim      }
2668249423Sdim
2669249423Sdim      // Never seen it before, can't alias.
2670249423Sdim      if (WriteObjects[*UI].empty())
2671249423Sdim        continue;
2672249423Sdim      // Direct alias found.
2673249423Sdim      if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2674249423Sdim        DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2675249423Sdim              << **UI <<"\n");
2676249423Sdim        return false;
2677243789Sdim      }
2678249423Sdim      DEBUG(dbgs() << "LV: Found a global value:  "
2679249423Sdim            << **UI <<"\n");
2680249423Sdim      Instruction *Inst = (*MI).second;
2681249423Sdim      DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2682249423Sdim      DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2683249423Sdim
2684249423Sdim      // If global alias, make sure they do alias.
2685249423Sdim      if (hasPossibleGlobalWriteReorder(*UI,
2686249423Sdim                                        Inst,
2687249423Sdim                                        WriteObjects,
2688249423Sdim                                        MaxByteWidth)) {
2689249423Sdim        DEBUG(dbgs() << "LV: Found a possible read-write reorder:"
2690249423Sdim              << *UI <<"\n");
2691249423Sdim        return false;
2692249423Sdim      }
2693243789Sdim    }
2694243789Sdim    TempObjects.clear();
2695243789Sdim  }
2696243789Sdim
2697249423Sdim  PtrRtCheck.Need = NeedRTCheck;
2698249423Sdim  if (NeedRTCheck && !CanDoRT) {
2699249423Sdim    DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2700249423Sdim          "the array bounds.\n");
2701249423Sdim    PtrRtCheck.reset();
2702249423Sdim    return false;
2703249423Sdim  }
2704249423Sdim
2705249423Sdim  DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2706249423Sdim        " need a runtime memory check.\n");
2707243789Sdim  return true;
2708243789Sdim}
2709243789Sdim
2710243789Sdimbool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2711243789Sdim                                                ReductionKind Kind) {
2712243789Sdim  if (Phi->getNumIncomingValues() != 2)
2713243789Sdim    return false;
2714243789Sdim
2715249423Sdim  // Reduction variables are only found in the loop header block.
2716249423Sdim  if (Phi->getParent() != TheLoop->getHeader())
2717249423Sdim    return false;
2718243789Sdim
2719249423Sdim  // Obtain the reduction start value from the value that comes from the loop
2720249423Sdim  // preheader.
2721249423Sdim  Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2722249423Sdim
2723243789Sdim  // ExitInstruction is the single value which is used outside the loop.
2724243789Sdim  // We only allow for a single reduction value to be used outside the loop.
2725243789Sdim  // This includes users of the reduction, variables (which form a cycle
2726243789Sdim  // which ends in the phi node).
2727243789Sdim  Instruction *ExitInstruction = 0;
2728249423Sdim  // Indicates that we found a binary operation in our scan.
2729249423Sdim  bool FoundBinOp = false;
2730243789Sdim
2731243789Sdim  // Iter is our iterator. We start with the PHI node and scan for all of the
2732249423Sdim  // users of this instruction. All users must be instructions that can be
2733243789Sdim  // used as reduction variables (such as ADD). We may have a single
2734249423Sdim  // out-of-block user. The cycle must end with the original PHI.
2735243789Sdim  Instruction *Iter = Phi;
2736243789Sdim  while (true) {
2737249423Sdim    // If the instruction has no users then this is a broken
2738249423Sdim    // chain and can't be a reduction variable.
2739249423Sdim    if (Iter->use_empty())
2740243789Sdim      return false;
2741243789Sdim
2742249423Sdim    // Did we find a user inside this loop already ?
2743243789Sdim    bool FoundInBlockUser = false;
2744249423Sdim    // Did we reach the initial PHI node already ?
2745243789Sdim    bool FoundStartPHI = false;
2746243789Sdim
2747249423Sdim    // Is this a bin op ?
2748249423Sdim    FoundBinOp |= !isa<PHINode>(Iter);
2749243789Sdim
2750249423Sdim    // Remember the current instruction.
2751249423Sdim    Instruction *OldIter = Iter;
2752249423Sdim
2753243789Sdim    // For each of the *users* of iter.
2754243789Sdim    for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2755243789Sdim         it != e; ++it) {
2756243789Sdim      Instruction *U = cast<Instruction>(*it);
2757243789Sdim      // We already know that the PHI is a user.
2758243789Sdim      if (U == Phi) {
2759243789Sdim        FoundStartPHI = true;
2760243789Sdim        continue;
2761243789Sdim      }
2762249423Sdim
2763243789Sdim      // Check if we found the exit user.
2764243789Sdim      BasicBlock *Parent = U->getParent();
2765249423Sdim      if (!TheLoop->contains(Parent)) {
2766249423Sdim        // Exit if you find multiple outside users.
2767243789Sdim        if (ExitInstruction != 0)
2768243789Sdim          return false;
2769243789Sdim        ExitInstruction = Iter;
2770243789Sdim      }
2771249423Sdim
2772249423Sdim      // We allow in-loop PHINodes which are not the original reduction PHI
2773249423Sdim      // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2774249423Sdim      // structure) then don't skip this PHI.
2775249423Sdim      if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2776249423Sdim          U->getParent() != TheLoop->getHeader() &&
2777249423Sdim          TheLoop->contains(U) &&
2778249423Sdim          Iter->hasNUsesOrMore(2))
2779249423Sdim        continue;
2780249423Sdim
2781243789Sdim      // We can't have multiple inside users.
2782243789Sdim      if (FoundInBlockUser)
2783243789Sdim        return false;
2784243789Sdim      FoundInBlockUser = true;
2785249423Sdim
2786249423Sdim      // Any reduction instr must be of one of the allowed kinds.
2787249423Sdim      if (!isReductionInstr(U, Kind))
2788249423Sdim        return false;
2789249423Sdim
2790249423Sdim      // Reductions of instructions such as Div, and Sub is only
2791249423Sdim      // possible if the LHS is the reduction variable.
2792249423Sdim      if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2793249423Sdim        return false;
2794249423Sdim
2795243789Sdim      Iter = U;
2796243789Sdim    }
2797243789Sdim
2798249423Sdim    // If all uses were skipped this can't be a reduction variable.
2799249423Sdim    if (Iter == OldIter)
2800249423Sdim      return false;
2801249423Sdim
2802243789Sdim    // We found a reduction var if we have reached the original
2803243789Sdim    // phi node and we only have a single instruction with out-of-loop
2804243789Sdim    // users.
2805249423Sdim    if (FoundStartPHI) {
2806249423Sdim      // This instruction is allowed to have out-of-loop users.
2807249423Sdim      AllowedExit.insert(ExitInstruction);
2808243789Sdim
2809249423Sdim      // Save the description of this reduction variable.
2810249423Sdim      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2811249423Sdim      Reductions[Phi] = RD;
2812249423Sdim      // We've ended the cycle. This is a reduction variable if we have an
2813249423Sdim      // outside user and it has a binary op.
2814249423Sdim      return FoundBinOp && ExitInstruction;
2815249423Sdim    }
2816243789Sdim  }
2817243789Sdim}
2818243789Sdim
2819243789Sdimbool
2820243789SdimLoopVectorizationLegality::isReductionInstr(Instruction *I,
2821243789Sdim                                            ReductionKind Kind) {
2822249423Sdim  bool FP = I->getType()->isFloatingPointTy();
2823249423Sdim  bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2824249423Sdim
2825249423Sdim  switch (I->getOpcode()) {
2826249423Sdim  default:
2827249423Sdim    return false;
2828249423Sdim  case Instruction::PHI:
2829249423Sdim      if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2830249423Sdim        return false;
2831249423Sdim    // possibly.
2832249423Sdim    return true;
2833249423Sdim  case Instruction::Sub:
2834249423Sdim  case Instruction::Add:
2835249423Sdim    return Kind == RK_IntegerAdd;
2836249423Sdim  case Instruction::SDiv:
2837249423Sdim  case Instruction::UDiv:
2838249423Sdim  case Instruction::Mul:
2839249423Sdim    return Kind == RK_IntegerMult;
2840249423Sdim  case Instruction::And:
2841249423Sdim    return Kind == RK_IntegerAnd;
2842249423Sdim  case Instruction::Or:
2843249423Sdim    return Kind == RK_IntegerOr;
2844249423Sdim  case Instruction::Xor:
2845249423Sdim    return Kind == RK_IntegerXor;
2846249423Sdim  case Instruction::FMul:
2847249423Sdim    return Kind == RK_FloatMult && FastMath;
2848249423Sdim  case Instruction::FAdd:
2849249423Sdim    return Kind == RK_FloatAdd && FastMath;
2850249423Sdim   }
2851243789Sdim}
2852243789Sdim
2853249423SdimLoopVectorizationLegality::InductionKind
2854249423SdimLoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2855249423Sdim  Type *PhiTy = Phi->getType();
2856249423Sdim  // We only handle integer and pointer inductions variables.
2857249423Sdim  if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2858249423Sdim    return IK_NoInduction;
2859249423Sdim
2860249423Sdim  // Check that the PHI is consecutive.
2861243789Sdim  const SCEV *PhiScev = SE->getSCEV(Phi);
2862243789Sdim  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2863243789Sdim  if (!AR) {
2864243789Sdim    DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2865249423Sdim    return IK_NoInduction;
2866243789Sdim  }
2867243789Sdim  const SCEV *Step = AR->getStepRecurrence(*SE);
2868243789Sdim
2869249423Sdim  // Integer inductions need to have a stride of one.
2870249423Sdim  if (PhiTy->isIntegerTy()) {
2871249423Sdim    if (Step->isOne())
2872249423Sdim      return IK_IntInduction;
2873249423Sdim    if (Step->isAllOnesValue())
2874249423Sdim      return IK_ReverseIntInduction;
2875249423Sdim    return IK_NoInduction;
2876249423Sdim  }
2877249423Sdim
2878249423Sdim  // Calculate the pointer stride and check if it is consecutive.
2879249423Sdim  const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2880249423Sdim  if (!C)
2881249423Sdim    return IK_NoInduction;
2882249423Sdim
2883249423Sdim  assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2884249423Sdim  uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2885249423Sdim  if (C->getValue()->equalsInt(Size))
2886249423Sdim    return IK_PtrInduction;
2887249423Sdim  else if (C->getValue()->equalsInt(0 - Size))
2888249423Sdim    return IK_ReversePtrInduction;
2889249423Sdim
2890249423Sdim  return IK_NoInduction;
2891249423Sdim}
2892249423Sdim
2893249423Sdimbool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2894249423Sdim  Value *In0 = const_cast<Value*>(V);
2895249423Sdim  PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2896249423Sdim  if (!PN)
2897243789Sdim    return false;
2898249423Sdim
2899249423Sdim  return Inductions.count(PN);
2900249423Sdim}
2901249423Sdim
2902249423Sdimbool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2903249423Sdim  assert(TheLoop->contains(BB) && "Unknown block used");
2904249423Sdim
2905249423Sdim  // Blocks that do not dominate the latch need predication.
2906249423Sdim  BasicBlock* Latch = TheLoop->getLoopLatch();
2907249423Sdim  return !DT->dominates(BB, Latch);
2908249423Sdim}
2909249423Sdim
2910249423Sdimbool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2911249423Sdim  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2912249423Sdim    // We don't predicate loads/stores at the moment.
2913249423Sdim    if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2914249423Sdim      return false;
2915249423Sdim
2916249423Sdim    // The instructions below can trap.
2917249423Sdim    switch (it->getOpcode()) {
2918249423Sdim    default: continue;
2919249423Sdim    case Instruction::UDiv:
2920249423Sdim    case Instruction::SDiv:
2921249423Sdim    case Instruction::URem:
2922249423Sdim    case Instruction::SRem:
2923249423Sdim             return false;
2924249423Sdim    }
2925243789Sdim  }
2926249423Sdim
2927243789Sdim  return true;
2928243789Sdim}
2929243789Sdim
2930243789Sdimbool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2931243789Sdim  const SCEV *PhiScev = SE->getSCEV(Ptr);
2932243789Sdim  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2933243789Sdim  if (!AR)
2934243789Sdim    return false;
2935243789Sdim
2936243789Sdim  return AR->isAffine();
2937243789Sdim}
2938243789Sdim
2939249423SdimLoopVectorizationCostModel::VectorizationFactor
2940249423SdimLoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2941249423Sdim                                                      unsigned UserVF) {
2942249423Sdim  // Width 1 means no vectorize
2943249423Sdim  VectorizationFactor Factor = { 1U, 0U };
2944249423Sdim  if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2945249423Sdim    DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2946249423Sdim    return Factor;
2947243789Sdim  }
2948243789Sdim
2949249423Sdim  // Find the trip count.
2950249423Sdim  unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2951249423Sdim  DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2952249423Sdim
2953249423Sdim  unsigned WidestType = getWidestType();
2954249423Sdim  unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2955249423Sdim  unsigned MaxVectorSize = WidestRegister / WidestType;
2956249423Sdim  DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2957249423Sdim  DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2958249423Sdim
2959249423Sdim  if (MaxVectorSize == 0) {
2960249423Sdim    DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2961249423Sdim    MaxVectorSize = 1;
2962249423Sdim  }
2963249423Sdim
2964249423Sdim  assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2965249423Sdim         " into one vector!");
2966249423Sdim
2967249423Sdim  unsigned VF = MaxVectorSize;
2968249423Sdim
2969249423Sdim  // If we optimize the program for size, avoid creating the tail loop.
2970249423Sdim  if (OptForSize) {
2971249423Sdim    // If we are unable to calculate the trip count then don't try to vectorize.
2972249423Sdim    if (TC < 2) {
2973249423Sdim      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2974249423Sdim      return Factor;
2975249423Sdim    }
2976249423Sdim
2977249423Sdim    // Find the maximum SIMD width that can fit within the trip count.
2978249423Sdim    VF = TC % MaxVectorSize;
2979249423Sdim
2980249423Sdim    if (VF == 0)
2981249423Sdim      VF = MaxVectorSize;
2982249423Sdim
2983249423Sdim    // If the trip count that we found modulo the vectorization factor is not
2984249423Sdim    // zero then we require a tail.
2985249423Sdim    if (VF < 2) {
2986249423Sdim      DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2987249423Sdim      return Factor;
2988249423Sdim    }
2989249423Sdim  }
2990249423Sdim
2991249423Sdim  if (UserVF != 0) {
2992249423Sdim    assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2993249423Sdim    DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2994249423Sdim
2995249423Sdim    Factor.Width = UserVF;
2996249423Sdim    return Factor;
2997249423Sdim  }
2998249423Sdim
2999243789Sdim  float Cost = expectedCost(1);
3000243789Sdim  unsigned Width = 1;
3001243789Sdim  DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
3002243789Sdim  for (unsigned i=2; i <= VF; i*=2) {
3003243789Sdim    // Notice that the vector loop needs to be executed less times, so
3004243789Sdim    // we need to divide the cost of the vector loops by the width of
3005243789Sdim    // the vector elements.
3006243789Sdim    float VectorCost = expectedCost(i) / (float)i;
3007243789Sdim    DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3008243789Sdim          (int)VectorCost << ".\n");
3009243789Sdim    if (VectorCost < Cost) {
3010243789Sdim      Cost = VectorCost;
3011243789Sdim      Width = i;
3012243789Sdim    }
3013243789Sdim  }
3014243789Sdim
3015243789Sdim  DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3016249423Sdim  Factor.Width = Width;
3017249423Sdim  Factor.Cost = Width * Cost;
3018249423Sdim  return Factor;
3019243789Sdim}
3020243789Sdim
3021249423Sdimunsigned LoopVectorizationCostModel::getWidestType() {
3022249423Sdim  unsigned MaxWidth = 8;
3023249423Sdim
3024249423Sdim  // For each block.
3025249423Sdim  for (Loop::block_iterator bb = TheLoop->block_begin(),
3026249423Sdim       be = TheLoop->block_end(); bb != be; ++bb) {
3027249423Sdim    BasicBlock *BB = *bb;
3028249423Sdim
3029249423Sdim    // For each instruction in the loop.
3030249423Sdim    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3031249423Sdim      Type *T = it->getType();
3032249423Sdim
3033249423Sdim      // Only examine Loads, Stores and PHINodes.
3034249423Sdim      if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3035249423Sdim        continue;
3036249423Sdim
3037249423Sdim      // Examine PHI nodes that are reduction variables.
3038249423Sdim      if (PHINode *PN = dyn_cast<PHINode>(it))
3039249423Sdim        if (!Legal->getReductionVars()->count(PN))
3040249423Sdim          continue;
3041249423Sdim
3042249423Sdim      // Examine the stored values.
3043249423Sdim      if (StoreInst *ST = dyn_cast<StoreInst>(it))
3044249423Sdim        T = ST->getValueOperand()->getType();
3045249423Sdim
3046249423Sdim      // Ignore loaded pointer types and stored pointer types that are not
3047249423Sdim      // consecutive. However, we do want to take consecutive stores/loads of
3048249423Sdim      // pointer vectors into account.
3049249423Sdim      if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3050249423Sdim        continue;
3051249423Sdim
3052249423Sdim      MaxWidth = std::max(MaxWidth,
3053249423Sdim                          (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3054249423Sdim    }
3055249423Sdim  }
3056249423Sdim
3057249423Sdim  return MaxWidth;
3058249423Sdim}
3059249423Sdim
3060249423Sdimunsigned
3061249423SdimLoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3062249423Sdim                                               unsigned UserUF,
3063249423Sdim                                               unsigned VF,
3064249423Sdim                                               unsigned LoopCost) {
3065249423Sdim
3066249423Sdim  // -- The unroll heuristics --
3067249423Sdim  // We unroll the loop in order to expose ILP and reduce the loop overhead.
3068249423Sdim  // There are many micro-architectural considerations that we can't predict
3069249423Sdim  // at this level. For example frontend pressure (on decode or fetch) due to
3070249423Sdim  // code size, or the number and capabilities of the execution ports.
3071249423Sdim  //
3072249423Sdim  // We use the following heuristics to select the unroll factor:
3073249423Sdim  // 1. If the code has reductions the we unroll in order to break the cross
3074249423Sdim  // iteration dependency.
3075249423Sdim  // 2. If the loop is really small then we unroll in order to reduce the loop
3076249423Sdim  // overhead.
3077249423Sdim  // 3. We don't unroll if we think that we will spill registers to memory due
3078249423Sdim  // to the increased register pressure.
3079249423Sdim
3080249423Sdim  // Use the user preference, unless 'auto' is selected.
3081249423Sdim  if (UserUF != 0)
3082249423Sdim    return UserUF;
3083249423Sdim
3084249423Sdim  // When we optimize for size we don't unroll.
3085249423Sdim  if (OptForSize)
3086249423Sdim    return 1;
3087249423Sdim
3088249423Sdim  // Do not unroll loops with a relatively small trip count.
3089249423Sdim  unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3090249423Sdim                                              TheLoop->getLoopLatch());
3091249423Sdim  if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3092249423Sdim    return 1;
3093249423Sdim
3094249423Sdim  unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3095249423Sdim  DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3096249423Sdim        " vector registers\n");
3097249423Sdim
3098249423Sdim  LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3099249423Sdim  // We divide by these constants so assume that we have at least one
3100249423Sdim  // instruction that uses at least one register.
3101249423Sdim  R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3102249423Sdim  R.NumInstructions = std::max(R.NumInstructions, 1U);
3103249423Sdim
3104249423Sdim  // We calculate the unroll factor using the following formula.
3105249423Sdim  // Subtract the number of loop invariants from the number of available
3106249423Sdim  // registers. These registers are used by all of the unrolled instances.
3107249423Sdim  // Next, divide the remaining registers by the number of registers that is
3108249423Sdim  // required by the loop, in order to estimate how many parallel instances
3109249423Sdim  // fit without causing spills.
3110249423Sdim  unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3111249423Sdim
3112249423Sdim  // Clamp the unroll factor ranges to reasonable factors.
3113249423Sdim  unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3114249423Sdim
3115249423Sdim  // If we did not calculate the cost for VF (because the user selected the VF)
3116249423Sdim  // then we calculate the cost of VF here.
3117249423Sdim  if (LoopCost == 0)
3118249423Sdim    LoopCost = expectedCost(VF);
3119249423Sdim
3120249423Sdim  // Clamp the calculated UF to be between the 1 and the max unroll factor
3121249423Sdim  // that the target allows.
3122249423Sdim  if (UF > MaxUnrollSize)
3123249423Sdim    UF = MaxUnrollSize;
3124249423Sdim  else if (UF < 1)
3125249423Sdim    UF = 1;
3126249423Sdim
3127249423Sdim  if (Legal->getReductionVars()->size()) {
3128249423Sdim    DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3129249423Sdim    return UF;
3130249423Sdim  }
3131249423Sdim
3132249423Sdim  // We want to unroll tiny loops in order to reduce the loop overhead.
3133249423Sdim  // We assume that the cost overhead is 1 and we use the cost model
3134249423Sdim  // to estimate the cost of the loop and unroll until the cost of the
3135249423Sdim  // loop overhead is about 5% of the cost of the loop.
3136249423Sdim  DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3137249423Sdim  if (LoopCost < 20) {
3138249423Sdim    DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3139249423Sdim    unsigned NewUF = 20/LoopCost + 1;
3140249423Sdim    return std::min(NewUF, UF);
3141249423Sdim  }
3142249423Sdim
3143249423Sdim  DEBUG(dbgs() << "LV: Not Unrolling. \n");
3144249423Sdim  return 1;
3145249423Sdim}
3146249423Sdim
3147249423SdimLoopVectorizationCostModel::RegisterUsage
3148249423SdimLoopVectorizationCostModel::calculateRegisterUsage() {
3149249423Sdim  // This function calculates the register usage by measuring the highest number
3150249423Sdim  // of values that are alive at a single location. Obviously, this is a very
3151249423Sdim  // rough estimation. We scan the loop in a topological order in order and
3152249423Sdim  // assign a number to each instruction. We use RPO to ensure that defs are
3153249423Sdim  // met before their users. We assume that each instruction that has in-loop
3154249423Sdim  // users starts an interval. We record every time that an in-loop value is
3155249423Sdim  // used, so we have a list of the first and last occurrences of each
3156249423Sdim  // instruction. Next, we transpose this data structure into a multi map that
3157249423Sdim  // holds the list of intervals that *end* at a specific location. This multi
3158249423Sdim  // map allows us to perform a linear search. We scan the instructions linearly
3159249423Sdim  // and record each time that a new interval starts, by placing it in a set.
3160249423Sdim  // If we find this value in the multi-map then we remove it from the set.
3161249423Sdim  // The max register usage is the maximum size of the set.
3162249423Sdim  // We also search for instructions that are defined outside the loop, but are
3163249423Sdim  // used inside the loop. We need this number separately from the max-interval
3164249423Sdim  // usage number because when we unroll, loop-invariant values do not take
3165249423Sdim  // more register.
3166249423Sdim  LoopBlocksDFS DFS(TheLoop);
3167249423Sdim  DFS.perform(LI);
3168249423Sdim
3169249423Sdim  RegisterUsage R;
3170249423Sdim  R.NumInstructions = 0;
3171249423Sdim
3172249423Sdim  // Each 'key' in the map opens a new interval. The values
3173249423Sdim  // of the map are the index of the 'last seen' usage of the
3174249423Sdim  // instruction that is the key.
3175249423Sdim  typedef DenseMap<Instruction*, unsigned> IntervalMap;
3176249423Sdim  // Maps instruction to its index.
3177249423Sdim  DenseMap<unsigned, Instruction*> IdxToInstr;
3178249423Sdim  // Marks the end of each interval.
3179249423Sdim  IntervalMap EndPoint;
3180249423Sdim  // Saves the list of instruction indices that are used in the loop.
3181249423Sdim  SmallSet<Instruction*, 8> Ends;
3182249423Sdim  // Saves the list of values that are used in the loop but are
3183249423Sdim  // defined outside the loop, such as arguments and constants.
3184249423Sdim  SmallPtrSet<Value*, 8> LoopInvariants;
3185249423Sdim
3186249423Sdim  unsigned Index = 0;
3187249423Sdim  for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3188249423Sdim       be = DFS.endRPO(); bb != be; ++bb) {
3189249423Sdim    R.NumInstructions += (*bb)->size();
3190249423Sdim    for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3191249423Sdim         ++it) {
3192249423Sdim      Instruction *I = it;
3193249423Sdim      IdxToInstr[Index++] = I;
3194249423Sdim
3195249423Sdim      // Save the end location of each USE.
3196249423Sdim      for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3197249423Sdim        Value *U = I->getOperand(i);
3198249423Sdim        Instruction *Instr = dyn_cast<Instruction>(U);
3199249423Sdim
3200249423Sdim        // Ignore non-instruction values such as arguments, constants, etc.
3201249423Sdim        if (!Instr) continue;
3202249423Sdim
3203249423Sdim        // If this instruction is outside the loop then record it and continue.
3204249423Sdim        if (!TheLoop->contains(Instr)) {
3205249423Sdim          LoopInvariants.insert(Instr);
3206249423Sdim          continue;
3207249423Sdim        }
3208249423Sdim
3209249423Sdim        // Overwrite previous end points.
3210249423Sdim        EndPoint[Instr] = Index;
3211249423Sdim        Ends.insert(Instr);
3212249423Sdim      }
3213249423Sdim    }
3214249423Sdim  }
3215249423Sdim
3216249423Sdim  // Saves the list of intervals that end with the index in 'key'.
3217249423Sdim  typedef SmallVector<Instruction*, 2> InstrList;
3218249423Sdim  DenseMap<unsigned, InstrList> TransposeEnds;
3219249423Sdim
3220249423Sdim  // Transpose the EndPoints to a list of values that end at each index.
3221249423Sdim  for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3222249423Sdim       it != e; ++it)
3223249423Sdim    TransposeEnds[it->second].push_back(it->first);
3224249423Sdim
3225249423Sdim  SmallSet<Instruction*, 8> OpenIntervals;
3226249423Sdim  unsigned MaxUsage = 0;
3227249423Sdim
3228249423Sdim
3229249423Sdim  DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3230249423Sdim  for (unsigned int i = 0; i < Index; ++i) {
3231249423Sdim    Instruction *I = IdxToInstr[i];
3232249423Sdim    // Ignore instructions that are never used within the loop.
3233249423Sdim    if (!Ends.count(I)) continue;
3234249423Sdim
3235249423Sdim    // Remove all of the instructions that end at this location.
3236249423Sdim    InstrList &List = TransposeEnds[i];
3237249423Sdim    for (unsigned int j=0, e = List.size(); j < e; ++j)
3238249423Sdim      OpenIntervals.erase(List[j]);
3239249423Sdim
3240249423Sdim    // Count the number of live interals.
3241249423Sdim    MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3242249423Sdim
3243249423Sdim    DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3244249423Sdim          OpenIntervals.size() <<"\n");
3245249423Sdim
3246249423Sdim    // Add the current instruction to the list of open intervals.
3247249423Sdim    OpenIntervals.insert(I);
3248249423Sdim  }
3249249423Sdim
3250249423Sdim  unsigned Invariant = LoopInvariants.size();
3251249423Sdim  DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3252249423Sdim  DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3253249423Sdim  DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3254249423Sdim
3255249423Sdim  R.LoopInvariantRegs = Invariant;
3256249423Sdim  R.MaxLocalUsers = MaxUsage;
3257249423Sdim  return R;
3258249423Sdim}
3259249423Sdim
3260243789Sdimunsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3261243789Sdim  unsigned Cost = 0;
3262243789Sdim
3263249423Sdim  // For each block.
3264249423Sdim  for (Loop::block_iterator bb = TheLoop->block_begin(),
3265249423Sdim       be = TheLoop->block_end(); bb != be; ++bb) {
3266249423Sdim    unsigned BlockCost = 0;
3267249423Sdim    BasicBlock *BB = *bb;
3268249423Sdim
3269249423Sdim    // For each instruction in the old loop.
3270249423Sdim    for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3271249423Sdim      // Skip dbg intrinsics.
3272249423Sdim      if (isa<DbgInfoIntrinsic>(it))
3273249423Sdim        continue;
3274249423Sdim
3275249423Sdim      unsigned C = getInstructionCost(it, VF);
3276249423Sdim      Cost += C;
3277249423Sdim      DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3278249423Sdim            VF << " For instruction: "<< *it << "\n");
3279249423Sdim    }
3280249423Sdim
3281249423Sdim    // We assume that if-converted blocks have a 50% chance of being executed.
3282249423Sdim    // When the code is scalar then some of the blocks are avoided due to CF.
3283249423Sdim    // When the code is vectorized we execute all code paths.
3284249423Sdim    if (Legal->blockNeedsPredication(*bb) && VF == 1)
3285249423Sdim      BlockCost /= 2;
3286249423Sdim
3287249423Sdim    Cost += BlockCost;
3288243789Sdim  }
3289243789Sdim
3290243789Sdim  return Cost;
3291243789Sdim}
3292243789Sdim
3293243789Sdimunsigned
3294243789SdimLoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3295243789Sdim  // If we know that this instruction will remain uniform, check the cost of
3296243789Sdim  // the scalar version.
3297243789Sdim  if (Legal->isUniformAfterVectorization(I))
3298243789Sdim    VF = 1;
3299243789Sdim
3300243789Sdim  Type *RetTy = I->getType();
3301243789Sdim  Type *VectorTy = ToVectorTy(RetTy, VF);
3302243789Sdim
3303243789Sdim  // TODO: We need to estimate the cost of intrinsic calls.
3304243789Sdim  switch (I->getOpcode()) {
3305249423Sdim  case Instruction::GetElementPtr:
3306249423Sdim    // We mark this instruction as zero-cost because the cost of GEPs in
3307249423Sdim    // vectorized code depends on whether the corresponding memory instruction
3308249423Sdim    // is scalarized or not. Therefore, we handle GEPs with the memory
3309249423Sdim    // instruction cost.
3310249423Sdim    return 0;
3311249423Sdim  case Instruction::Br: {
3312249423Sdim    return TTI.getCFInstrCost(I->getOpcode());
3313249423Sdim  }
3314249423Sdim  case Instruction::PHI:
3315249423Sdim    //TODO: IF-converted IFs become selects.
3316249423Sdim    return 0;
3317249423Sdim  case Instruction::Add:
3318249423Sdim  case Instruction::FAdd:
3319249423Sdim  case Instruction::Sub:
3320249423Sdim  case Instruction::FSub:
3321249423Sdim  case Instruction::Mul:
3322249423Sdim  case Instruction::FMul:
3323249423Sdim  case Instruction::UDiv:
3324249423Sdim  case Instruction::SDiv:
3325249423Sdim  case Instruction::FDiv:
3326249423Sdim  case Instruction::URem:
3327249423Sdim  case Instruction::SRem:
3328249423Sdim  case Instruction::FRem:
3329249423Sdim  case Instruction::Shl:
3330249423Sdim  case Instruction::LShr:
3331249423Sdim  case Instruction::AShr:
3332249423Sdim  case Instruction::And:
3333249423Sdim  case Instruction::Or:
3334249423Sdim  case Instruction::Xor: {
3335249423Sdim    // Certain instructions can be cheaper to vectorize if they have a constant
3336249423Sdim    // second vector operand. One example of this are shifts on x86.
3337249423Sdim    TargetTransformInfo::OperandValueKind Op1VK =
3338249423Sdim      TargetTransformInfo::OK_AnyValue;
3339249423Sdim    TargetTransformInfo::OperandValueKind Op2VK =
3340249423Sdim      TargetTransformInfo::OK_AnyValue;
3341243789Sdim
3342249423Sdim    if (isa<ConstantInt>(I->getOperand(1)))
3343249423Sdim      Op2VK = TargetTransformInfo::OK_UniformConstantValue;
3344243789Sdim
3345249423Sdim    return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
3346249423Sdim  }
3347249423Sdim  case Instruction::Select: {
3348249423Sdim    SelectInst *SI = cast<SelectInst>(I);
3349249423Sdim    const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3350249423Sdim    bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3351249423Sdim    Type *CondTy = SI->getCondition()->getType();
3352249423Sdim    if (!ScalarCond)
3353249423Sdim      CondTy = VectorType::get(CondTy, VF);
3354243789Sdim
3355249423Sdim    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3356249423Sdim  }
3357249423Sdim  case Instruction::ICmp:
3358249423Sdim  case Instruction::FCmp: {
3359249423Sdim    Type *ValTy = I->getOperand(0)->getType();
3360249423Sdim    VectorTy = ToVectorTy(ValTy, VF);
3361249423Sdim    return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3362249423Sdim  }
3363249423Sdim  case Instruction::Store:
3364249423Sdim  case Instruction::Load: {
3365249423Sdim    StoreInst *SI = dyn_cast<StoreInst>(I);
3366249423Sdim    LoadInst *LI = dyn_cast<LoadInst>(I);
3367249423Sdim    Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3368249423Sdim                   LI->getType());
3369249423Sdim    VectorTy = ToVectorTy(ValTy, VF);
3370243789Sdim
3371249423Sdim    unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3372249423Sdim    unsigned AS = SI ? SI->getPointerAddressSpace() :
3373249423Sdim      LI->getPointerAddressSpace();
3374249423Sdim    Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3375249423Sdim    // We add the cost of address computation here instead of with the gep
3376249423Sdim    // instruction because only here we know whether the operation is
3377249423Sdim    // scalarized.
3378249423Sdim    if (VF == 1)
3379249423Sdim      return TTI.getAddressComputationCost(VectorTy) +
3380249423Sdim        TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3381243789Sdim
3382249423Sdim    // Scalarized loads/stores.
3383249423Sdim    int Stride = Legal->isConsecutivePtr(Ptr);
3384249423Sdim    bool Reverse = Stride < 0;
3385249423Sdim    if (0 == Stride) {
3386249423Sdim      unsigned Cost = 0;
3387249423Sdim      // The cost of extracting from the value vector and pointer vector.
3388249423Sdim      Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3389249423Sdim      for (unsigned i = 0; i < VF; ++i) {
3390249423Sdim        //  The cost of extracting the pointer operand.
3391249423Sdim        Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3392249423Sdim        // In case of STORE, the cost of ExtractElement from the vector.
3393249423Sdim        // In case of LOAD, the cost of InsertElement into the returned
3394249423Sdim        // vector.
3395249423Sdim        Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3396249423Sdim                                            Instruction::InsertElement,
3397249423Sdim                                            VectorTy, i);
3398243789Sdim      }
3399243789Sdim
3400249423Sdim      // The cost of the scalar loads/stores.
3401249423Sdim      Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3402249423Sdim      Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3403249423Sdim                                       Alignment, AS);
3404249423Sdim      return Cost;
3405243789Sdim    }
3406243789Sdim
3407249423Sdim    // Wide load/stores.
3408249423Sdim    unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3409249423Sdim    Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3410243789Sdim
3411249423Sdim    if (Reverse)
3412249423Sdim      Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3413249423Sdim                                  VectorTy, 0);
3414249423Sdim    return Cost;
3415249423Sdim  }
3416249423Sdim  case Instruction::ZExt:
3417249423Sdim  case Instruction::SExt:
3418249423Sdim  case Instruction::FPToUI:
3419249423Sdim  case Instruction::FPToSI:
3420249423Sdim  case Instruction::FPExt:
3421249423Sdim  case Instruction::PtrToInt:
3422249423Sdim  case Instruction::IntToPtr:
3423249423Sdim  case Instruction::SIToFP:
3424249423Sdim  case Instruction::UIToFP:
3425249423Sdim  case Instruction::Trunc:
3426249423Sdim  case Instruction::FPTrunc:
3427249423Sdim  case Instruction::BitCast: {
3428249423Sdim    // We optimize the truncation of induction variable.
3429249423Sdim    // The cost of these is the same as the scalar operation.
3430249423Sdim    if (I->getOpcode() == Instruction::Trunc &&
3431249423Sdim        Legal->isInductionVariable(I->getOperand(0)))
3432249423Sdim      return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3433249423Sdim                                  I->getOperand(0)->getType());
3434243789Sdim
3435249423Sdim    Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3436249423Sdim    return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3437249423Sdim  }
3438249423Sdim  case Instruction::Call: {
3439249423Sdim    CallInst *CI = cast<CallInst>(I);
3440249423Sdim    Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3441249423Sdim    assert(ID && "Not an intrinsic call!");
3442249423Sdim    Type *RetTy = ToVectorTy(CI->getType(), VF);
3443249423Sdim    SmallVector<Type*, 4> Tys;
3444249423Sdim    for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3445249423Sdim      Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3446249423Sdim    return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3447249423Sdim  }
3448249423Sdim  default: {
3449249423Sdim    // We are scalarizing the instruction. Return the cost of the scalar
3450249423Sdim    // instruction, plus the cost of insert and extract into vector
3451249423Sdim    // elements, times the vector width.
3452249423Sdim    unsigned Cost = 0;
3453243789Sdim
3454249423Sdim    if (!RetTy->isVoidTy() && VF != 1) {
3455249423Sdim      unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3456249423Sdim                                                VectorTy);
3457249423Sdim      unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3458249423Sdim                                                VectorTy);
3459249423Sdim
3460243789Sdim      // The cost of inserting the results plus extracting each one of the
3461243789Sdim      // operands.
3462243789Sdim      Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3463249423Sdim    }
3464243789Sdim
3465249423Sdim    // The cost of executing VF copies of the scalar instruction. This opcode
3466249423Sdim    // is unknown. Assume that it is the same as 'mul'.
3467249423Sdim    Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3468249423Sdim    return Cost;
3469249423Sdim  }
3470243789Sdim  }// end of switch.
3471243789Sdim}
3472243789Sdim
3473243789SdimType* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3474243789Sdim  if (Scalar->isVoidTy() || VF == 1)
3475243789Sdim    return Scalar;
3476243789Sdim  return VectorType::get(Scalar, VF);
3477243789Sdim}
3478243789Sdim
3479243789Sdimchar LoopVectorize::ID = 0;
3480243789Sdimstatic const char lv_name[] = "Loop Vectorization";
3481243789SdimINITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3482243789SdimINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3483249423SdimINITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3484243789SdimINITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3485243789SdimINITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3486243789SdimINITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3487243789Sdim
3488243789Sdimnamespace llvm {
3489243789Sdim  Pass *createLoopVectorizePass() {
3490243789Sdim    return new LoopVectorize();
3491243789Sdim  }
3492243789Sdim}
3493243789Sdim
3494249423Sdimbool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3495249423Sdim  // Check for a store.
3496249423Sdim  if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3497249423Sdim    return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3498249423Sdim
3499249423Sdim  // Check for a load.
3500249423Sdim  if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3501249423Sdim    return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
3502249423Sdim
3503249423Sdim  return false;
3504249423Sdim}
3505