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