LoopVectorize: convert TinyTripCountVectorThreshold constant
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
14 //
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 //    of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 //    widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 //    of vectorization. It decides on the optimal vector width, which
27 //    can be one, if vectorization is not profitable.
28 //
29 //===----------------------------------------------------------------------===//
30 //
31 // The reduction-variable vectorization is based on the paper:
32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 //
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 //
37 // Other ideas/concepts are from:
38 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //
40 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41 //  Vectorizing Compilers.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
47
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
85 #include <algorithm>
86 #include <map>
87
88 using namespace llvm;
89
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92                     cl::desc("Sets the SIMD width. Zero is autoselect."));
93
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96                     cl::desc("Sets the vectorization unroll count. "
97                              "Zero is autoselect."));
98
99 static cl::opt<bool>
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101                    cl::desc("Enable if-conversion during vectorization."));
102
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static cl::opt<unsigned>
105 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), cl::Hidden,
106                              cl::desc("The minimum trip count in the loops to vectorize."));
107
108 /// We don't unroll loops with a known constant trip count below this number.
109 static const unsigned TinyTripCountUnrollThreshold = 128;
110
111 /// When performing a runtime memory check, do not check more than this
112 /// number of pointers. Notice that the check is quadratic!
113 static const unsigned RuntimeMemoryCheckThreshold = 4;
114
115 namespace {
116
117 // Forward declarations.
118 class LoopVectorizationLegality;
119 class LoopVectorizationCostModel;
120
121 /// InnerLoopVectorizer vectorizes loops which contain only one basic
122 /// block to a specified vectorization factor (VF).
123 /// This class performs the widening of scalars into vectors, or multiple
124 /// scalars. This class also implements the following features:
125 /// * It inserts an epilogue loop for handling loops that don't have iteration
126 ///   counts that are known to be a multiple of the vectorization factor.
127 /// * It handles the code generation for reduction variables.
128 /// * Scalarization (implementation using scalars) of un-vectorizable
129 ///   instructions.
130 /// InnerLoopVectorizer does not perform any vectorization-legality
131 /// checks, and relies on the caller to check for the different legality
132 /// aspects. The InnerLoopVectorizer relies on the
133 /// LoopVectorizationLegality class to provide information about the induction
134 /// and reduction variables that were found to a given vectorization factor.
135 class InnerLoopVectorizer {
136 public:
137   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
138                       DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
139                       unsigned UnrollFactor)
140       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
141         UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
142         OldInduction(0), WidenMap(UnrollFactor) {}
143
144   // Perform the actual loop widening (vectorization).
145   void vectorize(LoopVectorizationLegality *Legal) {
146     // Create a new empty loop. Unlink the old loop and connect the new one.
147     createEmptyLoop(Legal);
148     // Widen each instruction in the old loop to a new one in the new loop.
149     // Use the Legality module to find the induction and reduction variables.
150     vectorizeLoop(Legal);
151     // Register the new loop and update the analysis passes.
152     updateAnalysis();
153   }
154
155 private:
156   /// A small list of PHINodes.
157   typedef SmallVector<PHINode*, 4> PhiVector;
158   /// When we unroll loops we have multiple vector values for each scalar.
159   /// This data structure holds the unrolled and vectorized values that
160   /// originated from one scalar instruction.
161   typedef SmallVector<Value*, 2> VectorParts;
162
163   /// Add code that checks at runtime if the accessed arrays overlap.
164   /// Returns the comparator value or NULL if no check is needed.
165   Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
166                                Instruction *Loc);
167   /// Create an empty loop, based on the loop ranges of the old loop.
168   void createEmptyLoop(LoopVectorizationLegality *Legal);
169   /// Copy and widen the instructions from the old loop.
170   void vectorizeLoop(LoopVectorizationLegality *Legal);
171
172   /// A helper function that computes the predicate of the block BB, assuming
173   /// that the header block of the loop is set to True. It returns the *entry*
174   /// mask for the block BB.
175   VectorParts createBlockInMask(BasicBlock *BB);
176   /// A helper function that computes the predicate of the edge between SRC
177   /// and DST.
178   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
179
180   /// A helper function to vectorize a single BB within the innermost loop.
181   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
182                             PhiVector *PV);
183
184   /// Insert the new loop to the loop hierarchy and pass manager
185   /// and update the analysis passes.
186   void updateAnalysis();
187
188   /// This instruction is un-vectorizable. Implement it as a sequence
189   /// of scalars.
190   void scalarizeInstruction(Instruction *Instr);
191
192   /// Vectorize Load and Store instructions,
193   void vectorizeMemoryInstruction(Instruction *Instr,
194                                   LoopVectorizationLegality *Legal);
195
196   /// Create a broadcast instruction. This method generates a broadcast
197   /// instruction (shuffle) for loop invariant values and for the induction
198   /// value. If this is the induction variable then we extend it to N, N+1, ...
199   /// this is needed because each iteration in the loop corresponds to a SIMD
200   /// element.
201   Value *getBroadcastInstrs(Value *V);
202
203   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
204   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
205   /// The sequence starts at StartIndex.
206   Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
207
208   /// When we go over instructions in the basic block we rely on previous
209   /// values within the current basic block or on loop invariant values.
210   /// When we widen (vectorize) values we place them in the map. If the values
211   /// are not within the map, they have to be loop invariant, so we simply
212   /// broadcast them into a vector.
213   VectorParts &getVectorValue(Value *V);
214
215   /// Generate a shuffle sequence that will reverse the vector Vec.
216   Value *reverseVector(Value *Vec);
217
218   /// This is a helper class that holds the vectorizer state. It maps scalar
219   /// instructions to vector instructions. When the code is 'unrolled' then
220   /// then a single scalar value is mapped to multiple vector parts. The parts
221   /// are stored in the VectorPart type.
222   struct ValueMap {
223     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
224     /// are mapped.
225     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
226
227     /// \return True if 'Key' is saved in the Value Map.
228     bool has(Value *Key) const { return MapStorage.count(Key); }
229
230     /// Initializes a new entry in the map. Sets all of the vector parts to the
231     /// save value in 'Val'.
232     /// \return A reference to a vector with splat values.
233     VectorParts &splat(Value *Key, Value *Val) {
234       VectorParts &Entry = MapStorage[Key];
235       Entry.assign(UF, Val);
236       return Entry;
237     }
238
239     ///\return A reference to the value that is stored at 'Key'.
240     VectorParts &get(Value *Key) {
241       VectorParts &Entry = MapStorage[Key];
242       if (Entry.empty())
243         Entry.resize(UF);
244       assert(Entry.size() == UF);
245       return Entry;
246     }
247
248   private:
249     /// The unroll factor. Each entry in the map stores this number of vector
250     /// elements.
251     unsigned UF;
252
253     /// Map storage. We use std::map and not DenseMap because insertions to a
254     /// dense map invalidates its iterators.
255     std::map<Value *, VectorParts> MapStorage;
256   };
257
258   /// The original loop.
259   Loop *OrigLoop;
260   /// Scev analysis to use.
261   ScalarEvolution *SE;
262   /// Loop Info.
263   LoopInfo *LI;
264   /// Dominator Tree.
265   DominatorTree *DT;
266   /// Data Layout.
267   DataLayout *DL;
268   /// The vectorization SIMD factor to use. Each vector will have this many
269   /// vector elements.
270   unsigned VF;
271   /// The vectorization unroll factor to use. Each scalar is vectorized to this
272   /// many different vector instructions.
273   unsigned UF;
274
275   /// The builder that we use
276   IRBuilder<> Builder;
277
278   // --- Vectorization state ---
279
280   /// The vector-loop preheader.
281   BasicBlock *LoopVectorPreHeader;
282   /// The scalar-loop preheader.
283   BasicBlock *LoopScalarPreHeader;
284   /// Middle Block between the vector and the scalar.
285   BasicBlock *LoopMiddleBlock;
286   ///The ExitBlock of the scalar loop.
287   BasicBlock *LoopExitBlock;
288   ///The vector loop body.
289   BasicBlock *LoopVectorBody;
290   ///The scalar loop body.
291   BasicBlock *LoopScalarBody;
292   /// A list of all bypass blocks. The first block is the entry of the loop.
293   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
294
295   /// The new Induction variable which was added to the new block.
296   PHINode *Induction;
297   /// The induction variable of the old basic block.
298   PHINode *OldInduction;
299   /// Maps scalars to widened vectors.
300   ValueMap WidenMap;
301 };
302
303 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
304 /// to what vectorization factor.
305 /// This class does not look at the profitability of vectorization, only the
306 /// legality. This class has two main kinds of checks:
307 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
308 ///   will change the order of memory accesses in a way that will change the
309 ///   correctness of the program.
310 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
311 /// checks for a number of different conditions, such as the availability of a
312 /// single induction variable, that all types are supported and vectorize-able,
313 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
314 /// This class is also used by InnerLoopVectorizer for identifying
315 /// induction variable and the different reduction variables.
316 class LoopVectorizationLegality {
317 public:
318   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
319                             DominatorTree *DT)
320       : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
321
322   /// This enum represents the kinds of reductions that we support.
323   enum ReductionKind {
324     RK_NoReduction, ///< Not a reduction.
325     RK_IntegerAdd,  ///< Sum of integers.
326     RK_IntegerMult, ///< Product of integers.
327     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
328     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
329     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
330     RK_FloatAdd,    ///< Sum of floats.
331     RK_FloatMult    ///< Product of floats.
332   };
333
334   /// This enum represents the kinds of inductions that we support.
335   enum InductionKind {
336     IK_NoInduction,         ///< Not an induction variable.
337     IK_IntInduction,        ///< Integer induction variable. Step = 1.
338     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
339     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
340     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
341   };
342
343   /// This POD struct holds information about reduction variables.
344   struct ReductionDescriptor {
345     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
346       Kind(RK_NoReduction) {}
347
348     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
349         : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
350
351     // The starting value of the reduction.
352     // It does not have to be zero!
353     Value *StartValue;
354     // The instruction who's value is used outside the loop.
355     Instruction *LoopExitInstr;
356     // The kind of the reduction.
357     ReductionKind Kind;
358   };
359
360   // This POD struct holds information about the memory runtime legality
361   // check that a group of pointers do not overlap.
362   struct RuntimePointerCheck {
363     RuntimePointerCheck() : Need(false) {}
364
365     /// Reset the state of the pointer runtime information.
366     void reset() {
367       Need = false;
368       Pointers.clear();
369       Starts.clear();
370       Ends.clear();
371     }
372
373     /// Insert a pointer and calculate the start and end SCEVs.
374     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
375
376     /// This flag indicates if we need to add the runtime check.
377     bool Need;
378     /// Holds the pointers that we need to check.
379     SmallVector<Value*, 2> Pointers;
380     /// Holds the pointer value at the beginning of the loop.
381     SmallVector<const SCEV*, 2> Starts;
382     /// Holds the pointer value at the end of the loop.
383     SmallVector<const SCEV*, 2> Ends;
384   };
385
386   /// A POD for saving information about induction variables.
387   struct InductionInfo {
388     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
389     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
390     /// Start value.
391     Value *StartValue;
392     /// Induction kind.
393     InductionKind IK;
394   };
395
396   /// ReductionList contains the reduction descriptors for all
397   /// of the reductions that were found in the loop.
398   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
399
400   /// InductionList saves induction variables and maps them to the
401   /// induction descriptor.
402   typedef MapVector<PHINode*, InductionInfo> InductionList;
403
404   /// Returns true if it is legal to vectorize this loop.
405   /// This does not mean that it is profitable to vectorize this
406   /// loop, only that it is legal to do so.
407   bool canVectorize();
408
409   /// Returns the Induction variable.
410   PHINode *getInduction() { return Induction; }
411
412   /// Returns the reduction variables found in the loop.
413   ReductionList *getReductionVars() { return &Reductions; }
414
415   /// Returns the induction variables found in the loop.
416   InductionList *getInductionVars() { return &Inductions; }
417
418   /// Returns True if V is an induction variable in this loop.
419   bool isInductionVariable(const Value *V);
420
421   /// Return true if the block BB needs to be predicated in order for the loop
422   /// to be vectorized.
423   bool blockNeedsPredication(BasicBlock *BB);
424
425   /// Check if this  pointer is consecutive when vectorizing. This happens
426   /// when the last index of the GEP is the induction variable, or that the
427   /// pointer itself is an induction variable.
428   /// This check allows us to vectorize A[idx] into a wide load/store.
429   /// Returns:
430   /// 0 - Stride is unknown or non consecutive.
431   /// 1 - Address is consecutive.
432   /// -1 - Address is consecutive, and decreasing.
433   int isConsecutivePtr(Value *Ptr);
434
435   /// Returns true if the value V is uniform within the loop.
436   bool isUniform(Value *V);
437
438   /// Returns true if this instruction will remain scalar after vectorization.
439   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
440
441   /// Returns the information that we collected about runtime memory check.
442   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
443 private:
444   /// Check if a single basic block loop is vectorizable.
445   /// At this point we know that this is a loop with a constant trip count
446   /// and we only need to check individual instructions.
447   bool canVectorizeInstrs();
448
449   /// When we vectorize loops we may change the order in which
450   /// we read and write from memory. This method checks if it is
451   /// legal to vectorize the code, considering only memory constrains.
452   /// Returns true if the loop is vectorizable
453   bool canVectorizeMemory();
454
455   /// Return true if we can vectorize this loop using the IF-conversion
456   /// transformation.
457   bool canVectorizeWithIfConvert();
458
459   /// Collect the variables that need to stay uniform after vectorization.
460   void collectLoopUniforms();
461
462   /// Return true if all of the instructions in the block can be speculatively
463   /// executed.
464   bool blockCanBePredicated(BasicBlock *BB);
465
466   /// Returns True, if 'Phi' is the kind of reduction variable for type
467   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
468   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
469   /// Returns true if the instruction I can be a reduction variable of type
470   /// 'Kind'.
471   bool isReductionInstr(Instruction *I, ReductionKind Kind);
472   /// Returns the induction kind of Phi. This function may return NoInduction
473   /// if the PHI is not an induction variable.
474   InductionKind isInductionVariable(PHINode *Phi);
475   /// Return true if can compute the address bounds of Ptr within the loop.
476   bool hasComputableBounds(Value *Ptr);
477
478   /// The loop that we evaluate.
479   Loop *TheLoop;
480   /// Scev analysis.
481   ScalarEvolution *SE;
482   /// DataLayout analysis.
483   DataLayout *DL;
484   // Dominators.
485   DominatorTree *DT;
486
487   //  ---  vectorization state --- //
488
489   /// Holds the integer induction variable. This is the counter of the
490   /// loop.
491   PHINode *Induction;
492   /// Holds the reduction variables.
493   ReductionList Reductions;
494   /// Holds all of the induction variables that we found in the loop.
495   /// Notice that inductions don't need to start at zero and that induction
496   /// variables can be pointers.
497   InductionList Inductions;
498
499   /// Allowed outside users. This holds the reduction
500   /// vars which can be accessed from outside the loop.
501   SmallPtrSet<Value*, 4> AllowedExit;
502   /// This set holds the variables which are known to be uniform after
503   /// vectorization.
504   SmallPtrSet<Instruction*, 4> Uniforms;
505   /// We need to check that all of the pointers in this list are disjoint
506   /// at runtime.
507   RuntimePointerCheck PtrRtCheck;
508 };
509
510 /// LoopVectorizationCostModel - estimates the expected speedups due to
511 /// vectorization.
512 /// In many cases vectorization is not profitable. This can happen because of
513 /// a number of reasons. In this class we mainly attempt to predict the
514 /// expected speedup/slowdowns due to the supported instruction set. We use the
515 /// TargetTransformInfo to query the different backends for the cost of
516 /// different operations.
517 class LoopVectorizationCostModel {
518 public:
519   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
520                              LoopVectorizationLegality *Legal,
521                              const TargetTransformInfo &TTI)
522       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
523
524   /// Information about vectorization costs
525   struct VectorizationFactor {
526     unsigned Width; // Vector width with best cost
527     unsigned Cost; // Cost of the loop with that width
528   };
529   /// \return The most profitable vectorization factor and the cost of that VF.
530   /// This method checks every power of two up to VF. If UserVF is not ZERO
531   /// then this vectorization factor will be selected if vectorization is
532   /// possible.
533   VectorizationFactor selectVectorizationFactor(bool OptForSize, unsigned UserVF);
534
535   /// \return The size (in bits) of the widest type in the code that
536   /// needs to be vectorized. We ignore values that remain scalar such as
537   /// 64 bit loop indices.
538   unsigned getWidestType();
539
540   /// \return The most profitable unroll factor.
541   /// If UserUF is non-zero then this method finds the best unroll-factor
542   /// based on register pressure and other parameters.
543   /// VF and LoopCost are the selected vectorization factor and the cost of the
544   /// selected VF.
545   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
546                               unsigned LoopCost);
547
548   /// \brief A struct that represents some properties of the register usage
549   /// of a loop.
550   struct RegisterUsage {
551     /// Holds the number of loop invariant values that are used in the loop.
552     unsigned LoopInvariantRegs;
553     /// Holds the maximum number of concurrent live intervals in the loop.
554     unsigned MaxLocalUsers;
555     /// Holds the number of instructions in the loop.
556     unsigned NumInstructions;
557   };
558
559   /// \return  information about the register usage of the loop.
560   RegisterUsage calculateRegisterUsage();
561
562 private:
563   /// Returns the expected execution cost. The unit of the cost does
564   /// not matter because we use the 'cost' units to compare different
565   /// vector widths. The cost that is returned is *not* normalized by
566   /// the factor width.
567   unsigned expectedCost(unsigned VF);
568
569   /// Returns the execution time cost of an instruction for a given vector
570   /// width. Vector width of one means scalar.
571   unsigned getInstructionCost(Instruction *I, unsigned VF);
572
573   /// A helper function for converting Scalar types to vector types.
574   /// If the incoming type is void, we return void. If the VF is 1, we return
575   /// the scalar type.
576   static Type* ToVectorTy(Type *Scalar, unsigned VF);
577
578   /// The loop that we evaluate.
579   Loop *TheLoop;
580   /// Scev analysis.
581   ScalarEvolution *SE;
582   /// Loop Info analysis.
583   LoopInfo *LI;
584   /// Vectorization legality.
585   LoopVectorizationLegality *Legal;
586   /// Vector target information.
587   const TargetTransformInfo &TTI;
588 };
589
590 /// The LoopVectorize Pass.
591 struct LoopVectorize : public LoopPass {
592   /// Pass identification, replacement for typeid
593   static char ID;
594
595   explicit LoopVectorize() : LoopPass(ID) {
596     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
597   }
598
599   ScalarEvolution *SE;
600   DataLayout *DL;
601   LoopInfo *LI;
602   TargetTransformInfo *TTI;
603   DominatorTree *DT;
604
605   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
606     // We only vectorize innermost loops.
607     if (!L->empty())
608       return false;
609
610     SE = &getAnalysis<ScalarEvolution>();
611     DL = getAnalysisIfAvailable<DataLayout>();
612     LI = &getAnalysis<LoopInfo>();
613     TTI = &getAnalysis<TargetTransformInfo>();
614     DT = &getAnalysis<DominatorTree>();
615
616     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
617           L->getHeader()->getParent()->getName() << "\"\n");
618
619     // Check if it is legal to vectorize the loop.
620     LoopVectorizationLegality LVL(L, SE, DL, DT);
621     if (!LVL.canVectorize()) {
622       DEBUG(dbgs() << "LV: Not vectorizing.\n");
623       return false;
624     }
625
626     // Use the cost model.
627     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
628
629     // Check the function attribues to find out if this function should be
630     // optimized for size.
631     Function *F = L->getHeader()->getParent();
632     Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
633     Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
634     unsigned FnIndex = AttributeSet::FunctionIndex;
635     bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
636     bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
637
638     if (NoFloat) {
639       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
640             "attribute is used.\n");
641       return false;
642     }
643
644     // Select the optimal vectorization factor.
645     LoopVectorizationCostModel::VectorizationFactor VF;
646     VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
647     // Select the unroll factor.
648     unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
649                                         VF.Width, VF.Cost);
650
651     if (VF.Width == 1) {
652       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
653       return false;
654     }
655
656     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
657           F->getParent()->getModuleIdentifier()<<"\n");
658     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
659
660     // If we decided that it is *legal* to vectorizer the loop then do it.
661     InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF);
662     LB.vectorize(&LVL);
663
664     DEBUG(verifyFunction(*L->getHeader()->getParent()));
665     return true;
666   }
667
668   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
669     LoopPass::getAnalysisUsage(AU);
670     AU.addRequiredID(LoopSimplifyID);
671     AU.addRequiredID(LCSSAID);
672     AU.addRequired<DominatorTree>();
673     AU.addRequired<LoopInfo>();
674     AU.addRequired<ScalarEvolution>();
675     AU.addRequired<TargetTransformInfo>();
676     AU.addPreserved<LoopInfo>();
677     AU.addPreserved<DominatorTree>();
678   }
679
680 };
681
682 } // end anonymous namespace
683
684 //===----------------------------------------------------------------------===//
685 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
686 // LoopVectorizationCostModel.
687 //===----------------------------------------------------------------------===//
688
689 void
690 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
691                                                        Loop *Lp, Value *Ptr) {
692   const SCEV *Sc = SE->getSCEV(Ptr);
693   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
694   assert(AR && "Invalid addrec expression");
695   const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
696   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
697   Pointers.push_back(Ptr);
698   Starts.push_back(AR->getStart());
699   Ends.push_back(ScEnd);
700 }
701
702 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
703   // Save the current insertion location.
704   Instruction *Loc = Builder.GetInsertPoint();
705
706   // We need to place the broadcast of invariant variables outside the loop.
707   Instruction *Instr = dyn_cast<Instruction>(V);
708   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
709   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
710
711   // Place the code for broadcasting invariant variables in the new preheader.
712   if (Invariant)
713     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
714
715   // Broadcast the scalar into all locations in the vector.
716   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
717
718   // Restore the builder insertion point.
719   if (Invariant)
720     Builder.SetInsertPoint(Loc);
721
722   return Shuf;
723 }
724
725 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
726                                                  bool Negate) {
727   assert(Val->getType()->isVectorTy() && "Must be a vector");
728   assert(Val->getType()->getScalarType()->isIntegerTy() &&
729          "Elem must be an integer");
730   // Create the types.
731   Type *ITy = Val->getType()->getScalarType();
732   VectorType *Ty = cast<VectorType>(Val->getType());
733   int VLen = Ty->getNumElements();
734   SmallVector<Constant*, 8> Indices;
735
736   // Create a vector of consecutive numbers from zero to VF.
737   for (int i = 0; i < VLen; ++i) {
738     int Idx = Negate ? (-i): i;
739     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
740   }
741
742   // Add the consecutive indices to the vector value.
743   Constant *Cv = ConstantVector::get(Indices);
744   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
745   return Builder.CreateAdd(Val, Cv, "induction");
746 }
747
748 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
749   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
750   // Make sure that the pointer does not point to structs.
751   if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
752     return 0;
753
754   // If this value is a pointer induction variable we know it is consecutive.
755   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
756   if (Phi && Inductions.count(Phi)) {
757     InductionInfo II = Inductions[Phi];
758     if (IK_PtrInduction == II.IK)
759       return 1;
760     else if (IK_ReversePtrInduction == II.IK)
761       return -1;
762   }
763
764   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
765   if (!Gep)
766     return 0;
767
768   unsigned NumOperands = Gep->getNumOperands();
769   Value *LastIndex = Gep->getOperand(NumOperands - 1);
770
771   Value *GpPtr = Gep->getPointerOperand();
772   // If this GEP value is a consecutive pointer induction variable and all of
773   // the indices are constant then we know it is consecutive. We can
774   Phi = dyn_cast<PHINode>(GpPtr);
775   if (Phi && Inductions.count(Phi)) {
776
777     // Make sure that the pointer does not point to structs.
778     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
779     if (GepPtrType->getElementType()->isAggregateType())
780       return 0;
781
782     // Make sure that all of the index operands are loop invariant.
783     for (unsigned i = 1; i < NumOperands; ++i)
784       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
785         return 0;
786
787     InductionInfo II = Inductions[Phi];
788     if (IK_PtrInduction == II.IK)
789       return 1;
790     else if (IK_ReversePtrInduction == II.IK)
791       return -1;
792   }
793
794   // Check that all of the gep indices are uniform except for the last.
795   for (unsigned i = 0; i < NumOperands - 1; ++i)
796     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
797       return 0;
798
799   // We can emit wide load/stores only if the last index is the induction
800   // variable.
801   const SCEV *Last = SE->getSCEV(LastIndex);
802   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
803     const SCEV *Step = AR->getStepRecurrence(*SE);
804
805     // The memory is consecutive because the last index is consecutive
806     // and all other indices are loop invariant.
807     if (Step->isOne())
808       return 1;
809     if (Step->isAllOnesValue())
810       return -1;
811   }
812
813   return 0;
814 }
815
816 bool LoopVectorizationLegality::isUniform(Value *V) {
817   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
818 }
819
820 InnerLoopVectorizer::VectorParts&
821 InnerLoopVectorizer::getVectorValue(Value *V) {
822   assert(V != Induction && "The new induction variable should not be used.");
823   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
824
825   // If we have this scalar in the map, return it.
826   if (WidenMap.has(V))
827     return WidenMap.get(V);
828
829   // If this scalar is unknown, assume that it is a constant or that it is
830   // loop invariant. Broadcast V and save the value for future uses.
831   Value *B = getBroadcastInstrs(V);
832   return WidenMap.splat(V, B);
833 }
834
835 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
836   assert(Vec->getType()->isVectorTy() && "Invalid type");
837   SmallVector<Constant*, 8> ShuffleMask;
838   for (unsigned i = 0; i < VF; ++i)
839     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
840
841   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
842                                      ConstantVector::get(ShuffleMask),
843                                      "reverse");
844 }
845
846
847 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
848                                              LoopVectorizationLegality *Legal) {
849   // Attempt to issue a wide load.
850   LoadInst *LI = dyn_cast<LoadInst>(Instr);
851   StoreInst *SI = dyn_cast<StoreInst>(Instr);
852
853   assert((LI || SI) && "Invalid Load/Store instruction");
854
855   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
856   Type *DataTy = VectorType::get(ScalarDataTy, VF);
857   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
858   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
859
860   // If the pointer is loop invariant or if it is non consecutive,
861   // scalarize the load.
862   int Stride = Legal->isConsecutivePtr(Ptr);
863   bool Reverse = Stride < 0;
864   bool UniformLoad = LI && Legal->isUniform(Ptr);
865   if (Stride == 0 || UniformLoad)
866     return scalarizeInstruction(Instr);
867
868   Constant *Zero = Builder.getInt32(0);
869   VectorParts &Entry = WidenMap.get(Instr);
870
871   // Handle consecutive loads/stores.
872   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
873   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
874     Value *PtrOperand = Gep->getPointerOperand();
875     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
876     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
877
878     // Create the new GEP with the new induction variable.
879     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
880     Gep2->setOperand(0, FirstBasePtr);
881     Gep2->setName("gep.indvar.base");
882     Ptr = Builder.Insert(Gep2);
883   } else if (Gep) {
884     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
885                                OrigLoop) && "Base ptr must be invariant");
886
887     // The last index does not have to be the induction. It can be
888     // consecutive and be a function of the index. For example A[I+1];
889     unsigned NumOperands = Gep->getNumOperands();
890
891     Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
892     VectorParts &GEPParts = getVectorValue(LastGepOperand);
893     Value *LastIndex = GEPParts[0];
894     LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
895
896     // Create the new GEP with the new induction variable.
897     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
898     Gep2->setOperand(NumOperands - 1, LastIndex);
899     Gep2->setName("gep.indvar.idx");
900     Ptr = Builder.Insert(Gep2);
901   } else {
902     // Use the induction element ptr.
903     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
904     VectorParts &PtrVal = getVectorValue(Ptr);
905     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
906   }
907
908   // Handle Stores:
909   if (SI) {
910     assert(!Legal->isUniform(SI->getPointerOperand()) &&
911            "We do not allow storing to uniform addresses");
912
913     VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
914     for (unsigned Part = 0; Part < UF; ++Part) {
915       // Calculate the pointer for the specific unroll-part.
916       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
917
918       if (Reverse) {
919         // If we store to reverse consecutive memory locations then we need
920         // to reverse the order of elements in the stored value.
921         StoredVal[Part] = reverseVector(StoredVal[Part]);
922         // If the address is consecutive but reversed, then the
923         // wide store needs to start at the last vector element.
924         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
925         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
926       }
927
928       Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
929       Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
930     }
931   }
932
933   for (unsigned Part = 0; Part < UF; ++Part) {
934     // Calculate the pointer for the specific unroll-part.
935     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
936
937     if (Reverse) {
938       // If the address is consecutive but reversed, then the
939       // wide store needs to start at the last vector element.
940       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
941       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
942     }
943
944     Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
945     Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
946     cast<LoadInst>(LI)->setAlignment(Alignment);
947     Entry[Part] = Reverse ? reverseVector(LI) :  LI;
948   }
949 }
950
951 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
952   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
953   // Holds vector parameters or scalars, in case of uniform vals.
954   SmallVector<VectorParts, 4> Params;
955
956   // Find all of the vectorized parameters.
957   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
958     Value *SrcOp = Instr->getOperand(op);
959
960     // If we are accessing the old induction variable, use the new one.
961     if (SrcOp == OldInduction) {
962       Params.push_back(getVectorValue(SrcOp));
963       continue;
964     }
965
966     // Try using previously calculated values.
967     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
968
969     // If the src is an instruction that appeared earlier in the basic block
970     // then it should already be vectorized.
971     if (SrcInst && OrigLoop->contains(SrcInst)) {
972       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
973       // The parameter is a vector value from earlier.
974       Params.push_back(WidenMap.get(SrcInst));
975     } else {
976       // The parameter is a scalar from outside the loop. Maybe even a constant.
977       VectorParts Scalars;
978       Scalars.append(UF, SrcOp);
979       Params.push_back(Scalars);
980     }
981   }
982
983   assert(Params.size() == Instr->getNumOperands() &&
984          "Invalid number of operands");
985
986   // Does this instruction return a value ?
987   bool IsVoidRetTy = Instr->getType()->isVoidTy();
988
989   Value *UndefVec = IsVoidRetTy ? 0 :
990     UndefValue::get(VectorType::get(Instr->getType(), VF));
991   // Create a new entry in the WidenMap and initialize it to Undef or Null.
992   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
993
994   // For each scalar that we create:
995   for (unsigned Width = 0; Width < VF; ++Width) {
996     // For each vector unroll 'part':
997     for (unsigned Part = 0; Part < UF; ++Part) {
998       Instruction *Cloned = Instr->clone();
999       if (!IsVoidRetTy)
1000         Cloned->setName(Instr->getName() + ".cloned");
1001       // Replace the operands of the cloned instrucions with extracted scalars.
1002       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1003         Value *Op = Params[op][Part];
1004         // Param is a vector. Need to extract the right lane.
1005         if (Op->getType()->isVectorTy())
1006           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1007         Cloned->setOperand(op, Op);
1008       }
1009
1010       // Place the cloned scalar in the new loop.
1011       Builder.Insert(Cloned);
1012
1013       // If the original scalar returns a value we need to place it in a vector
1014       // so that future users will be able to use it.
1015       if (!IsVoidRetTy)
1016         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1017                                                        Builder.getInt32(Width));
1018     }
1019   }
1020 }
1021
1022 Instruction *
1023 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1024                                      Instruction *Loc) {
1025   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1026   Legal->getRuntimePointerCheck();
1027
1028   if (!PtrRtCheck->Need)
1029     return NULL;
1030
1031   Instruction *MemoryRuntimeCheck = 0;
1032   unsigned NumPointers = PtrRtCheck->Pointers.size();
1033   SmallVector<Value* , 2> Starts;
1034   SmallVector<Value* , 2> Ends;
1035
1036   SCEVExpander Exp(*SE, "induction");
1037
1038   // Use this type for pointer arithmetic.
1039   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1040
1041   for (unsigned i = 0; i < NumPointers; ++i) {
1042     Value *Ptr = PtrRtCheck->Pointers[i];
1043     const SCEV *Sc = SE->getSCEV(Ptr);
1044
1045     if (SE->isLoopInvariant(Sc, OrigLoop)) {
1046       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1047             *Ptr <<"\n");
1048       Starts.push_back(Ptr);
1049       Ends.push_back(Ptr);
1050     } else {
1051       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1052
1053       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1054       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1055       Starts.push_back(Start);
1056       Ends.push_back(End);
1057     }
1058   }
1059
1060   IRBuilder<> ChkBuilder(Loc);
1061
1062   for (unsigned i = 0; i < NumPointers; ++i) {
1063     for (unsigned j = i+1; j < NumPointers; ++j) {
1064       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1065       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1066       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1067       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1068
1069       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1070       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1071       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1072       if (MemoryRuntimeCheck)
1073         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1074                                          "conflict.rdx");
1075
1076       MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1077     }
1078   }
1079
1080   return MemoryRuntimeCheck;
1081 }
1082
1083 void
1084 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1085   /*
1086    In this function we generate a new loop. The new loop will contain
1087    the vectorized instructions while the old loop will continue to run the
1088    scalar remainder.
1089
1090        [ ] <-- vector loop bypass (may consist of multiple blocks).
1091      /  |
1092     /   v
1093    |   [ ]     <-- vector pre header.
1094    |    |
1095    |    v
1096    |   [  ] \
1097    |   [  ]_|   <-- vector loop.
1098    |    |
1099     \   v
1100       >[ ]   <--- middle-block.
1101      /  |
1102     /   v
1103    |   [ ]     <--- new preheader.
1104    |    |
1105    |    v
1106    |   [ ] \
1107    |   [ ]_|   <-- old scalar loop to handle remainder.
1108     \   |
1109      \  v
1110       >[ ]     <-- exit block.
1111    ...
1112    */
1113
1114   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1115   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1116   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1117   assert(ExitBlock && "Must have an exit block");
1118
1119   // Some loops have a single integer induction variable, while other loops
1120   // don't. One example is c++ iterators that often have multiple pointer
1121   // induction variables. In the code below we also support a case where we
1122   // don't have a single induction variable.
1123   OldInduction = Legal->getInduction();
1124   Type *IdxTy = OldInduction ? OldInduction->getType() :
1125   DL->getIntPtrType(SE->getContext());
1126
1127   // Find the loop boundaries.
1128   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1129   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1130
1131   // Get the total trip count from the count by adding 1.
1132   ExitCount = SE->getAddExpr(ExitCount,
1133                              SE->getConstant(ExitCount->getType(), 1));
1134
1135   // Expand the trip count and place the new instructions in the preheader.
1136   // Notice that the pre-header does not change, only the loop body.
1137   SCEVExpander Exp(*SE, "induction");
1138
1139   // Count holds the overall loop count (N).
1140   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1141                                    BypassBlock->getTerminator());
1142
1143   // The loop index does not have to start at Zero. Find the original start
1144   // value from the induction PHI node. If we don't have an induction variable
1145   // then we know that it starts at zero.
1146   Value *StartIdx = OldInduction ?
1147   OldInduction->getIncomingValueForBlock(BypassBlock):
1148   ConstantInt::get(IdxTy, 0);
1149
1150   assert(BypassBlock && "Invalid loop structure");
1151   LoopBypassBlocks.push_back(BypassBlock);
1152
1153   // Split the single block loop into the two loop structure described above.
1154   BasicBlock *VectorPH =
1155   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1156   BasicBlock *VecBody =
1157   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1158   BasicBlock *MiddleBlock =
1159   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1160   BasicBlock *ScalarPH =
1161   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1162
1163   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1164   // inside the loop.
1165   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1166
1167   // Generate the induction variable.
1168   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1169   // The loop step is equal to the vectorization factor (num of SIMD elements)
1170   // times the unroll factor (num of SIMD instructions).
1171   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1172
1173   // This is the IR builder that we use to add all of the logic for bypassing
1174   // the new vector loop.
1175   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1176
1177   // We may need to extend the index in case there is a type mismatch.
1178   // We know that the count starts at zero and does not overflow.
1179   if (Count->getType() != IdxTy) {
1180     // The exit count can be of pointer type. Convert it to the correct
1181     // integer type.
1182     if (ExitCount->getType()->isPointerTy())
1183       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1184     else
1185       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1186   }
1187
1188   // Add the start index to the loop count to get the new end index.
1189   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1190
1191   // Now we need to generate the expression for N - (N % VF), which is
1192   // the part that the vectorized body will execute.
1193   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1194   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1195   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1196                                                      "end.idx.rnd.down");
1197
1198   // Now, compare the new count to zero. If it is zero skip the vector loop and
1199   // jump to the scalar loop.
1200   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1201                                           "cmp.zero");
1202
1203   BasicBlock *LastBypassBlock = BypassBlock;
1204
1205   // Generate the code that checks in runtime if arrays overlap. We put the
1206   // checks into a separate block to make the more common case of few elements
1207   // faster.
1208   Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1209                                                  BypassBlock->getTerminator());
1210   if (MemRuntimeCheck) {
1211     // Create a new block containing the memory check.
1212     BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1213                                                           "vector.memcheck");
1214     LoopBypassBlocks.push_back(CheckBlock);
1215
1216     // Replace the branch into the memory check block with a conditional branch
1217     // for the "few elements case".
1218     Instruction *OldTerm = BypassBlock->getTerminator();
1219     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1220     OldTerm->eraseFromParent();
1221
1222     Cmp = MemRuntimeCheck;
1223     LastBypassBlock = CheckBlock;
1224   }
1225
1226   LastBypassBlock->getTerminator()->eraseFromParent();
1227   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1228                      LastBypassBlock);
1229
1230   // We are going to resume the execution of the scalar loop.
1231   // Go over all of the induction variables that we found and fix the
1232   // PHIs that are left in the scalar version of the loop.
1233   // The starting values of PHI nodes depend on the counter of the last
1234   // iteration in the vectorized loop.
1235   // If we come from a bypass edge then we need to start from the original
1236   // start value.
1237
1238   // This variable saves the new starting index for the scalar loop.
1239   PHINode *ResumeIndex = 0;
1240   LoopVectorizationLegality::InductionList::iterator I, E;
1241   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1242   for (I = List->begin(), E = List->end(); I != E; ++I) {
1243     PHINode *OrigPhi = I->first;
1244     LoopVectorizationLegality::InductionInfo II = I->second;
1245     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1246                                          MiddleBlock->getTerminator());
1247     Value *EndValue = 0;
1248     switch (II.IK) {
1249     case LoopVectorizationLegality::IK_NoInduction:
1250       llvm_unreachable("Unknown induction");
1251     case LoopVectorizationLegality::IK_IntInduction: {
1252       // Handle the integer induction counter:
1253       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1254       assert(OrigPhi == OldInduction && "Unknown integer PHI");
1255       // We know what the end value is.
1256       EndValue = IdxEndRoundDown;
1257       // We also know which PHI node holds it.
1258       ResumeIndex = ResumeVal;
1259       break;
1260     }
1261     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1262       // Convert the CountRoundDown variable to the PHI size.
1263       unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1264       unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1265       Value *CRD = CountRoundDown;
1266       if (CRDSize > IISize)
1267         CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1268                                II.StartValue->getType(), "tr.crd",
1269                                LoopBypassBlocks.back()->getTerminator());
1270       else if (CRDSize < IISize)
1271         CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1272                                II.StartValue->getType(),
1273                                "sext.crd",
1274                                LoopBypassBlocks.back()->getTerminator());
1275       // Handle reverse integer induction counter:
1276       EndValue =
1277         BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1278                                   LoopBypassBlocks.back()->getTerminator());
1279       break;
1280     }
1281     case LoopVectorizationLegality::IK_PtrInduction: {
1282       // For pointer induction variables, calculate the offset using
1283       // the end index.
1284       EndValue =
1285         GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1286                                   LoopBypassBlocks.back()->getTerminator());
1287       break;
1288     }
1289     case LoopVectorizationLegality::IK_ReversePtrInduction: {
1290       // The value at the end of the loop for the reverse pointer is calculated
1291       // by creating a GEP with a negative index starting from the start value.
1292       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1293       Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1294                                   "rev.ind.end",
1295                                   LoopBypassBlocks.back()->getTerminator());
1296       EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1297                                   "rev.ptr.ind.end",
1298                                   LoopBypassBlocks.back()->getTerminator());
1299       break;
1300     }
1301     }// end of case
1302
1303     // The new PHI merges the original incoming value, in case of a bypass,
1304     // or the value at the end of the vectorized loop.
1305     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1306       ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1307     ResumeVal->addIncoming(EndValue, VecBody);
1308
1309     // Fix the scalar body counter (PHI node).
1310     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1311     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1312   }
1313
1314   // If we are generating a new induction variable then we also need to
1315   // generate the code that calculates the exit value. This value is not
1316   // simply the end of the counter because we may skip the vectorized body
1317   // in case of a runtime check.
1318   if (!OldInduction){
1319     assert(!ResumeIndex && "Unexpected resume value found");
1320     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1321                                   MiddleBlock->getTerminator());
1322     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1323       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1324     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1325   }
1326
1327   // Make sure that we found the index where scalar loop needs to continue.
1328   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1329          "Invalid resume Index");
1330
1331   // Add a check in the middle block to see if we have completed
1332   // all of the iterations in the first vector loop.
1333   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1334   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1335                                 ResumeIndex, "cmp.n",
1336                                 MiddleBlock->getTerminator());
1337
1338   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1339   // Remove the old terminator.
1340   MiddleBlock->getTerminator()->eraseFromParent();
1341
1342   // Create i+1 and fill the PHINode.
1343   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1344   Induction->addIncoming(StartIdx, VectorPH);
1345   Induction->addIncoming(NextIdx, VecBody);
1346   // Create the compare.
1347   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1348   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1349
1350   // Now we have two terminators. Remove the old one from the block.
1351   VecBody->getTerminator()->eraseFromParent();
1352
1353   // Get ready to start creating new instructions into the vectorized body.
1354   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1355
1356   // Create and register the new vector loop.
1357   Loop* Lp = new Loop();
1358   Loop *ParentLoop = OrigLoop->getParentLoop();
1359
1360   // Insert the new loop into the loop nest and register the new basic blocks.
1361   if (ParentLoop) {
1362     ParentLoop->addChildLoop(Lp);
1363     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1364       ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1365     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1366     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1367     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1368   } else {
1369     LI->addTopLevelLoop(Lp);
1370   }
1371
1372   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1373
1374   // Save the state.
1375   LoopVectorPreHeader = VectorPH;
1376   LoopScalarPreHeader = ScalarPH;
1377   LoopMiddleBlock = MiddleBlock;
1378   LoopExitBlock = ExitBlock;
1379   LoopVectorBody = VecBody;
1380   LoopScalarBody = OldBasicBlock;
1381 }
1382
1383 /// This function returns the identity element (or neutral element) for
1384 /// the operation K.
1385 static Constant*
1386 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1387   switch (K) {
1388   case LoopVectorizationLegality:: RK_IntegerXor:
1389   case LoopVectorizationLegality:: RK_IntegerAdd:
1390   case LoopVectorizationLegality:: RK_IntegerOr:
1391     // Adding, Xoring, Oring zero to a number does not change it.
1392     return ConstantInt::get(Tp, 0);
1393   case LoopVectorizationLegality:: RK_IntegerMult:
1394     // Multiplying a number by 1 does not change it.
1395     return ConstantInt::get(Tp, 1);
1396   case LoopVectorizationLegality:: RK_IntegerAnd:
1397     // AND-ing a number with an all-1 value does not change it.
1398     return ConstantInt::get(Tp, -1, true);
1399   case LoopVectorizationLegality:: RK_FloatMult:
1400     // Multiplying a number by 1 does not change it.
1401     return ConstantFP::get(Tp, 1.0L);
1402   case LoopVectorizationLegality:: RK_FloatAdd:
1403     // Adding zero to a number does not change it.
1404     return ConstantFP::get(Tp, 0.0L);
1405   default:
1406     llvm_unreachable("Unknown reduction kind");
1407   }
1408 }
1409
1410 static bool
1411 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1412   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1413   if (!II)
1414     return false;
1415   switch (II->getIntrinsicID()) {
1416   case Intrinsic::sqrt:
1417   case Intrinsic::sin:
1418   case Intrinsic::cos:
1419   case Intrinsic::exp:
1420   case Intrinsic::exp2:
1421   case Intrinsic::log:
1422   case Intrinsic::log10:
1423   case Intrinsic::log2:
1424   case Intrinsic::fabs:
1425   case Intrinsic::floor:
1426   case Intrinsic::ceil:
1427   case Intrinsic::trunc:
1428   case Intrinsic::rint:
1429   case Intrinsic::nearbyint:
1430   case Intrinsic::pow:
1431   case Intrinsic::fma:
1432   case Intrinsic::fmuladd:
1433     return true;
1434   default:
1435     return false;
1436   }
1437   return false;
1438 }
1439
1440 /// This function translates the reduction kind to an LLVM binary operator.
1441 static Instruction::BinaryOps
1442 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1443   switch (Kind) {
1444     case LoopVectorizationLegality::RK_IntegerAdd:
1445       return Instruction::Add;
1446     case LoopVectorizationLegality::RK_IntegerMult:
1447       return Instruction::Mul;
1448     case LoopVectorizationLegality::RK_IntegerOr:
1449       return Instruction::Or;
1450     case LoopVectorizationLegality::RK_IntegerAnd:
1451       return Instruction::And;
1452     case LoopVectorizationLegality::RK_IntegerXor:
1453       return Instruction::Xor;
1454     case LoopVectorizationLegality::RK_FloatMult:
1455       return Instruction::FMul;
1456     case LoopVectorizationLegality::RK_FloatAdd:
1457       return Instruction::FAdd;
1458     default:
1459       llvm_unreachable("Unknown reduction operation");
1460   }
1461 }
1462
1463 void
1464 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1465   //===------------------------------------------------===//
1466   //
1467   // Notice: any optimization or new instruction that go
1468   // into the code below should be also be implemented in
1469   // the cost-model.
1470   //
1471   //===------------------------------------------------===//
1472   Constant *Zero = Builder.getInt32(0);
1473
1474   // In order to support reduction variables we need to be able to vectorize
1475   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1476   // stages. First, we create a new vector PHI node with no incoming edges.
1477   // We use this value when we vectorize all of the instructions that use the
1478   // PHI. Next, after all of the instructions in the block are complete we
1479   // add the new incoming edges to the PHI. At this point all of the
1480   // instructions in the basic block are vectorized, so we can use them to
1481   // construct the PHI.
1482   PhiVector RdxPHIsToFix;
1483
1484   // Scan the loop in a topological order to ensure that defs are vectorized
1485   // before users.
1486   LoopBlocksDFS DFS(OrigLoop);
1487   DFS.perform(LI);
1488
1489   // Vectorize all of the blocks in the original loop.
1490   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1491        be = DFS.endRPO(); bb != be; ++bb)
1492     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1493
1494   // At this point every instruction in the original loop is widened to
1495   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1496   // that we vectorized. The PHI nodes are currently empty because we did
1497   // not want to introduce cycles. Notice that the remaining PHI nodes
1498   // that we need to fix are reduction variables.
1499
1500   // Create the 'reduced' values for each of the induction vars.
1501   // The reduced values are the vector values that we scalarize and combine
1502   // after the loop is finished.
1503   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1504        it != e; ++it) {
1505     PHINode *RdxPhi = *it;
1506     assert(RdxPhi && "Unable to recover vectorized PHI");
1507
1508     // Find the reduction variable descriptor.
1509     assert(Legal->getReductionVars()->count(RdxPhi) &&
1510            "Unable to find the reduction variable");
1511     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1512     (*Legal->getReductionVars())[RdxPhi];
1513
1514     // We need to generate a reduction vector from the incoming scalar.
1515     // To do so, we need to generate the 'identity' vector and overide
1516     // one of the elements with the incoming scalar reduction. We need
1517     // to do it in the vector-loop preheader.
1518     Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1519
1520     // This is the vector-clone of the value that leaves the loop.
1521     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1522     Type *VecTy = VectorExit[0]->getType();
1523
1524     // Find the reduction identity variable. Zero for addition, or, xor,
1525     // one for multiplication, -1 for And.
1526     Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1527     Constant *Identity = ConstantVector::getSplat(VF, Iden);
1528
1529     // This vector is the Identity vector where the first element is the
1530     // incoming scalar reduction.
1531     Value *VectorStart = Builder.CreateInsertElement(Identity,
1532                                                      RdxDesc.StartValue, Zero);
1533
1534     // Fix the vector-loop phi.
1535     // We created the induction variable so we know that the
1536     // preheader is the first entry.
1537     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1538
1539     // Reductions do not have to start at zero. They can start with
1540     // any loop invariant values.
1541     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1542     BasicBlock *Latch = OrigLoop->getLoopLatch();
1543     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1544     VectorParts &Val = getVectorValue(LoopVal);
1545     for (unsigned part = 0; part < UF; ++part) {
1546       // Make sure to add the reduction stat value only to the 
1547       // first unroll part.
1548       Value *StartVal = (part == 0) ? VectorStart : Identity;
1549       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1550       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1551     }
1552
1553     // Before each round, move the insertion point right between
1554     // the PHIs and the values we are going to write.
1555     // This allows us to write both PHINodes and the extractelement
1556     // instructions.
1557     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1558
1559     VectorParts RdxParts;
1560     for (unsigned part = 0; part < UF; ++part) {
1561       // This PHINode contains the vectorized reduction variable, or
1562       // the initial value vector, if we bypass the vector loop.
1563       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1564       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1565       Value *StartVal = (part == 0) ? VectorStart : Identity;
1566       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1567         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1568       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1569       RdxParts.push_back(NewPhi);
1570     }
1571
1572     // Reduce all of the unrolled parts into a single vector.
1573     Value *ReducedPartRdx = RdxParts[0];
1574     for (unsigned part = 1; part < UF; ++part) {
1575       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1576       ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1577                                            "bin.rdx");
1578     }
1579
1580     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1581     // and vector ops, reducing the set of values being computed by half each
1582     // round.
1583     assert(isPowerOf2_32(VF) &&
1584            "Reduction emission only supported for pow2 vectors!");
1585     Value *TmpVec = ReducedPartRdx;
1586     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1587     for (unsigned i = VF; i != 1; i >>= 1) {
1588       // Move the upper half of the vector to the lower half.
1589       for (unsigned j = 0; j != i/2; ++j)
1590         ShuffleMask[j] = Builder.getInt32(i/2 + j);
1591
1592       // Fill the rest of the mask with undef.
1593       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1594                 UndefValue::get(Builder.getInt32Ty()));
1595
1596       Value *Shuf =
1597         Builder.CreateShuffleVector(TmpVec,
1598                                     UndefValue::get(TmpVec->getType()),
1599                                     ConstantVector::get(ShuffleMask),
1600                                     "rdx.shuf");
1601
1602       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1603       TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1604     }
1605
1606     // The result is in the first element of the vector.
1607     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1608
1609     // Now, we need to fix the users of the reduction variable
1610     // inside and outside of the scalar remainder loop.
1611     // We know that the loop is in LCSSA form. We need to update the
1612     // PHI nodes in the exit blocks.
1613     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1614          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1615       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1616       if (!LCSSAPhi) continue;
1617
1618       // All PHINodes need to have a single entry edge, or two if
1619       // we already fixed them.
1620       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1621
1622       // We found our reduction value exit-PHI. Update it with the
1623       // incoming bypass edge.
1624       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1625         // Add an edge coming from the bypass.
1626         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1627         break;
1628       }
1629     }// end of the LCSSA phi scan.
1630
1631     // Fix the scalar loop reduction variable with the incoming reduction sum
1632     // from the vector body and from the backedge value.
1633     int IncomingEdgeBlockIdx =
1634     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1635     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1636     // Pick the other block.
1637     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1638     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1639     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1640   }// end of for each redux variable.
1641
1642   // The Loop exit block may have single value PHI nodes where the incoming
1643   // value is 'undef'. While vectorizing we only handled real values that
1644   // were defined inside the loop. Here we handle the 'undef case'.
1645   // See PR14725.
1646   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1647        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1648     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1649     if (!LCSSAPhi) continue;
1650     if (LCSSAPhi->getNumIncomingValues() == 1)
1651       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1652                             LoopMiddleBlock);
1653   }
1654 }
1655
1656 InnerLoopVectorizer::VectorParts
1657 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1658   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1659          "Invalid edge");
1660
1661   VectorParts SrcMask = createBlockInMask(Src);
1662
1663   // The terminator has to be a branch inst!
1664   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1665   assert(BI && "Unexpected terminator found");
1666
1667   if (BI->isConditional()) {
1668     VectorParts EdgeMask = getVectorValue(BI->getCondition());
1669
1670     if (BI->getSuccessor(0) != Dst)
1671       for (unsigned part = 0; part < UF; ++part)
1672         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1673
1674     for (unsigned part = 0; part < UF; ++part)
1675       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1676     return EdgeMask;
1677   }
1678
1679   return SrcMask;
1680 }
1681
1682 InnerLoopVectorizer::VectorParts
1683 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1684   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1685
1686   // Loop incoming mask is all-one.
1687   if (OrigLoop->getHeader() == BB) {
1688     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1689     return getVectorValue(C);
1690   }
1691
1692   // This is the block mask. We OR all incoming edges, and with zero.
1693   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1694   VectorParts BlockMask = getVectorValue(Zero);
1695
1696   // For each pred:
1697   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1698     VectorParts EM = createEdgeMask(*it, BB);
1699     for (unsigned part = 0; part < UF; ++part)
1700       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1701   }
1702
1703   return BlockMask;
1704 }
1705
1706 void
1707 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1708                                           BasicBlock *BB, PhiVector *PV) {
1709   // For each instruction in the old loop.
1710   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1711     VectorParts &Entry = WidenMap.get(it);
1712     switch (it->getOpcode()) {
1713     case Instruction::Br:
1714       // Nothing to do for PHIs and BR, since we already took care of the
1715       // loop control flow instructions.
1716       continue;
1717     case Instruction::PHI:{
1718       PHINode* P = cast<PHINode>(it);
1719       // Handle reduction variables:
1720       if (Legal->getReductionVars()->count(P)) {
1721         for (unsigned part = 0; part < UF; ++part) {
1722           // This is phase one of vectorizing PHIs.
1723           Type *VecTy = VectorType::get(it->getType(), VF);
1724           Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1725                                         LoopVectorBody-> getFirstInsertionPt());
1726         }
1727         PV->push_back(P);
1728         continue;
1729       }
1730
1731       // Check for PHI nodes that are lowered to vector selects.
1732       if (P->getParent() != OrigLoop->getHeader()) {
1733         // We know that all PHIs in non header blocks are converted into
1734         // selects, so we don't have to worry about the insertion order and we
1735         // can just use the builder.
1736
1737         // At this point we generate the predication tree. There may be
1738         // duplications since this is a simple recursive scan, but future
1739         // optimizations will clean it up.
1740         VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1741                                                P->getParent());
1742
1743         for (unsigned part = 0; part < UF; ++part) {
1744         VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1745         VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1746           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1747                                              "predphi");
1748         }
1749         continue;
1750       }
1751
1752       // This PHINode must be an induction variable.
1753       // Make sure that we know about it.
1754       assert(Legal->getInductionVars()->count(P) &&
1755              "Not an induction variable");
1756
1757       LoopVectorizationLegality::InductionInfo II =
1758         Legal->getInductionVars()->lookup(P);
1759
1760       switch (II.IK) {
1761       case LoopVectorizationLegality::IK_NoInduction:
1762         llvm_unreachable("Unknown induction");
1763       case LoopVectorizationLegality::IK_IntInduction: {
1764         assert(P == OldInduction && "Unexpected PHI");
1765         Value *Broadcasted = getBroadcastInstrs(Induction);
1766         // After broadcasting the induction variable we need to make the
1767         // vector consecutive by adding 0, 1, 2 ...
1768         for (unsigned part = 0; part < UF; ++part)
1769           Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1770         continue;
1771       }
1772       case LoopVectorizationLegality::IK_ReverseIntInduction:
1773       case LoopVectorizationLegality::IK_PtrInduction:
1774       case LoopVectorizationLegality::IK_ReversePtrInduction:
1775         // Handle reverse integer and pointer inductions.
1776         Value *StartIdx = 0;
1777         // If we have a single integer induction variable then use it.
1778         // Otherwise, start counting at zero.
1779         if (OldInduction) {
1780           LoopVectorizationLegality::InductionInfo OldII =
1781             Legal->getInductionVars()->lookup(OldInduction);
1782           StartIdx = OldII.StartValue;
1783         } else {
1784           StartIdx = ConstantInt::get(Induction->getType(), 0);
1785         }
1786         // This is the normalized GEP that starts counting at zero.
1787         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1788                                                  "normalized.idx");
1789
1790         // Handle the reverse integer induction variable case.
1791         if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1792           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1793           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1794                                                  "resize.norm.idx");
1795           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1796                                                  "reverse.idx");
1797
1798           // This is a new value so do not hoist it out.
1799           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1800           // After broadcasting the induction variable we need to make the
1801           // vector consecutive by adding  ... -3, -2, -1, 0.
1802           for (unsigned part = 0; part < UF; ++part)
1803             Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1804           continue;
1805         }
1806
1807         // Handle the pointer induction variable case.
1808         assert(P->getType()->isPointerTy() && "Unexpected type.");
1809
1810         // Is this a reverse induction ptr or a consecutive induction ptr.
1811         bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
1812                         II.IK);
1813
1814         // This is the vector of results. Notice that we don't generate
1815         // vector geps because scalar geps result in better code.
1816         for (unsigned part = 0; part < UF; ++part) {
1817           Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1818           for (unsigned int i = 0; i < VF; ++i) {
1819             int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
1820             Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
1821             Value *GlobalIdx;
1822             if (!Reverse)
1823               GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1824             else
1825               GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
1826
1827             Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1828                                                "next.gep");
1829             VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1830                                                  Builder.getInt32(i),
1831                                                  "insert.gep");
1832           }
1833           Entry[part] = VecVal;
1834         }
1835         continue;
1836       }
1837
1838     }// End of PHI.
1839
1840     case Instruction::Add:
1841     case Instruction::FAdd:
1842     case Instruction::Sub:
1843     case Instruction::FSub:
1844     case Instruction::Mul:
1845     case Instruction::FMul:
1846     case Instruction::UDiv:
1847     case Instruction::SDiv:
1848     case Instruction::FDiv:
1849     case Instruction::URem:
1850     case Instruction::SRem:
1851     case Instruction::FRem:
1852     case Instruction::Shl:
1853     case Instruction::LShr:
1854     case Instruction::AShr:
1855     case Instruction::And:
1856     case Instruction::Or:
1857     case Instruction::Xor: {
1858       // Just widen binops.
1859       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1860       VectorParts &A = getVectorValue(it->getOperand(0));
1861       VectorParts &B = getVectorValue(it->getOperand(1));
1862
1863       // Use this vector value for all users of the original instruction.
1864       for (unsigned Part = 0; Part < UF; ++Part) {
1865         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1866
1867         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1868         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1869         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1870           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1871           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1872         }
1873         if (VecOp && isa<PossiblyExactOperator>(VecOp))
1874           VecOp->setIsExact(BinOp->isExact());
1875
1876         Entry[Part] = V;
1877       }
1878       break;
1879     }
1880     case Instruction::Select: {
1881       // Widen selects.
1882       // If the selector is loop invariant we can create a select
1883       // instruction with a scalar condition. Otherwise, use vector-select.
1884       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1885                                                OrigLoop);
1886
1887       // The condition can be loop invariant  but still defined inside the
1888       // loop. This means that we can't just use the original 'cond' value.
1889       // We have to take the 'vectorized' value and pick the first lane.
1890       // Instcombine will make this a no-op.
1891       VectorParts &Cond = getVectorValue(it->getOperand(0));
1892       VectorParts &Op0  = getVectorValue(it->getOperand(1));
1893       VectorParts &Op1  = getVectorValue(it->getOperand(2));
1894       Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1895                                                        Builder.getInt32(0));
1896       for (unsigned Part = 0; Part < UF; ++Part) {
1897         Entry[Part] = Builder.CreateSelect(
1898           InvariantCond ? ScalarCond : Cond[Part],
1899           Op0[Part],
1900           Op1[Part]);
1901       }
1902       break;
1903     }
1904
1905     case Instruction::ICmp:
1906     case Instruction::FCmp: {
1907       // Widen compares. Generate vector compares.
1908       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1909       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1910       VectorParts &A = getVectorValue(it->getOperand(0));
1911       VectorParts &B = getVectorValue(it->getOperand(1));
1912       for (unsigned Part = 0; Part < UF; ++Part) {
1913         Value *C = 0;
1914         if (FCmp)
1915           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1916         else
1917           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1918         Entry[Part] = C;
1919       }
1920       break;
1921     }
1922
1923     case Instruction::Store:
1924     case Instruction::Load:
1925         vectorizeMemoryInstruction(it, Legal);
1926         break;
1927     case Instruction::ZExt:
1928     case Instruction::SExt:
1929     case Instruction::FPToUI:
1930     case Instruction::FPToSI:
1931     case Instruction::FPExt:
1932     case Instruction::PtrToInt:
1933     case Instruction::IntToPtr:
1934     case Instruction::SIToFP:
1935     case Instruction::UIToFP:
1936     case Instruction::Trunc:
1937     case Instruction::FPTrunc:
1938     case Instruction::BitCast: {
1939       CastInst *CI = dyn_cast<CastInst>(it);
1940       /// Optimize the special case where the source is the induction
1941       /// variable. Notice that we can only optimize the 'trunc' case
1942       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1943       /// c. other casts depend on pointer size.
1944       if (CI->getOperand(0) == OldInduction &&
1945           it->getOpcode() == Instruction::Trunc) {
1946         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1947                                                CI->getType());
1948         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1949         for (unsigned Part = 0; Part < UF; ++Part)
1950           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1951         break;
1952       }
1953       /// Vectorize casts.
1954       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1955
1956       VectorParts &A = getVectorValue(it->getOperand(0));
1957       for (unsigned Part = 0; Part < UF; ++Part)
1958         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1959       break;
1960     }
1961
1962     case Instruction::Call: {
1963       assert(isTriviallyVectorizableIntrinsic(it));
1964       Module *M = BB->getParent()->getParent();
1965       IntrinsicInst *II = cast<IntrinsicInst>(it);
1966       Intrinsic::ID ID = II->getIntrinsicID();
1967       for (unsigned Part = 0; Part < UF; ++Part) {
1968         SmallVector<Value*, 4> Args;
1969         for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1970           VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1971           Args.push_back(Arg[Part]);
1972         }
1973         Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1974         Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1975         Entry[Part] = Builder.CreateCall(F, Args);
1976       }
1977       break;
1978     }
1979
1980     default:
1981       // All other instructions are unsupported. Scalarize them.
1982       scalarizeInstruction(it);
1983       break;
1984     }// end of switch.
1985   }// end of for_each instr.
1986 }
1987
1988 void InnerLoopVectorizer::updateAnalysis() {
1989   // Forget the original basic block.
1990   SE->forgetLoop(OrigLoop);
1991
1992   // Update the dominator tree information.
1993   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
1994          "Entry does not dominate exit.");
1995
1996   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1997     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
1998   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
1999   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2000   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2001   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2002   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2003   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2004
2005   DEBUG(DT->verifyAnalysis());
2006 }
2007
2008 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2009   if (!EnableIfConversion)
2010     return false;
2011
2012   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2013   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2014
2015   // Collect the blocks that need predication.
2016   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2017     BasicBlock *BB = LoopBlocks[i];
2018
2019     // We don't support switch statements inside loops.
2020     if (!isa<BranchInst>(BB->getTerminator()))
2021       return false;
2022
2023     // We must have at most two predecessors because we need to convert
2024     // all PHIs to selects.
2025     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2026     if (Preds > 2)
2027       return false;
2028
2029     // We must be able to predicate all blocks that need to be predicated.
2030     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2031       return false;
2032   }
2033
2034   // We can if-convert this loop.
2035   return true;
2036 }
2037
2038 bool LoopVectorizationLegality::canVectorize() {
2039   assert(TheLoop->getLoopPreheader() && "No preheader!!");
2040
2041   // We can only vectorize innermost loops.
2042   if (TheLoop->getSubLoopsVector().size())
2043     return false;
2044
2045   // We must have a single backedge.
2046   if (TheLoop->getNumBackEdges() != 1)
2047     return false;
2048
2049   // We must have a single exiting block.
2050   if (!TheLoop->getExitingBlock())
2051     return false;
2052
2053   unsigned NumBlocks = TheLoop->getNumBlocks();
2054
2055   // Check if we can if-convert non single-bb loops.
2056   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2057     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2058     return false;
2059   }
2060
2061   // We need to have a loop header.
2062   BasicBlock *Latch = TheLoop->getLoopLatch();
2063   DEBUG(dbgs() << "LV: Found a loop: " <<
2064         TheLoop->getHeader()->getName() << "\n");
2065
2066   // ScalarEvolution needs to be able to find the exit count.
2067   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2068   if (ExitCount == SE->getCouldNotCompute()) {
2069     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2070     return false;
2071   }
2072
2073   // Do not loop-vectorize loops with a tiny trip count.
2074   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2075   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2076     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2077           "This loop is not worth vectorizing.\n");
2078     return false;
2079   }
2080
2081   // Check if we can vectorize the instructions and CFG in this loop.
2082   if (!canVectorizeInstrs()) {
2083     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2084     return false;
2085   }
2086
2087   // Go over each instruction and look at memory deps.
2088   if (!canVectorizeMemory()) {
2089     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2090     return false;
2091   }
2092
2093   // Collect all of the variables that remain uniform after vectorization.
2094   collectLoopUniforms();
2095
2096   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2097         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2098         <<"!\n");
2099
2100   // Okay! We can vectorize. At this point we don't have any other mem analysis
2101   // which may limit our maximum vectorization factor, so just return true with
2102   // no restrictions.
2103   return true;
2104 }
2105
2106 bool LoopVectorizationLegality::canVectorizeInstrs() {
2107   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2108   BasicBlock *Header = TheLoop->getHeader();
2109
2110   // For each block in the loop.
2111   for (Loop::block_iterator bb = TheLoop->block_begin(),
2112        be = TheLoop->block_end(); bb != be; ++bb) {
2113
2114     // Scan the instructions in the block and look for hazards.
2115     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2116          ++it) {
2117
2118       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2119         // This should not happen because the loop should be normalized.
2120         if (Phi->getNumIncomingValues() != 2) {
2121           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2122           return false;
2123         }
2124
2125         // Check that this PHI type is allowed.
2126         if (!Phi->getType()->isIntegerTy() &&
2127             !Phi->getType()->isFloatingPointTy() &&
2128             !Phi->getType()->isPointerTy()) {
2129           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2130           return false;
2131         }
2132
2133         // If this PHINode is not in the header block, then we know that we
2134         // can convert it to select during if-conversion. No need to check if
2135         // the PHIs in this block are induction or reduction variables.
2136         if (*bb != Header)
2137           continue;
2138
2139         // This is the value coming from the preheader.
2140         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2141         // Check if this is an induction variable.
2142         InductionKind IK = isInductionVariable(Phi);
2143
2144         if (IK_NoInduction != IK) {
2145           // Int inductions are special because we only allow one IV.
2146           if (IK == IK_IntInduction) {
2147             if (Induction) {
2148               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2149               return false;
2150             }
2151             Induction = Phi;
2152           }
2153
2154           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2155           Inductions[Phi] = InductionInfo(StartValue, IK);
2156           continue;
2157         }
2158
2159         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2160           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2161           continue;
2162         }
2163         if (AddReductionVar(Phi, RK_IntegerMult)) {
2164           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2165           continue;
2166         }
2167         if (AddReductionVar(Phi, RK_IntegerOr)) {
2168           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2169           continue;
2170         }
2171         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2172           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2173           continue;
2174         }
2175         if (AddReductionVar(Phi, RK_IntegerXor)) {
2176           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2177           continue;
2178         }
2179         if (AddReductionVar(Phi, RK_FloatMult)) {
2180           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2181           continue;
2182         }
2183         if (AddReductionVar(Phi, RK_FloatAdd)) {
2184           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2185           continue;
2186         }
2187
2188         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2189         return false;
2190       }// end of PHI handling
2191
2192       // We still don't handle functions.
2193       CallInst *CI = dyn_cast<CallInst>(it);
2194       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2195         DEBUG(dbgs() << "LV: Found a call site.\n");
2196         return false;
2197       }
2198
2199       // Check that the instruction return type is vectorizable.
2200       if (!VectorType::isValidElementType(it->getType()) &&
2201           !it->getType()->isVoidTy()) {
2202         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2203         return false;
2204       }
2205
2206       // Check that the stored type is vectorizable.
2207       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2208         Type *T = ST->getValueOperand()->getType();
2209         if (!VectorType::isValidElementType(T))
2210           return false;
2211       }
2212
2213       // Reduction instructions are allowed to have exit users.
2214       // All other instructions must not have external users.
2215       if (!AllowedExit.count(it))
2216         //Check that all of the users of the loop are inside the BB.
2217         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2218              I != E; ++I) {
2219           Instruction *U = cast<Instruction>(*I);
2220           // This user may be a reduction exit value.
2221           if (!TheLoop->contains(U)) {
2222             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2223             return false;
2224           }
2225         }
2226     } // next instr.
2227
2228   }
2229
2230   if (!Induction) {
2231     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2232     assert(getInductionVars()->size() && "No induction variables");
2233   }
2234
2235   return true;
2236 }
2237
2238 void LoopVectorizationLegality::collectLoopUniforms() {
2239   // We now know that the loop is vectorizable!
2240   // Collect variables that will remain uniform after vectorization.
2241   std::vector<Value*> Worklist;
2242   BasicBlock *Latch = TheLoop->getLoopLatch();
2243
2244   // Start with the conditional branch and walk up the block.
2245   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2246
2247   while (Worklist.size()) {
2248     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2249     Worklist.pop_back();
2250
2251     // Look at instructions inside this loop.
2252     // Stop when reaching PHI nodes.
2253     // TODO: we need to follow values all over the loop, not only in this block.
2254     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2255       continue;
2256
2257     // This is a known uniform.
2258     Uniforms.insert(I);
2259
2260     // Insert all operands.
2261     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2262       Worklist.push_back(I->getOperand(i));
2263     }
2264   }
2265 }
2266
2267 bool LoopVectorizationLegality::canVectorizeMemory() {
2268   typedef SmallVector<Value*, 16> ValueVector;
2269   typedef SmallPtrSet<Value*, 16> ValueSet;
2270   // Holds the Load and Store *instructions*.
2271   ValueVector Loads;
2272   ValueVector Stores;
2273   PtrRtCheck.Pointers.clear();
2274   PtrRtCheck.Need = false;
2275
2276   // For each block.
2277   for (Loop::block_iterator bb = TheLoop->block_begin(),
2278        be = TheLoop->block_end(); bb != be; ++bb) {
2279
2280     // Scan the BB and collect legal loads and stores.
2281     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2282          ++it) {
2283
2284       // If this is a load, save it. If this instruction can read from memory
2285       // but is not a load, then we quit. Notice that we don't handle function
2286       // calls that read or write.
2287       if (it->mayReadFromMemory()) {
2288         LoadInst *Ld = dyn_cast<LoadInst>(it);
2289         if (!Ld) return false;
2290         if (!Ld->isSimple()) {
2291           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2292           return false;
2293         }
2294         Loads.push_back(Ld);
2295         continue;
2296       }
2297
2298       // Save 'store' instructions. Abort if other instructions write to memory.
2299       if (it->mayWriteToMemory()) {
2300         StoreInst *St = dyn_cast<StoreInst>(it);
2301         if (!St) return false;
2302         if (!St->isSimple()) {
2303           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2304           return false;
2305         }
2306         Stores.push_back(St);
2307       }
2308     } // next instr.
2309   } // next block.
2310
2311   // Now we have two lists that hold the loads and the stores.
2312   // Next, we find the pointers that they use.
2313
2314   // Check if we see any stores. If there are no stores, then we don't
2315   // care if the pointers are *restrict*.
2316   if (!Stores.size()) {
2317     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2318     return true;
2319   }
2320
2321   // Holds the read and read-write *pointers* that we find.
2322   ValueVector Reads;
2323   ValueVector ReadWrites;
2324
2325   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2326   // multiple times on the same object. If the ptr is accessed twice, once
2327   // for read and once for write, it will only appear once (on the write
2328   // list). This is okay, since we are going to check for conflicts between
2329   // writes and between reads and writes, but not between reads and reads.
2330   ValueSet Seen;
2331
2332   ValueVector::iterator I, IE;
2333   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2334     StoreInst *ST = cast<StoreInst>(*I);
2335     Value* Ptr = ST->getPointerOperand();
2336
2337     if (isUniform(Ptr)) {
2338       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2339       return false;
2340     }
2341
2342     // If we did *not* see this pointer before, insert it to
2343     // the read-write list. At this phase it is only a 'write' list.
2344     if (Seen.insert(Ptr))
2345       ReadWrites.push_back(Ptr);
2346   }
2347
2348   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2349     LoadInst *LD = cast<LoadInst>(*I);
2350     Value* Ptr = LD->getPointerOperand();
2351     // If we did *not* see this pointer before, insert it to the
2352     // read list. If we *did* see it before, then it is already in
2353     // the read-write list. This allows us to vectorize expressions
2354     // such as A[i] += x;  Because the address of A[i] is a read-write
2355     // pointer. This only works if the index of A[i] is consecutive.
2356     // If the address of i is unknown (for example A[B[i]]) then we may
2357     // read a few words, modify, and write a few words, and some of the
2358     // words may be written to the same address.
2359     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2360       Reads.push_back(Ptr);
2361   }
2362
2363   // If we write (or read-write) to a single destination and there are no
2364   // other reads in this loop then is it safe to vectorize.
2365   if (ReadWrites.size() == 1 && Reads.size() == 0) {
2366     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2367     return true;
2368   }
2369
2370   // Find pointers with computable bounds. We are going to use this information
2371   // to place a runtime bound check.
2372   bool CanDoRT = true;
2373   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2374     if (hasComputableBounds(*I)) {
2375       PtrRtCheck.insert(SE, TheLoop, *I);
2376       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2377     } else {
2378       CanDoRT = false;
2379       break;
2380     }
2381   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2382     if (hasComputableBounds(*I)) {
2383       PtrRtCheck.insert(SE, TheLoop, *I);
2384       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2385     } else {
2386       CanDoRT = false;
2387       break;
2388     }
2389
2390   // Check that we did not collect too many pointers or found a
2391   // unsizeable pointer.
2392   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2393     PtrRtCheck.reset();
2394     CanDoRT = false;
2395   }
2396
2397   if (CanDoRT) {
2398     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2399   }
2400
2401   bool NeedRTCheck = false;
2402
2403   // Now that the pointers are in two lists (Reads and ReadWrites), we
2404   // can check that there are no conflicts between each of the writes and
2405   // between the writes to the reads.
2406   ValueSet WriteObjects;
2407   ValueVector TempObjects;
2408
2409   // Check that the read-writes do not conflict with other read-write
2410   // pointers.
2411   bool AllWritesIdentified = true;
2412   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2413     GetUnderlyingObjects(*I, TempObjects, DL);
2414     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2415          it != e; ++it) {
2416       if (!isIdentifiedObject(*it)) {
2417         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2418         NeedRTCheck = true;
2419         AllWritesIdentified = false;
2420       }
2421       if (!WriteObjects.insert(*it)) {
2422         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2423               << **it <<"\n");
2424         return false;
2425       }
2426     }
2427     TempObjects.clear();
2428   }
2429
2430   /// Check that the reads don't conflict with the read-writes.
2431   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2432     GetUnderlyingObjects(*I, TempObjects, DL);
2433     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2434          it != e; ++it) {
2435       // If all of the writes are identified then we don't care if the read
2436       // pointer is identified or not.
2437       if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2438         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2439         NeedRTCheck = true;
2440       }
2441       if (WriteObjects.count(*it)) {
2442         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2443               << **it <<"\n");
2444         return false;
2445       }
2446     }
2447     TempObjects.clear();
2448   }
2449
2450   PtrRtCheck.Need = NeedRTCheck;
2451   if (NeedRTCheck && !CanDoRT) {
2452     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2453           "the array bounds.\n");
2454     PtrRtCheck.reset();
2455     return false;
2456   }
2457
2458   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2459         " need a runtime memory check.\n");
2460   return true;
2461 }
2462
2463 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2464                                                 ReductionKind Kind) {
2465   if (Phi->getNumIncomingValues() != 2)
2466     return false;
2467
2468   // Reduction variables are only found in the loop header block.
2469   if (Phi->getParent() != TheLoop->getHeader())
2470     return false;
2471
2472   // Obtain the reduction start value from the value that comes from the loop
2473   // preheader.
2474   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2475
2476   // ExitInstruction is the single value which is used outside the loop.
2477   // We only allow for a single reduction value to be used outside the loop.
2478   // This includes users of the reduction, variables (which form a cycle
2479   // which ends in the phi node).
2480   Instruction *ExitInstruction = 0;
2481   // Indicates that we found a binary operation in our scan.
2482   bool FoundBinOp = false;
2483
2484   // Iter is our iterator. We start with the PHI node and scan for all of the
2485   // users of this instruction. All users must be instructions that can be
2486   // used as reduction variables (such as ADD). We may have a single
2487   // out-of-block user. The cycle must end with the original PHI.
2488   Instruction *Iter = Phi;
2489   while (true) {
2490     // If the instruction has no users then this is a broken
2491     // chain and can't be a reduction variable.
2492     if (Iter->use_empty())
2493       return false;
2494
2495     // Did we find a user inside this loop already ?
2496     bool FoundInBlockUser = false;
2497     // Did we reach the initial PHI node already ?
2498     bool FoundStartPHI = false;
2499
2500     // Is this a bin op ?
2501     FoundBinOp |= !isa<PHINode>(Iter);
2502
2503     // For each of the *users* of iter.
2504     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2505          it != e; ++it) {
2506       Instruction *U = cast<Instruction>(*it);
2507       // We already know that the PHI is a user.
2508       if (U == Phi) {
2509         FoundStartPHI = true;
2510         continue;
2511       }
2512
2513       // Check if we found the exit user.
2514       BasicBlock *Parent = U->getParent();
2515       if (!TheLoop->contains(Parent)) {
2516         // Exit if you find multiple outside users.
2517         if (ExitInstruction != 0)
2518           return false;
2519         ExitInstruction = Iter;
2520       }
2521
2522       // We allow in-loop PHINodes which are not the original reduction PHI
2523       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2524       // structure) then don't skip this PHI.
2525       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2526           U->getParent() != TheLoop->getHeader() &&
2527           TheLoop->contains(U) &&
2528           Iter->getNumUses() > 1)
2529         continue;
2530
2531       // We can't have multiple inside users.
2532       if (FoundInBlockUser)
2533         return false;
2534       FoundInBlockUser = true;
2535
2536       // Any reduction instr must be of one of the allowed kinds.
2537       if (!isReductionInstr(U, Kind))
2538         return false;
2539
2540       // Reductions of instructions such as Div, and Sub is only
2541       // possible if the LHS is the reduction variable.
2542       if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2543         return false;
2544
2545       Iter = U;
2546     }
2547
2548     // We found a reduction var if we have reached the original
2549     // phi node and we only have a single instruction with out-of-loop
2550     // users.
2551     if (FoundStartPHI) {
2552       // This instruction is allowed to have out-of-loop users.
2553       AllowedExit.insert(ExitInstruction);
2554
2555       // Save the description of this reduction variable.
2556       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2557       Reductions[Phi] = RD;
2558       // We've ended the cycle. This is a reduction variable if we have an
2559       // outside user and it has a binary op.
2560       return FoundBinOp && ExitInstruction;
2561     }
2562   }
2563 }
2564
2565 bool
2566 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2567                                             ReductionKind Kind) {
2568   bool FP = I->getType()->isFloatingPointTy();
2569   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2570
2571   switch (I->getOpcode()) {
2572   default:
2573     return false;
2574   case Instruction::PHI:
2575       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2576         return false;
2577     // possibly.
2578     return true;
2579   case Instruction::Sub:
2580   case Instruction::Add:
2581     return Kind == RK_IntegerAdd;
2582   case Instruction::SDiv:
2583   case Instruction::UDiv:
2584   case Instruction::Mul:
2585     return Kind == RK_IntegerMult;
2586   case Instruction::And:
2587     return Kind == RK_IntegerAnd;
2588   case Instruction::Or:
2589     return Kind == RK_IntegerOr;
2590   case Instruction::Xor:
2591     return Kind == RK_IntegerXor;
2592   case Instruction::FMul:
2593     return Kind == RK_FloatMult && FastMath;
2594   case Instruction::FAdd:
2595     return Kind == RK_FloatAdd && FastMath;
2596    }
2597 }
2598
2599 LoopVectorizationLegality::InductionKind
2600 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2601   Type *PhiTy = Phi->getType();
2602   // We only handle integer and pointer inductions variables.
2603   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2604     return IK_NoInduction;
2605
2606   // Check that the PHI is consecutive.
2607   const SCEV *PhiScev = SE->getSCEV(Phi);
2608   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2609   if (!AR) {
2610     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2611     return IK_NoInduction;
2612   }
2613   const SCEV *Step = AR->getStepRecurrence(*SE);
2614
2615   // Integer inductions need to have a stride of one.
2616   if (PhiTy->isIntegerTy()) {
2617     if (Step->isOne())
2618       return IK_IntInduction;
2619     if (Step->isAllOnesValue())
2620       return IK_ReverseIntInduction;
2621     return IK_NoInduction;
2622   }
2623
2624   // Calculate the pointer stride and check if it is consecutive.
2625   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2626   if (!C)
2627     return IK_NoInduction;
2628
2629   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2630   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2631   if (C->getValue()->equalsInt(Size))
2632     return IK_PtrInduction;
2633   else if (C->getValue()->equalsInt(0 - Size))
2634     return IK_ReversePtrInduction;
2635
2636   return IK_NoInduction;
2637 }
2638
2639 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2640   Value *In0 = const_cast<Value*>(V);
2641   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2642   if (!PN)
2643     return false;
2644
2645   return Inductions.count(PN);
2646 }
2647
2648 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2649   assert(TheLoop->contains(BB) && "Unknown block used");
2650
2651   // Blocks that do not dominate the latch need predication.
2652   BasicBlock* Latch = TheLoop->getLoopLatch();
2653   return !DT->dominates(BB, Latch);
2654 }
2655
2656 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2657   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2658     // We don't predicate loads/stores at the moment.
2659     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2660       return false;
2661
2662     // The instructions below can trap.
2663     switch (it->getOpcode()) {
2664     default: continue;
2665     case Instruction::UDiv:
2666     case Instruction::SDiv:
2667     case Instruction::URem:
2668     case Instruction::SRem:
2669              return false;
2670     }
2671   }
2672
2673   return true;
2674 }
2675
2676 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2677   const SCEV *PhiScev = SE->getSCEV(Ptr);
2678   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2679   if (!AR)
2680     return false;
2681
2682   return AR->isAffine();
2683 }
2684
2685 LoopVectorizationCostModel::VectorizationFactor
2686 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2687                                                       unsigned UserVF) {
2688   // Width 1 means no vectorize
2689   VectorizationFactor Factor = { 1U, 0U };
2690   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2691     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2692     return Factor;
2693   }
2694
2695   // Find the trip count.
2696   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2697   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2698
2699   unsigned WidestType = getWidestType();
2700   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2701   unsigned MaxVectorSize = WidestRegister / WidestType;
2702   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2703   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2704
2705   if (MaxVectorSize == 0) {
2706     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2707     MaxVectorSize = 1;
2708   }
2709
2710   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2711          " into one vector!");
2712
2713   unsigned VF = MaxVectorSize;
2714
2715   // If we optimize the program for size, avoid creating the tail loop.
2716   if (OptForSize) {
2717     // If we are unable to calculate the trip count then don't try to vectorize.
2718     if (TC < 2) {
2719       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2720       return Factor;
2721     }
2722
2723     // Find the maximum SIMD width that can fit within the trip count.
2724     VF = TC % MaxVectorSize;
2725
2726     if (VF == 0)
2727       VF = MaxVectorSize;
2728
2729     // If the trip count that we found modulo the vectorization factor is not
2730     // zero then we require a tail.
2731     if (VF < 2) {
2732       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2733       return Factor;
2734     }
2735   }
2736
2737   if (UserVF != 0) {
2738     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2739     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2740
2741     Factor.Width = UserVF;
2742     return Factor;
2743   }
2744
2745   float Cost = expectedCost(1);
2746   unsigned Width = 1;
2747   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2748   for (unsigned i=2; i <= VF; i*=2) {
2749     // Notice that the vector loop needs to be executed less times, so
2750     // we need to divide the cost of the vector loops by the width of
2751     // the vector elements.
2752     float VectorCost = expectedCost(i) / (float)i;
2753     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2754           (int)VectorCost << ".\n");
2755     if (VectorCost < Cost) {
2756       Cost = VectorCost;
2757       Width = i;
2758     }
2759   }
2760
2761   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2762   Factor.Width = Width;
2763   Factor.Cost = Width * Cost;
2764   return Factor;
2765 }
2766
2767 unsigned LoopVectorizationCostModel::getWidestType() {
2768   unsigned MaxWidth = 8;
2769
2770   // For each block.
2771   for (Loop::block_iterator bb = TheLoop->block_begin(),
2772        be = TheLoop->block_end(); bb != be; ++bb) {
2773     BasicBlock *BB = *bb;
2774
2775     // For each instruction in the loop.
2776     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2777       Type *T = it->getType();
2778
2779       // Only examine Loads, Stores and PHINodes.
2780       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2781         continue;
2782
2783       // Examine PHI nodes that are reduction variables.
2784       if (PHINode *PN = dyn_cast<PHINode>(it))
2785         if (!Legal->getReductionVars()->count(PN))
2786           continue;
2787
2788       // Examine the stored values.
2789       if (StoreInst *ST = dyn_cast<StoreInst>(it))
2790         T = ST->getValueOperand()->getType();
2791
2792       // Ignore stored/loaded pointer types.
2793       if (T->isPointerTy())
2794         continue;
2795
2796       MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2797     }
2798   }
2799
2800   return MaxWidth;
2801 }
2802
2803 unsigned
2804 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2805                                                unsigned UserUF,
2806                                                unsigned VF,
2807                                                unsigned LoopCost) {
2808
2809   // -- The unroll heuristics --
2810   // We unroll the loop in order to expose ILP and reduce the loop overhead.
2811   // There are many micro-architectural considerations that we can't predict
2812   // at this level. For example frontend pressure (on decode or fetch) due to
2813   // code size, or the number and capabilities of the execution ports.
2814   //
2815   // We use the following heuristics to select the unroll factor:
2816   // 1. If the code has reductions the we unroll in order to break the cross
2817   // iteration dependency.
2818   // 2. If the loop is really small then we unroll in order to reduce the loop
2819   // overhead.
2820   // 3. We don't unroll if we think that we will spill registers to memory due
2821   // to the increased register pressure.
2822
2823   // Use the user preference, unless 'auto' is selected.
2824   if (UserUF != 0)
2825     return UserUF;
2826
2827   // When we optimize for size we don't unroll.
2828   if (OptForSize)
2829     return 1;
2830
2831   // Do not unroll loops with a relatively small trip count.
2832   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2833                                               TheLoop->getLoopLatch());
2834   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2835     return 1;
2836
2837   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2838   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2839         " vector registers\n");
2840
2841   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2842   // We divide by these constants so assume that we have at least one
2843   // instruction that uses at least one register.
2844   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2845   R.NumInstructions = std::max(R.NumInstructions, 1U);
2846
2847   // We calculate the unroll factor using the following formula.
2848   // Subtract the number of loop invariants from the number of available
2849   // registers. These registers are used by all of the unrolled instances.
2850   // Next, divide the remaining registers by the number of registers that is
2851   // required by the loop, in order to estimate how many parallel instances
2852   // fit without causing spills.
2853   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2854
2855   // Clamp the unroll factor ranges to reasonable factors.
2856   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2857
2858   // If we did not calculate the cost for VF (because the user selected the VF)
2859   // then we calculate the cost of VF here.
2860   if (LoopCost == 0)
2861     LoopCost = expectedCost(VF);
2862
2863   // Clamp the calculated UF to be between the 1 and the max unroll factor
2864   // that the target allows.
2865   if (UF > MaxUnrollSize)
2866     UF = MaxUnrollSize;
2867   else if (UF < 1)
2868     UF = 1;
2869
2870   if (Legal->getReductionVars()->size()) {
2871     DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
2872     return UF;
2873   }
2874
2875   // We want to unroll tiny loops in order to reduce the loop overhead.
2876   // We assume that the cost overhead is 1 and we use the cost model
2877   // to estimate the cost of the loop and unroll until the cost of the
2878   // loop overhead is about 5% of the cost of the loop.
2879   DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
2880   if (LoopCost < 20) {
2881     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
2882     unsigned NewUF = 20/LoopCost + 1;
2883     return std::min(NewUF, UF);
2884   }
2885
2886   DEBUG(dbgs() << "LV: Not Unrolling. \n");
2887   return 1;
2888 }
2889
2890 LoopVectorizationCostModel::RegisterUsage
2891 LoopVectorizationCostModel::calculateRegisterUsage() {
2892   // This function calculates the register usage by measuring the highest number
2893   // of values that are alive at a single location. Obviously, this is a very
2894   // rough estimation. We scan the loop in a topological order in order and
2895   // assign a number to each instruction. We use RPO to ensure that defs are
2896   // met before their users. We assume that each instruction that has in-loop
2897   // users starts an interval. We record every time that an in-loop value is
2898   // used, so we have a list of the first and last occurrences of each
2899   // instruction. Next, we transpose this data structure into a multi map that
2900   // holds the list of intervals that *end* at a specific location. This multi
2901   // map allows us to perform a linear search. We scan the instructions linearly
2902   // and record each time that a new interval starts, by placing it in a set.
2903   // If we find this value in the multi-map then we remove it from the set.
2904   // The max register usage is the maximum size of the set.
2905   // We also search for instructions that are defined outside the loop, but are
2906   // used inside the loop. We need this number separately from the max-interval
2907   // usage number because when we unroll, loop-invariant values do not take
2908   // more register.
2909   LoopBlocksDFS DFS(TheLoop);
2910   DFS.perform(LI);
2911
2912   RegisterUsage R;
2913   R.NumInstructions = 0;
2914
2915   // Each 'key' in the map opens a new interval. The values
2916   // of the map are the index of the 'last seen' usage of the
2917   // instruction that is the key.
2918   typedef DenseMap<Instruction*, unsigned> IntervalMap;
2919   // Maps instruction to its index.
2920   DenseMap<unsigned, Instruction*> IdxToInstr;
2921   // Marks the end of each interval.
2922   IntervalMap EndPoint;
2923   // Saves the list of instruction indices that are used in the loop.
2924   SmallSet<Instruction*, 8> Ends;
2925   // Saves the list of values that are used in the loop but are
2926   // defined outside the loop, such as arguments and constants.
2927   SmallPtrSet<Value*, 8> LoopInvariants;
2928
2929   unsigned Index = 0;
2930   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2931        be = DFS.endRPO(); bb != be; ++bb) {
2932     R.NumInstructions += (*bb)->size();
2933     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2934          ++it) {
2935       Instruction *I = it;
2936       IdxToInstr[Index++] = I;
2937
2938       // Save the end location of each USE.
2939       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2940         Value *U = I->getOperand(i);
2941         Instruction *Instr = dyn_cast<Instruction>(U);
2942
2943         // Ignore non-instruction values such as arguments, constants, etc.
2944         if (!Instr) continue;
2945
2946         // If this instruction is outside the loop then record it and continue.
2947         if (!TheLoop->contains(Instr)) {
2948           LoopInvariants.insert(Instr);
2949           continue;
2950         }
2951
2952         // Overwrite previous end points.
2953         EndPoint[Instr] = Index;
2954         Ends.insert(Instr);
2955       }
2956     }
2957   }
2958
2959   // Saves the list of intervals that end with the index in 'key'.
2960   typedef SmallVector<Instruction*, 2> InstrList;
2961   DenseMap<unsigned, InstrList> TransposeEnds;
2962
2963   // Transpose the EndPoints to a list of values that end at each index.
2964   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2965        it != e; ++it)
2966     TransposeEnds[it->second].push_back(it->first);
2967
2968   SmallSet<Instruction*, 8> OpenIntervals;
2969   unsigned MaxUsage = 0;
2970
2971
2972   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2973   for (unsigned int i = 0; i < Index; ++i) {
2974     Instruction *I = IdxToInstr[i];
2975     // Ignore instructions that are never used within the loop.
2976     if (!Ends.count(I)) continue;
2977
2978     // Remove all of the instructions that end at this location.
2979     InstrList &List = TransposeEnds[i];
2980     for (unsigned int j=0, e = List.size(); j < e; ++j)
2981       OpenIntervals.erase(List[j]);
2982
2983     // Count the number of live interals.
2984     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2985
2986     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2987           OpenIntervals.size() <<"\n");
2988
2989     // Add the current instruction to the list of open intervals.
2990     OpenIntervals.insert(I);
2991   }
2992
2993   unsigned Invariant = LoopInvariants.size();
2994   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2995   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2996   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2997
2998   R.LoopInvariantRegs = Invariant;
2999   R.MaxLocalUsers = MaxUsage;
3000   return R;
3001 }
3002
3003 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3004   unsigned Cost = 0;
3005
3006   // For each block.
3007   for (Loop::block_iterator bb = TheLoop->block_begin(),
3008        be = TheLoop->block_end(); bb != be; ++bb) {
3009     unsigned BlockCost = 0;
3010     BasicBlock *BB = *bb;
3011
3012     // For each instruction in the old loop.
3013     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3014       unsigned C = getInstructionCost(it, VF);
3015       Cost += C;
3016       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3017             VF << " For instruction: "<< *it << "\n");
3018     }
3019
3020     // We assume that if-converted blocks have a 50% chance of being executed.
3021     // When the code is scalar then some of the blocks are avoided due to CF.
3022     // When the code is vectorized we execute all code paths.
3023     if (Legal->blockNeedsPredication(*bb) && VF == 1)
3024       BlockCost /= 2;
3025
3026     Cost += BlockCost;
3027   }
3028
3029   return Cost;
3030 }
3031
3032 unsigned
3033 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3034   // If we know that this instruction will remain uniform, check the cost of
3035   // the scalar version.
3036   if (Legal->isUniformAfterVectorization(I))
3037     VF = 1;
3038
3039   Type *RetTy = I->getType();
3040   Type *VectorTy = ToVectorTy(RetTy, VF);
3041
3042   // TODO: We need to estimate the cost of intrinsic calls.
3043   switch (I->getOpcode()) {
3044   case Instruction::GetElementPtr:
3045     // We mark this instruction as zero-cost because scalar GEPs are usually
3046     // lowered to the intruction addressing mode. At the moment we don't
3047     // generate vector geps.
3048     return 0;
3049   case Instruction::Br: {
3050     return TTI.getCFInstrCost(I->getOpcode());
3051   }
3052   case Instruction::PHI:
3053     //TODO: IF-converted IFs become selects.
3054     return 0;
3055   case Instruction::Add:
3056   case Instruction::FAdd:
3057   case Instruction::Sub:
3058   case Instruction::FSub:
3059   case Instruction::Mul:
3060   case Instruction::FMul:
3061   case Instruction::UDiv:
3062   case Instruction::SDiv:
3063   case Instruction::FDiv:
3064   case Instruction::URem:
3065   case Instruction::SRem:
3066   case Instruction::FRem:
3067   case Instruction::Shl:
3068   case Instruction::LShr:
3069   case Instruction::AShr:
3070   case Instruction::And:
3071   case Instruction::Or:
3072   case Instruction::Xor:
3073     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3074   case Instruction::Select: {
3075     SelectInst *SI = cast<SelectInst>(I);
3076     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3077     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3078     Type *CondTy = SI->getCondition()->getType();
3079     if (ScalarCond)
3080       CondTy = VectorType::get(CondTy, VF);
3081
3082     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3083   }
3084   case Instruction::ICmp:
3085   case Instruction::FCmp: {
3086     Type *ValTy = I->getOperand(0)->getType();
3087     VectorTy = ToVectorTy(ValTy, VF);
3088     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3089   }
3090   case Instruction::Store: {
3091     StoreInst *SI = cast<StoreInst>(I);
3092     Type *ValTy = SI->getValueOperand()->getType();
3093     VectorTy = ToVectorTy(ValTy, VF);
3094
3095     if (VF == 1)
3096       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3097                                    SI->getAlignment(),
3098                                    SI->getPointerAddressSpace());
3099
3100     // Scalarized stores.
3101     int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
3102     bool Reverse = Stride < 0;
3103     if (0 == Stride) {
3104       unsigned Cost = 0;
3105
3106       // The cost of extracting from the value vector and pointer vector.
3107       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3108       for (unsigned i = 0; i < VF; ++i) {
3109         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
3110                                        i);
3111         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3112       }
3113
3114       // The cost of the scalar stores.
3115       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3116                                        SI->getAlignment(),
3117                                        SI->getPointerAddressSpace());
3118       return Cost;
3119     }
3120
3121     // Wide stores.
3122     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3123                                         SI->getAlignment(),
3124                                         SI->getPointerAddressSpace());
3125     if (Reverse)
3126       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3127                                   VectorTy, 0);
3128     return Cost;
3129   }
3130   case Instruction::Load: {
3131     LoadInst *LI = cast<LoadInst>(I);
3132
3133     if (VF == 1)
3134       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3135                                  LI->getPointerAddressSpace());
3136
3137     // Scalarized loads.
3138     int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3139     bool Reverse = Stride < 0;
3140     if (0 == Stride) {
3141       unsigned Cost = 0;
3142       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3143
3144       // The cost of extracting from the pointer vector.
3145       for (unsigned i = 0; i < VF; ++i)
3146         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3147
3148       // The cost of inserting data to the result vector.
3149       for (unsigned i = 0; i < VF; ++i)
3150         Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3151
3152       // The cost of the scalar stores.
3153       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3154                                        LI->getAlignment(),
3155                                        LI->getPointerAddressSpace());
3156       return Cost;
3157     }
3158
3159     // Wide loads.
3160     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3161                                         LI->getAlignment(),
3162                                         LI->getPointerAddressSpace());
3163     if (Reverse)
3164       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3165     return Cost;
3166   }
3167   case Instruction::ZExt:
3168   case Instruction::SExt:
3169   case Instruction::FPToUI:
3170   case Instruction::FPToSI:
3171   case Instruction::FPExt:
3172   case Instruction::PtrToInt:
3173   case Instruction::IntToPtr:
3174   case Instruction::SIToFP:
3175   case Instruction::UIToFP:
3176   case Instruction::Trunc:
3177   case Instruction::FPTrunc:
3178   case Instruction::BitCast: {
3179     // We optimize the truncation of induction variable.
3180     // The cost of these is the same as the scalar operation.
3181     if (I->getOpcode() == Instruction::Trunc &&
3182         Legal->isInductionVariable(I->getOperand(0)))
3183       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3184                                   I->getOperand(0)->getType());
3185
3186     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3187     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3188   }
3189   case Instruction::Call: {
3190     assert(isTriviallyVectorizableIntrinsic(I));
3191     IntrinsicInst *II = cast<IntrinsicInst>(I);
3192     Type *RetTy = ToVectorTy(II->getType(), VF);
3193     SmallVector<Type*, 4> Tys;
3194     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3195       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3196     return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3197   }
3198   default: {
3199     // We are scalarizing the instruction. Return the cost of the scalar
3200     // instruction, plus the cost of insert and extract into vector
3201     // elements, times the vector width.
3202     unsigned Cost = 0;
3203
3204     if (!RetTy->isVoidTy() && VF != 1) {
3205       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3206                                                 VectorTy);
3207       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3208                                                 VectorTy);
3209
3210       // The cost of inserting the results plus extracting each one of the
3211       // operands.
3212       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3213     }
3214
3215     // The cost of executing VF copies of the scalar instruction. This opcode
3216     // is unknown. Assume that it is the same as 'mul'.
3217     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3218     return Cost;
3219   }
3220   }// end of switch.
3221 }
3222
3223 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3224   if (Scalar->isVoidTy() || VF == 1)
3225     return Scalar;
3226   return VectorType::get(Scalar, VF);
3227 }
3228
3229 char LoopVectorize::ID = 0;
3230 static const char lv_name[] = "Loop Vectorization";
3231 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3232 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3233 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3234 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3235 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3236 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3237
3238 namespace llvm {
3239   Pass *createLoopVectorizePass() {
3240     return new LoopVectorize();
3241   }
3242 }
3243
3244