LoopVectorize.cpp: Fix abuse of StringRef on Twine. Twine captures the pointer of...
[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.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
14 //
15 // The loop vectorizer combines consecutive loop iterations 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/PatternMatch.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Support/ValueHandle.h"
84 #include "llvm/Target/TargetLibraryInfo.h"
85 #include "llvm/Transforms/Scalar.h"
86 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
87 #include "llvm/Transforms/Utils/Local.h"
88 #include <algorithm>
89 #include <map>
90
91 using namespace llvm;
92 using namespace llvm::PatternMatch;
93
94 static cl::opt<unsigned>
95 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
96                     cl::desc("Sets the SIMD width. Zero is autoselect."));
97
98 static cl::opt<unsigned>
99 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
100                     cl::desc("Sets the vectorization unroll count. "
101                              "Zero is autoselect."));
102
103 static cl::opt<bool>
104 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
105                    cl::desc("Enable if-conversion during vectorization."));
106
107 /// We don't vectorize loops with a known constant trip count below this number.
108 static cl::opt<unsigned>
109 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
110                              cl::Hidden,
111                              cl::desc("Don't vectorize loops with a constant "
112                                       "trip count that is smaller than this "
113                                       "value."));
114
115 /// We don't unroll loops with a known constant trip count below this number.
116 static const unsigned TinyTripCountUnrollThreshold = 128;
117
118 /// When performing memory disambiguation checks at runtime do not make more
119 /// than this number of comparisons.
120 static const unsigned RuntimeMemoryCheckThreshold = 8;
121
122 /// Maximum simd width.
123 static const unsigned MaxVectorWidth = 64;
124
125 /// Maximum vectorization unroll count.
126 static const unsigned MaxUnrollFactor = 16;
127
128 namespace {
129
130 // Forward declarations.
131 class LoopVectorizationLegality;
132 class LoopVectorizationCostModel;
133
134 /// InnerLoopVectorizer vectorizes loops which contain only one basic
135 /// block to a specified vectorization factor (VF).
136 /// This class performs the widening of scalars into vectors, or multiple
137 /// scalars. This class also implements the following features:
138 /// * It inserts an epilogue loop for handling loops that don't have iteration
139 ///   counts that are known to be a multiple of the vectorization factor.
140 /// * It handles the code generation for reduction variables.
141 /// * Scalarization (implementation using scalars) of un-vectorizable
142 ///   instructions.
143 /// InnerLoopVectorizer does not perform any vectorization-legality
144 /// checks, and relies on the caller to check for the different legality
145 /// aspects. The InnerLoopVectorizer relies on the
146 /// LoopVectorizationLegality class to provide information about the induction
147 /// and reduction variables that were found to a given vectorization factor.
148 class InnerLoopVectorizer {
149 public:
150   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
151                       DominatorTree *DT, DataLayout *DL,
152                       const TargetLibraryInfo *TLI, unsigned VecWidth,
153                       unsigned UnrollFactor)
154       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
155         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
156         OldInduction(0), WidenMap(UnrollFactor) {}
157
158   // Perform the actual loop widening (vectorization).
159   void vectorize(LoopVectorizationLegality *Legal) {
160     // Create a new empty loop. Unlink the old loop and connect the new one.
161     createEmptyLoop(Legal);
162     // Widen each instruction in the old loop to a new one in the new loop.
163     // Use the Legality module to find the induction and reduction variables.
164     vectorizeLoop(Legal);
165     // Register the new loop and update the analysis passes.
166     updateAnalysis();
167   }
168
169 private:
170   /// A small list of PHINodes.
171   typedef SmallVector<PHINode*, 4> PhiVector;
172   /// When we unroll loops we have multiple vector values for each scalar.
173   /// This data structure holds the unrolled and vectorized values that
174   /// originated from one scalar instruction.
175   typedef SmallVector<Value*, 2> VectorParts;
176
177   /// Add code that checks at runtime if the accessed arrays overlap.
178   /// Returns the comparator value or NULL if no check is needed.
179   Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
180                                Instruction *Loc);
181   /// Create an empty loop, based on the loop ranges of the old loop.
182   void createEmptyLoop(LoopVectorizationLegality *Legal);
183   /// Copy and widen the instructions from the old loop.
184   void vectorizeLoop(LoopVectorizationLegality *Legal);
185
186   /// A helper function that computes the predicate of the block BB, assuming
187   /// that the header block of the loop is set to True. It returns the *entry*
188   /// mask for the block BB.
189   VectorParts createBlockInMask(BasicBlock *BB);
190   /// A helper function that computes the predicate of the edge between SRC
191   /// and DST.
192   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
193
194   /// A helper function to vectorize a single BB within the innermost loop.
195   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
196                             PhiVector *PV);
197
198   /// Insert the new loop to the loop hierarchy and pass manager
199   /// and update the analysis passes.
200   void updateAnalysis();
201
202   /// This instruction is un-vectorizable. Implement it as a sequence
203   /// of scalars.
204   void scalarizeInstruction(Instruction *Instr);
205
206   /// Vectorize Load and Store instructions,
207   void vectorizeMemoryInstruction(Instruction *Instr,
208                                   LoopVectorizationLegality *Legal);
209
210   /// Create a broadcast instruction. This method generates a broadcast
211   /// instruction (shuffle) for loop invariant values and for the induction
212   /// value. If this is the induction variable then we extend it to N, N+1, ...
213   /// this is needed because each iteration in the loop corresponds to a SIMD
214   /// element.
215   Value *getBroadcastInstrs(Value *V);
216
217   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
218   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
219   /// The sequence starts at StartIndex.
220   Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
221
222   /// When we go over instructions in the basic block we rely on previous
223   /// values within the current basic block or on loop invariant values.
224   /// When we widen (vectorize) values we place them in the map. If the values
225   /// are not within the map, they have to be loop invariant, so we simply
226   /// broadcast them into a vector.
227   VectorParts &getVectorValue(Value *V);
228
229   /// Generate a shuffle sequence that will reverse the vector Vec.
230   Value *reverseVector(Value *Vec);
231
232   /// This is a helper class that holds the vectorizer state. It maps scalar
233   /// instructions to vector instructions. When the code is 'unrolled' then
234   /// then a single scalar value is mapped to multiple vector parts. The parts
235   /// are stored in the VectorPart type.
236   struct ValueMap {
237     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
238     /// are mapped.
239     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
240
241     /// \return True if 'Key' is saved in the Value Map.
242     bool has(Value *Key) const { return MapStorage.count(Key); }
243
244     /// Initializes a new entry in the map. Sets all of the vector parts to the
245     /// save value in 'Val'.
246     /// \return A reference to a vector with splat values.
247     VectorParts &splat(Value *Key, Value *Val) {
248       VectorParts &Entry = MapStorage[Key];
249       Entry.assign(UF, Val);
250       return Entry;
251     }
252
253     ///\return A reference to the value that is stored at 'Key'.
254     VectorParts &get(Value *Key) {
255       VectorParts &Entry = MapStorage[Key];
256       if (Entry.empty())
257         Entry.resize(UF);
258       assert(Entry.size() == UF);
259       return Entry;
260     }
261
262   private:
263     /// The unroll factor. Each entry in the map stores this number of vector
264     /// elements.
265     unsigned UF;
266
267     /// Map storage. We use std::map and not DenseMap because insertions to a
268     /// dense map invalidates its iterators.
269     std::map<Value *, VectorParts> MapStorage;
270   };
271
272   /// The original loop.
273   Loop *OrigLoop;
274   /// Scev analysis to use.
275   ScalarEvolution *SE;
276   /// Loop Info.
277   LoopInfo *LI;
278   /// Dominator Tree.
279   DominatorTree *DT;
280   /// Data Layout.
281   DataLayout *DL;
282   /// Target Library Info.
283   const TargetLibraryInfo *TLI;
284
285   /// The vectorization SIMD factor to use. Each vector will have this many
286   /// vector elements.
287   unsigned VF;
288   /// The vectorization unroll factor to use. Each scalar is vectorized to this
289   /// many different vector instructions.
290   unsigned UF;
291
292   /// The builder that we use
293   IRBuilder<> Builder;
294
295   // --- Vectorization state ---
296
297   /// The vector-loop preheader.
298   BasicBlock *LoopVectorPreHeader;
299   /// The scalar-loop preheader.
300   BasicBlock *LoopScalarPreHeader;
301   /// Middle Block between the vector and the scalar.
302   BasicBlock *LoopMiddleBlock;
303   ///The ExitBlock of the scalar loop.
304   BasicBlock *LoopExitBlock;
305   ///The vector loop body.
306   BasicBlock *LoopVectorBody;
307   ///The scalar loop body.
308   BasicBlock *LoopScalarBody;
309   /// A list of all bypass blocks. The first block is the entry of the loop.
310   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
311
312   /// The new Induction variable which was added to the new block.
313   PHINode *Induction;
314   /// The induction variable of the old basic block.
315   PHINode *OldInduction;
316   /// Holds the extended (to the widest induction type) start index.
317   Value *ExtendedIdx;
318   /// Maps scalars to widened vectors.
319   ValueMap WidenMap;
320 };
321
322 /// \brief Check if conditionally executed loads are hoistable.
323 ///
324 /// This class has two functions: isHoistableLoad and canHoistAllLoads.
325 /// isHoistableLoad should be called on all load instructions that are executed
326 /// conditionally. After all conditional loads are processed, the client should
327 /// call canHoistAllLoads to determine if all of the conditional executed loads
328 /// have an unconditional memory access to the same memory address in the loop.
329 class LoadHoisting {
330   typedef SmallPtrSet<Value *, 8> MemorySet;
331
332   Loop *TheLoop;
333   DominatorTree *DT;
334   MemorySet CondLoadAddrSet;
335
336 public:
337   LoadHoisting(Loop *L, DominatorTree *D) : TheLoop(L), DT(D) {}
338
339   /// \brief Check if the instruction is a load with a identifiable address.
340   bool isHoistableLoad(Instruction *L);
341
342   /// \brief Check if all of the conditional loads are hoistable because there
343   /// exists an unconditional memory access to the same address in the loop.
344   bool canHoistAllLoads();
345 };
346
347 bool LoadHoisting::isHoistableLoad(Instruction *L) {
348   LoadInst *LI = dyn_cast<LoadInst>(L);
349   if (!LI)
350     return false;
351
352   CondLoadAddrSet.insert(LI->getPointerOperand());
353   return true;
354 }
355
356 static void addMemAccesses(BasicBlock *BB, SmallPtrSet<Value *, 8> &Set) {
357   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
358     if (LoadInst *LI = dyn_cast<LoadInst>(BI)) // Try a load.
359       Set.insert(LI->getPointerOperand());
360     else if (StoreInst *SI = dyn_cast<StoreInst>(BI)) // Try a store.
361       Set.insert(SI->getPointerOperand());
362   }
363 }
364
365 bool LoadHoisting::canHoistAllLoads() {
366   // No conditional loads.
367   if (CondLoadAddrSet.empty())
368     return true;
369
370   MemorySet UncondMemAccesses;
371   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
372   BasicBlock *LoopLatch = TheLoop->getLoopLatch();
373
374   // Iterate over the unconditional blocks and collect memory access addresses.
375   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
376     BasicBlock *BB = LoopBlocks[i];
377
378     // Ignore conditional blocks.
379     if (BB != LoopLatch && !DT->dominates(BB, LoopLatch))
380       continue;
381
382     addMemAccesses(BB, UncondMemAccesses);
383   }
384
385   // And make sure there is a matching unconditional access for every
386   // conditional load.
387   for (MemorySet::iterator MI = CondLoadAddrSet.begin(),
388        ME = CondLoadAddrSet.end(); MI != ME; ++MI)
389     if (!UncondMemAccesses.count(*MI))
390       return false;
391
392   return true;
393 }
394
395 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
396 /// to what vectorization factor.
397 /// This class does not look at the profitability of vectorization, only the
398 /// legality. This class has two main kinds of checks:
399 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
400 ///   will change the order of memory accesses in a way that will change the
401 ///   correctness of the program.
402 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
403 /// checks for a number of different conditions, such as the availability of a
404 /// single induction variable, that all types are supported and vectorize-able,
405 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
406 /// This class is also used by InnerLoopVectorizer for identifying
407 /// induction variable and the different reduction variables.
408 class LoopVectorizationLegality {
409 public:
410   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
411                             DominatorTree *DT, TargetTransformInfo* TTI,
412                             AliasAnalysis *AA, TargetLibraryInfo *TLI)
413       : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
414         Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
415         LoadSpeculation(L, DT) {}
416
417   /// This enum represents the kinds of reductions that we support.
418   enum ReductionKind {
419     RK_NoReduction, ///< Not a reduction.
420     RK_IntegerAdd,  ///< Sum of integers.
421     RK_IntegerMult, ///< Product of integers.
422     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
423     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
424     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
425     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
426     RK_FloatAdd,    ///< Sum of floats.
427     RK_FloatMult,   ///< Product of floats.
428     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
429   };
430
431   /// This enum represents the kinds of inductions that we support.
432   enum InductionKind {
433     IK_NoInduction,         ///< Not an induction variable.
434     IK_IntInduction,        ///< Integer induction variable. Step = 1.
435     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
436     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
437     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
438   };
439
440   // This enum represents the kind of minmax reduction.
441   enum MinMaxReductionKind {
442     MRK_Invalid,
443     MRK_UIntMin,
444     MRK_UIntMax,
445     MRK_SIntMin,
446     MRK_SIntMax,
447     MRK_FloatMin,
448     MRK_FloatMax
449   };
450
451   /// This POD struct holds information about reduction variables.
452   struct ReductionDescriptor {
453     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
454       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
455
456     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
457                         MinMaxReductionKind MK)
458         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
459
460     // The starting value of the reduction.
461     // It does not have to be zero!
462     TrackingVH<Value> StartValue;
463     // The instruction who's value is used outside the loop.
464     Instruction *LoopExitInstr;
465     // The kind of the reduction.
466     ReductionKind Kind;
467     // If this a min/max reduction the kind of reduction.
468     MinMaxReductionKind MinMaxKind;
469   };
470
471   /// This POD struct holds information about a potential reduction operation.
472   struct ReductionInstDesc {
473     ReductionInstDesc(bool IsRedux, Instruction *I) :
474       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
475
476     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
477       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
478
479     // Is this instruction a reduction candidate.
480     bool IsReduction;
481     // The last instruction in a min/max pattern (select of the select(icmp())
482     // pattern), or the current reduction instruction otherwise.
483     Instruction *PatternLastInst;
484     // If this is a min/max pattern the comparison predicate.
485     MinMaxReductionKind MinMaxKind;
486   };
487
488   // This POD struct holds information about the memory runtime legality
489   // check that a group of pointers do not overlap.
490   struct RuntimePointerCheck {
491     RuntimePointerCheck() : Need(false) {}
492
493     /// Reset the state of the pointer runtime information.
494     void reset() {
495       Need = false;
496       Pointers.clear();
497       Starts.clear();
498       Ends.clear();
499     }
500
501     /// Insert a pointer and calculate the start and end SCEVs.
502     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr);
503
504     /// This flag indicates if we need to add the runtime check.
505     bool Need;
506     /// Holds the pointers that we need to check.
507     SmallVector<TrackingVH<Value>, 2> Pointers;
508     /// Holds the pointer value at the beginning of the loop.
509     SmallVector<const SCEV*, 2> Starts;
510     /// Holds the pointer value at the end of the loop.
511     SmallVector<const SCEV*, 2> Ends;
512     /// Holds the information if this pointer is used for writing to memory.
513     SmallVector<bool, 2> IsWritePtr;
514   };
515
516   /// A POD for saving information about induction variables.
517   struct InductionInfo {
518     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
519     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
520     /// Start value.
521     TrackingVH<Value> StartValue;
522     /// Induction kind.
523     InductionKind IK;
524   };
525
526   /// ReductionList contains the reduction descriptors for all
527   /// of the reductions that were found in the loop.
528   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
529
530   /// InductionList saves induction variables and maps them to the
531   /// induction descriptor.
532   typedef MapVector<PHINode*, InductionInfo> InductionList;
533
534   /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
535   /// respective Store/Load instruction(s) to calculate aliasing.
536   typedef MapVector<Value*, Instruction* > AliasMap;
537   typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
538
539   /// Returns true if it is legal to vectorize this loop.
540   /// This does not mean that it is profitable to vectorize this
541   /// loop, only that it is legal to do so.
542   bool canVectorize();
543
544   /// Returns the Induction variable.
545   PHINode *getInduction() { return Induction; }
546
547   /// Returns the reduction variables found in the loop.
548   ReductionList *getReductionVars() { return &Reductions; }
549
550   /// Returns the induction variables found in the loop.
551   InductionList *getInductionVars() { return &Inductions; }
552
553   /// Returns the widest induction type.
554   Type *getWidestInductionType() { return WidestIndTy; }
555
556   /// Returns True if V is an induction variable in this loop.
557   bool isInductionVariable(const Value *V);
558
559   /// Return true if the block BB needs to be predicated in order for the loop
560   /// to be vectorized.
561   bool blockNeedsPredication(BasicBlock *BB);
562
563   /// Check if this  pointer is consecutive when vectorizing. This happens
564   /// when the last index of the GEP is the induction variable, or that the
565   /// pointer itself is an induction variable.
566   /// This check allows us to vectorize A[idx] into a wide load/store.
567   /// Returns:
568   /// 0 - Stride is unknown or non consecutive.
569   /// 1 - Address is consecutive.
570   /// -1 - Address is consecutive, and decreasing.
571   int isConsecutivePtr(Value *Ptr);
572
573   /// Returns true if the value V is uniform within the loop.
574   bool isUniform(Value *V);
575
576   /// Returns true if this instruction will remain scalar after vectorization.
577   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
578
579   /// Returns the information that we collected about runtime memory check.
580   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
581
582   /// This function returns the identity element (or neutral element) for
583   /// the operation K.
584   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
585 private:
586   /// Check if a single basic block loop is vectorizable.
587   /// At this point we know that this is a loop with a constant trip count
588   /// and we only need to check individual instructions.
589   bool canVectorizeInstrs();
590
591   /// When we vectorize loops we may change the order in which
592   /// we read and write from memory. This method checks if it is
593   /// legal to vectorize the code, considering only memory constrains.
594   /// Returns true if the loop is vectorizable
595   bool canVectorizeMemory();
596
597   /// Return true if we can vectorize this loop using the IF-conversion
598   /// transformation.
599   bool canVectorizeWithIfConvert();
600
601   /// Collect the variables that need to stay uniform after vectorization.
602   void collectLoopUniforms();
603
604   /// Return true if all of the instructions in the block can be speculatively
605   /// executed.
606   bool blockCanBePredicated(BasicBlock *BB);
607
608   /// Returns True, if 'Phi' is the kind of reduction variable for type
609   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
610   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
611   /// Returns a struct describing if the instruction 'I' can be a reduction
612   /// variable of type 'Kind'. If the reduction is a min/max pattern of
613   /// select(icmp()) this function advances the instruction pointer 'I' from the
614   /// compare instruction to the select instruction and stores this pointer in
615   /// 'PatternLastInst' member of the returned struct.
616   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
617                                      ReductionInstDesc &Desc);
618   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
619   /// pattern corresponding to a min(X, Y) or max(X, Y).
620   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
621                                                     ReductionInstDesc &Prev);
622   /// Returns the induction kind of Phi. This function may return NoInduction
623   /// if the PHI is not an induction variable.
624   InductionKind isInductionVariable(PHINode *Phi);
625   /// Return true if can compute the address bounds of Ptr within the loop.
626   bool hasComputableBounds(Value *Ptr);
627   /// Return true if there is the chance of write reorder.
628   bool hasPossibleGlobalWriteReorder(Value *Object,
629                                      Instruction *Inst,
630                                      AliasMultiMap &WriteObjects,
631                                      unsigned MaxByteWidth);
632   /// Return the AA location for a load or a store.
633   AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
634
635
636   /// The loop that we evaluate.
637   Loop *TheLoop;
638   /// Scev analysis.
639   ScalarEvolution *SE;
640   /// DataLayout analysis.
641   DataLayout *DL;
642   /// Dominators.
643   DominatorTree *DT;
644   /// Target Info.
645   TargetTransformInfo *TTI;
646   /// Alias Analysis.
647   AliasAnalysis *AA;
648   /// Target Library Info.
649   TargetLibraryInfo *TLI;
650
651   //  ---  vectorization state --- //
652
653   /// Holds the integer induction variable. This is the counter of the
654   /// loop.
655   PHINode *Induction;
656   /// Holds the reduction variables.
657   ReductionList Reductions;
658   /// Holds all of the induction variables that we found in the loop.
659   /// Notice that inductions don't need to start at zero and that induction
660   /// variables can be pointers.
661   InductionList Inductions;
662   /// Holds the widest induction type encountered.
663   Type *WidestIndTy;
664
665   /// Allowed outside users. This holds the reduction
666   /// vars which can be accessed from outside the loop.
667   SmallPtrSet<Value*, 4> AllowedExit;
668   /// This set holds the variables which are known to be uniform after
669   /// vectorization.
670   SmallPtrSet<Instruction*, 4> Uniforms;
671   /// We need to check that all of the pointers in this list are disjoint
672   /// at runtime.
673   RuntimePointerCheck PtrRtCheck;
674   /// Can we assume the absence of NaNs.
675   bool HasFunNoNaNAttr;
676
677   /// Utility to determine whether loads can be speculated.
678   LoadHoisting LoadSpeculation;
679 };
680
681 /// LoopVectorizationCostModel - estimates the expected speedups due to
682 /// vectorization.
683 /// In many cases vectorization is not profitable. This can happen because of
684 /// a number of reasons. In this class we mainly attempt to predict the
685 /// expected speedup/slowdowns due to the supported instruction set. We use the
686 /// TargetTransformInfo to query the different backends for the cost of
687 /// different operations.
688 class LoopVectorizationCostModel {
689 public:
690   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
691                              LoopVectorizationLegality *Legal,
692                              const TargetTransformInfo &TTI,
693                              DataLayout *DL, const TargetLibraryInfo *TLI)
694       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
695
696   /// Information about vectorization costs
697   struct VectorizationFactor {
698     unsigned Width; // Vector width with best cost
699     unsigned Cost; // Cost of the loop with that width
700   };
701   /// \return The most profitable vectorization factor and the cost of that VF.
702   /// This method checks every power of two up to VF. If UserVF is not ZERO
703   /// then this vectorization factor will be selected if vectorization is
704   /// possible.
705   VectorizationFactor selectVectorizationFactor(bool OptForSize,
706                                                 unsigned UserVF);
707
708   /// \return The size (in bits) of the widest type in the code that
709   /// needs to be vectorized. We ignore values that remain scalar such as
710   /// 64 bit loop indices.
711   unsigned getWidestType();
712
713   /// \return The most profitable unroll factor.
714   /// If UserUF is non-zero then this method finds the best unroll-factor
715   /// based on register pressure and other parameters.
716   /// VF and LoopCost are the selected vectorization factor and the cost of the
717   /// selected VF.
718   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
719                               unsigned LoopCost);
720
721   /// \brief A struct that represents some properties of the register usage
722   /// of a loop.
723   struct RegisterUsage {
724     /// Holds the number of loop invariant values that are used in the loop.
725     unsigned LoopInvariantRegs;
726     /// Holds the maximum number of concurrent live intervals in the loop.
727     unsigned MaxLocalUsers;
728     /// Holds the number of instructions in the loop.
729     unsigned NumInstructions;
730   };
731
732   /// \return  information about the register usage of the loop.
733   RegisterUsage calculateRegisterUsage();
734
735 private:
736   /// Returns the expected execution cost. The unit of the cost does
737   /// not matter because we use the 'cost' units to compare different
738   /// vector widths. The cost that is returned is *not* normalized by
739   /// the factor width.
740   unsigned expectedCost(unsigned VF);
741
742   /// Returns the execution time cost of an instruction for a given vector
743   /// width. Vector width of one means scalar.
744   unsigned getInstructionCost(Instruction *I, unsigned VF);
745
746   /// A helper function for converting Scalar types to vector types.
747   /// If the incoming type is void, we return void. If the VF is 1, we return
748   /// the scalar type.
749   static Type* ToVectorTy(Type *Scalar, unsigned VF);
750
751   /// Returns whether the instruction is a load or store and will be a emitted
752   /// as a vector operation.
753   bool isConsecutiveLoadOrStore(Instruction *I);
754
755   /// The loop that we evaluate.
756   Loop *TheLoop;
757   /// Scev analysis.
758   ScalarEvolution *SE;
759   /// Loop Info analysis.
760   LoopInfo *LI;
761   /// Vectorization legality.
762   LoopVectorizationLegality *Legal;
763   /// Vector target information.
764   const TargetTransformInfo &TTI;
765   /// Target data layout information.
766   DataLayout *DL;
767   /// Target Library Info.
768   const TargetLibraryInfo *TLI;
769 };
770
771 /// Utility class for getting and setting loop vectorizer hints in the form
772 /// of loop metadata.
773 struct LoopVectorizeHints {
774   /// Vectorization width.
775   unsigned Width;
776   /// Vectorization unroll factor.
777   unsigned Unroll;
778
779   LoopVectorizeHints(const Loop *L)
780   : Width(VectorizationFactor)
781   , Unroll(VectorizationUnroll)
782   , LoopID(L->getLoopID()) {
783     getHints(L);
784     // The command line options override any loop metadata except for when
785     // width == 1 which is used to indicate the loop is already vectorized.
786     if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
787       Width = VectorizationFactor;
788     if (VectorizationUnroll.getNumOccurrences() > 0)
789       Unroll = VectorizationUnroll;
790   }
791
792   /// Return the loop vectorizer metadata prefix.
793   static StringRef Prefix() { return "llvm.vectorizer."; }
794
795   MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
796     SmallVector<Value*, 2> Vals;
797     Vals.push_back(MDString::get(Context, Name));
798     Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
799     return MDNode::get(Context, Vals);
800   }
801
802   /// Mark the loop L as already vectorized by setting the width to 1.
803   void setAlreadyVectorized(Loop *L) {
804     LLVMContext &Context = L->getHeader()->getContext();
805
806     Width = 1;
807
808     // Create a new loop id with one more operand for the already_vectorized
809     // hint. If the loop already has a loop id then copy the existing operands.
810     SmallVector<Value*, 4> Vals(1);
811     if (LoopID)
812       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
813         Vals.push_back(LoopID->getOperand(i));
814
815     Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
816
817     MDNode *NewLoopID = MDNode::get(Context, Vals);
818     // Set operand 0 to refer to the loop id itself.
819     NewLoopID->replaceOperandWith(0, NewLoopID);
820
821     L->setLoopID(NewLoopID);
822     if (LoopID)
823       LoopID->replaceAllUsesWith(NewLoopID);
824
825     LoopID = NewLoopID;
826   }
827
828 private:
829   MDNode *LoopID;
830
831   /// Find hints specified in the loop metadata.
832   void getHints(const Loop *L) {
833     if (!LoopID)
834       return;
835
836     // First operand should refer to the loop id itself.
837     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
838     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
839
840     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
841       const MDString *S = 0;
842       SmallVector<Value*, 4> Args;
843
844       // The expected hint is either a MDString or a MDNode with the first
845       // operand a MDString.
846       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
847         if (!MD || MD->getNumOperands() == 0)
848           continue;
849         S = dyn_cast<MDString>(MD->getOperand(0));
850         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
851           Args.push_back(MD->getOperand(i));
852       } else {
853         S = dyn_cast<MDString>(LoopID->getOperand(i));
854         assert(Args.size() == 0 && "too many arguments for MDString");
855       }
856
857       if (!S)
858         continue;
859
860       // Check if the hint starts with the vectorizer prefix.
861       StringRef Hint = S->getString();
862       if (!Hint.startswith(Prefix()))
863         continue;
864       // Remove the prefix.
865       Hint = Hint.substr(Prefix().size(), StringRef::npos);
866
867       if (Args.size() == 1)
868         getHint(Hint, Args[0]);
869     }
870   }
871
872   // Check string hint with one operand.
873   void getHint(StringRef Hint, Value *Arg) {
874     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
875     if (!C) return;
876     unsigned Val = C->getZExtValue();
877
878     if (Hint == "width") {
879       assert(isPowerOf2_32(Val) && Val <= MaxVectorWidth &&
880              "Invalid width metadata");
881       Width = Val;
882     } else if (Hint == "unroll") {
883       assert(isPowerOf2_32(Val) && Val <= MaxUnrollFactor &&
884              "Invalid unroll metadata");
885       Unroll = Val;
886     } else
887       DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint);
888   }
889 };
890
891 /// The LoopVectorize Pass.
892 struct LoopVectorize : public LoopPass {
893   /// Pass identification, replacement for typeid
894   static char ID;
895
896   explicit LoopVectorize() : LoopPass(ID) {
897     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
898   }
899
900   ScalarEvolution *SE;
901   DataLayout *DL;
902   LoopInfo *LI;
903   TargetTransformInfo *TTI;
904   DominatorTree *DT;
905   AliasAnalysis *AA;
906   TargetLibraryInfo *TLI;
907
908   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
909     // We only vectorize innermost loops.
910     if (!L->empty())
911       return false;
912
913     SE = &getAnalysis<ScalarEvolution>();
914     DL = getAnalysisIfAvailable<DataLayout>();
915     LI = &getAnalysis<LoopInfo>();
916     TTI = &getAnalysis<TargetTransformInfo>();
917     DT = &getAnalysis<DominatorTree>();
918     AA = getAnalysisIfAvailable<AliasAnalysis>();
919     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
920
921     if (DL == NULL) {
922       DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
923       return false;
924     }
925
926     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
927           L->getHeader()->getParent()->getName() << "\"\n");
928
929     LoopVectorizeHints Hints(L);
930
931     if (Hints.Width == 1) {
932       DEBUG(dbgs() << "LV: Not vectorizing.\n");
933       return false;
934     }
935
936     // Check if it is legal to vectorize the loop.
937     LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
938     if (!LVL.canVectorize()) {
939       DEBUG(dbgs() << "LV: Not vectorizing.\n");
940       return false;
941     }
942
943     // Use the cost model.
944     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
945
946     // Check the function attributes to find out if this function should be
947     // optimized for size.
948     Function *F = L->getHeader()->getParent();
949     Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
950     Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
951     unsigned FnIndex = AttributeSet::FunctionIndex;
952     bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
953     bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
954
955     if (NoFloat) {
956       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
957             "attribute is used.\n");
958       return false;
959     }
960
961     // Select the optimal vectorization factor.
962     LoopVectorizationCostModel::VectorizationFactor VF;
963     VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
964     // Select the unroll factor.
965     unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
966                                         VF.Cost);
967
968     if (VF.Width == 1) {
969       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
970       return false;
971     }
972
973     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
974           F->getParent()->getModuleIdentifier()<<"\n");
975     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
976
977     // If we decided that it is *legal* to vectorize the loop then do it.
978     InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
979     LB.vectorize(&LVL);
980
981     // Mark the loop as already vectorized to avoid vectorizing again.
982     Hints.setAlreadyVectorized(L);
983
984     DEBUG(verifyFunction(*L->getHeader()->getParent()));
985     return true;
986   }
987
988   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
989     LoopPass::getAnalysisUsage(AU);
990     AU.addRequiredID(LoopSimplifyID);
991     AU.addRequiredID(LCSSAID);
992     AU.addRequired<DominatorTree>();
993     AU.addRequired<LoopInfo>();
994     AU.addRequired<ScalarEvolution>();
995     AU.addRequired<TargetTransformInfo>();
996     AU.addPreserved<LoopInfo>();
997     AU.addPreserved<DominatorTree>();
998   }
999
1000 };
1001
1002 } // end anonymous namespace
1003
1004 //===----------------------------------------------------------------------===//
1005 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1006 // LoopVectorizationCostModel.
1007 //===----------------------------------------------------------------------===//
1008
1009 void
1010 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
1011                                                        Loop *Lp, Value *Ptr,
1012                                                        bool WritePtr) {
1013   const SCEV *Sc = SE->getSCEV(Ptr);
1014   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1015   assert(AR && "Invalid addrec expression");
1016   const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
1017   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1018   Pointers.push_back(Ptr);
1019   Starts.push_back(AR->getStart());
1020   Ends.push_back(ScEnd);
1021   IsWritePtr.push_back(WritePtr);
1022 }
1023
1024 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1025   // Save the current insertion location.
1026   Instruction *Loc = Builder.GetInsertPoint();
1027
1028   // We need to place the broadcast of invariant variables outside the loop.
1029   Instruction *Instr = dyn_cast<Instruction>(V);
1030   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1031   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1032
1033   // Place the code for broadcasting invariant variables in the new preheader.
1034   if (Invariant)
1035     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1036
1037   // Broadcast the scalar into all locations in the vector.
1038   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1039
1040   // Restore the builder insertion point.
1041   if (Invariant)
1042     Builder.SetInsertPoint(Loc);
1043
1044   return Shuf;
1045 }
1046
1047 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1048                                                  bool Negate) {
1049   assert(Val->getType()->isVectorTy() && "Must be a vector");
1050   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1051          "Elem must be an integer");
1052   // Create the types.
1053   Type *ITy = Val->getType()->getScalarType();
1054   VectorType *Ty = cast<VectorType>(Val->getType());
1055   int VLen = Ty->getNumElements();
1056   SmallVector<Constant*, 8> Indices;
1057
1058   // Create a vector of consecutive numbers from zero to VF.
1059   for (int i = 0; i < VLen; ++i) {
1060     int64_t Idx = Negate ? (-i) : i;
1061     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1062   }
1063
1064   // Add the consecutive indices to the vector value.
1065   Constant *Cv = ConstantVector::get(Indices);
1066   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1067   return Builder.CreateAdd(Val, Cv, "induction");
1068 }
1069
1070 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1071   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
1072   // Make sure that the pointer does not point to structs.
1073   if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
1074     return 0;
1075
1076   // If this value is a pointer induction variable we know it is consecutive.
1077   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1078   if (Phi && Inductions.count(Phi)) {
1079     InductionInfo II = Inductions[Phi];
1080     if (IK_PtrInduction == II.IK)
1081       return 1;
1082     else if (IK_ReversePtrInduction == II.IK)
1083       return -1;
1084   }
1085
1086   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1087   if (!Gep)
1088     return 0;
1089
1090   unsigned NumOperands = Gep->getNumOperands();
1091   Value *LastIndex = Gep->getOperand(NumOperands - 1);
1092
1093   Value *GpPtr = Gep->getPointerOperand();
1094   // If this GEP value is a consecutive pointer induction variable and all of
1095   // the indices are constant then we know it is consecutive. We can
1096   Phi = dyn_cast<PHINode>(GpPtr);
1097   if (Phi && Inductions.count(Phi)) {
1098
1099     // Make sure that the pointer does not point to structs.
1100     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1101     if (GepPtrType->getElementType()->isAggregateType())
1102       return 0;
1103
1104     // Make sure that all of the index operands are loop invariant.
1105     for (unsigned i = 1; i < NumOperands; ++i)
1106       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1107         return 0;
1108
1109     InductionInfo II = Inductions[Phi];
1110     if (IK_PtrInduction == II.IK)
1111       return 1;
1112     else if (IK_ReversePtrInduction == II.IK)
1113       return -1;
1114   }
1115
1116   // Check that all of the gep indices are uniform except for the last.
1117   for (unsigned i = 0; i < NumOperands - 1; ++i)
1118     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1119       return 0;
1120
1121   // We can emit wide load/stores only if the last index is the induction
1122   // variable.
1123   const SCEV *Last = SE->getSCEV(LastIndex);
1124   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1125     const SCEV *Step = AR->getStepRecurrence(*SE);
1126
1127     // The memory is consecutive because the last index is consecutive
1128     // and all other indices are loop invariant.
1129     if (Step->isOne())
1130       return 1;
1131     if (Step->isAllOnesValue())
1132       return -1;
1133   }
1134
1135   return 0;
1136 }
1137
1138 bool LoopVectorizationLegality::isUniform(Value *V) {
1139   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1140 }
1141
1142 InnerLoopVectorizer::VectorParts&
1143 InnerLoopVectorizer::getVectorValue(Value *V) {
1144   assert(V != Induction && "The new induction variable should not be used.");
1145   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1146
1147   // If we have this scalar in the map, return it.
1148   if (WidenMap.has(V))
1149     return WidenMap.get(V);
1150
1151   // If this scalar is unknown, assume that it is a constant or that it is
1152   // loop invariant. Broadcast V and save the value for future uses.
1153   Value *B = getBroadcastInstrs(V);
1154   return WidenMap.splat(V, B);
1155 }
1156
1157 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1158   assert(Vec->getType()->isVectorTy() && "Invalid type");
1159   SmallVector<Constant*, 8> ShuffleMask;
1160   for (unsigned i = 0; i < VF; ++i)
1161     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1162
1163   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1164                                      ConstantVector::get(ShuffleMask),
1165                                      "reverse");
1166 }
1167
1168
1169 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1170                                              LoopVectorizationLegality *Legal) {
1171   // Attempt to issue a wide load.
1172   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1173   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1174
1175   assert((LI || SI) && "Invalid Load/Store instruction");
1176
1177   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1178   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1179   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1180   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1181
1182   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1183   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1184
1185   if (ScalarAllocatedSize != VectorElementSize)
1186     return scalarizeInstruction(Instr);
1187
1188   // If the pointer is loop invariant or if it is non consecutive,
1189   // scalarize the load.
1190   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1191   bool Reverse = ConsecutiveStride < 0;
1192   bool UniformLoad = LI && Legal->isUniform(Ptr);
1193   if (!ConsecutiveStride || UniformLoad)
1194     return scalarizeInstruction(Instr);
1195
1196   Constant *Zero = Builder.getInt32(0);
1197   VectorParts &Entry = WidenMap.get(Instr);
1198
1199   // Handle consecutive loads/stores.
1200   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1201   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1202     Value *PtrOperand = Gep->getPointerOperand();
1203     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1204     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1205
1206     // Create the new GEP with the new induction variable.
1207     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1208     Gep2->setOperand(0, FirstBasePtr);
1209     Gep2->setName("gep.indvar.base");
1210     Ptr = Builder.Insert(Gep2);
1211   } else if (Gep) {
1212     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1213                                OrigLoop) && "Base ptr must be invariant");
1214
1215     // The last index does not have to be the induction. It can be
1216     // consecutive and be a function of the index. For example A[I+1];
1217     unsigned NumOperands = Gep->getNumOperands();
1218
1219     Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1220     VectorParts &GEPParts = getVectorValue(LastGepOperand);
1221     Value *LastIndex = GEPParts[0];
1222     LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1223
1224     // Create the new GEP with the new induction variable.
1225     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1226     Gep2->setOperand(NumOperands - 1, LastIndex);
1227     Gep2->setName("gep.indvar.idx");
1228     Ptr = Builder.Insert(Gep2);
1229   } else {
1230     // Use the induction element ptr.
1231     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1232     VectorParts &PtrVal = getVectorValue(Ptr);
1233     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1234   }
1235
1236   // Handle Stores:
1237   if (SI) {
1238     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1239            "We do not allow storing to uniform addresses");
1240
1241     VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1242     for (unsigned Part = 0; Part < UF; ++Part) {
1243       // Calculate the pointer for the specific unroll-part.
1244       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1245
1246       if (Reverse) {
1247         // If we store to reverse consecutive memory locations then we need
1248         // to reverse the order of elements in the stored value.
1249         StoredVal[Part] = reverseVector(StoredVal[Part]);
1250         // If the address is consecutive but reversed, then the
1251         // wide store needs to start at the last vector element.
1252         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1253         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1254       }
1255
1256       Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1257       Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1258     }
1259   }
1260
1261   for (unsigned Part = 0; Part < UF; ++Part) {
1262     // Calculate the pointer for the specific unroll-part.
1263     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1264
1265     if (Reverse) {
1266       // If the address is consecutive but reversed, then the
1267       // wide store needs to start at the last vector element.
1268       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1269       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1270     }
1271
1272     Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1273     Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1274     cast<LoadInst>(LI)->setAlignment(Alignment);
1275     Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1276   }
1277 }
1278
1279 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1280   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1281   // Holds vector parameters or scalars, in case of uniform vals.
1282   SmallVector<VectorParts, 4> Params;
1283
1284   // Find all of the vectorized parameters.
1285   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1286     Value *SrcOp = Instr->getOperand(op);
1287
1288     // If we are accessing the old induction variable, use the new one.
1289     if (SrcOp == OldInduction) {
1290       Params.push_back(getVectorValue(SrcOp));
1291       continue;
1292     }
1293
1294     // Try using previously calculated values.
1295     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1296
1297     // If the src is an instruction that appeared earlier in the basic block
1298     // then it should already be vectorized.
1299     if (SrcInst && OrigLoop->contains(SrcInst)) {
1300       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1301       // The parameter is a vector value from earlier.
1302       Params.push_back(WidenMap.get(SrcInst));
1303     } else {
1304       // The parameter is a scalar from outside the loop. Maybe even a constant.
1305       VectorParts Scalars;
1306       Scalars.append(UF, SrcOp);
1307       Params.push_back(Scalars);
1308     }
1309   }
1310
1311   assert(Params.size() == Instr->getNumOperands() &&
1312          "Invalid number of operands");
1313
1314   // Does this instruction return a value ?
1315   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1316
1317   Value *UndefVec = IsVoidRetTy ? 0 :
1318     UndefValue::get(VectorType::get(Instr->getType(), VF));
1319   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1320   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1321
1322   // For each vector unroll 'part':
1323   for (unsigned Part = 0; Part < UF; ++Part) {
1324     // For each scalar that we create:
1325     for (unsigned Width = 0; Width < VF; ++Width) {
1326       Instruction *Cloned = Instr->clone();
1327       if (!IsVoidRetTy)
1328         Cloned->setName(Instr->getName() + ".cloned");
1329       // Replace the operands of the cloned instrucions with extracted scalars.
1330       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1331         Value *Op = Params[op][Part];
1332         // Param is a vector. Need to extract the right lane.
1333         if (Op->getType()->isVectorTy())
1334           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1335         Cloned->setOperand(op, Op);
1336       }
1337
1338       // Place the cloned scalar in the new loop.
1339       Builder.Insert(Cloned);
1340
1341       // If the original scalar returns a value we need to place it in a vector
1342       // so that future users will be able to use it.
1343       if (!IsVoidRetTy)
1344         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1345                                                        Builder.getInt32(Width));
1346     }
1347   }
1348 }
1349
1350 Instruction *
1351 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1352                                      Instruction *Loc) {
1353   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1354   Legal->getRuntimePointerCheck();
1355
1356   if (!PtrRtCheck->Need)
1357     return NULL;
1358
1359   Instruction *MemoryRuntimeCheck = 0;
1360   unsigned NumPointers = PtrRtCheck->Pointers.size();
1361   SmallVector<Value* , 2> Starts;
1362   SmallVector<Value* , 2> Ends;
1363
1364   SCEVExpander Exp(*SE, "induction");
1365
1366   // Use this type for pointer arithmetic.
1367   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1368
1369   for (unsigned i = 0; i < NumPointers; ++i) {
1370     Value *Ptr = PtrRtCheck->Pointers[i];
1371     const SCEV *Sc = SE->getSCEV(Ptr);
1372
1373     if (SE->isLoopInvariant(Sc, OrigLoop)) {
1374       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1375             *Ptr <<"\n");
1376       Starts.push_back(Ptr);
1377       Ends.push_back(Ptr);
1378     } else {
1379       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1380
1381       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1382       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1383       Starts.push_back(Start);
1384       Ends.push_back(End);
1385     }
1386   }
1387
1388   IRBuilder<> ChkBuilder(Loc);
1389
1390   for (unsigned i = 0; i < NumPointers; ++i) {
1391     for (unsigned j = i+1; j < NumPointers; ++j) {
1392       // No need to check if two readonly pointers intersect.
1393       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1394         continue;
1395
1396       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1397       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1398       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1399       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1400
1401       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1402       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1403       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1404       if (MemoryRuntimeCheck)
1405         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1406                                          "conflict.rdx");
1407
1408       MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1409     }
1410   }
1411
1412   return MemoryRuntimeCheck;
1413 }
1414
1415 void
1416 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1417   /*
1418    In this function we generate a new loop. The new loop will contain
1419    the vectorized instructions while the old loop will continue to run the
1420    scalar remainder.
1421
1422        [ ] <-- vector loop bypass (may consist of multiple blocks).
1423      /  |
1424     /   v
1425    |   [ ]     <-- vector pre header.
1426    |    |
1427    |    v
1428    |   [  ] \
1429    |   [  ]_|   <-- vector loop.
1430    |    |
1431     \   v
1432       >[ ]   <--- middle-block.
1433      /  |
1434     /   v
1435    |   [ ]     <--- new preheader.
1436    |    |
1437    |    v
1438    |   [ ] \
1439    |   [ ]_|   <-- old scalar loop to handle remainder.
1440     \   |
1441      \  v
1442       >[ ]     <-- exit block.
1443    ...
1444    */
1445
1446   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1447   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1448   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1449   assert(ExitBlock && "Must have an exit block");
1450
1451   // Some loops have a single integer induction variable, while other loops
1452   // don't. One example is c++ iterators that often have multiple pointer
1453   // induction variables. In the code below we also support a case where we
1454   // don't have a single induction variable.
1455   OldInduction = Legal->getInduction();
1456   Type *IdxTy = Legal->getWidestInductionType();
1457
1458   // Find the loop boundaries.
1459   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1460   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1461
1462   // Get the total trip count from the count by adding 1.
1463   ExitCount = SE->getAddExpr(ExitCount,
1464                              SE->getConstant(ExitCount->getType(), 1));
1465
1466   // Expand the trip count and place the new instructions in the preheader.
1467   // Notice that the pre-header does not change, only the loop body.
1468   SCEVExpander Exp(*SE, "induction");
1469
1470   // Count holds the overall loop count (N).
1471   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1472                                    BypassBlock->getTerminator());
1473
1474   // The loop index does not have to start at Zero. Find the original start
1475   // value from the induction PHI node. If we don't have an induction variable
1476   // then we know that it starts at zero.
1477   Builder.SetInsertPoint(BypassBlock->getTerminator());
1478   Value *StartIdx = ExtendedIdx = OldInduction ?
1479     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1480                        IdxTy):
1481     ConstantInt::get(IdxTy, 0);
1482
1483   assert(BypassBlock && "Invalid loop structure");
1484   LoopBypassBlocks.push_back(BypassBlock);
1485
1486   // Split the single block loop into the two loop structure described above.
1487   BasicBlock *VectorPH =
1488   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1489   BasicBlock *VecBody =
1490   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1491   BasicBlock *MiddleBlock =
1492   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1493   BasicBlock *ScalarPH =
1494   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1495
1496   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1497   // inside the loop.
1498   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1499
1500   // Generate the induction variable.
1501   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1502   // The loop step is equal to the vectorization factor (num of SIMD elements)
1503   // times the unroll factor (num of SIMD instructions).
1504   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1505
1506   // This is the IR builder that we use to add all of the logic for bypassing
1507   // the new vector loop.
1508   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1509
1510   // We may need to extend the index in case there is a type mismatch.
1511   // We know that the count starts at zero and does not overflow.
1512   if (Count->getType() != IdxTy) {
1513     // The exit count can be of pointer type. Convert it to the correct
1514     // integer type.
1515     if (ExitCount->getType()->isPointerTy())
1516       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1517     else
1518       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1519   }
1520
1521   // Add the start index to the loop count to get the new end index.
1522   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1523
1524   // Now we need to generate the expression for N - (N % VF), which is
1525   // the part that the vectorized body will execute.
1526   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1527   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1528   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1529                                                      "end.idx.rnd.down");
1530
1531   // Now, compare the new count to zero. If it is zero skip the vector loop and
1532   // jump to the scalar loop.
1533   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1534                                           "cmp.zero");
1535
1536   BasicBlock *LastBypassBlock = BypassBlock;
1537
1538   // Generate the code that checks in runtime if arrays overlap. We put the
1539   // checks into a separate block to make the more common case of few elements
1540   // faster.
1541   Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1542                                                  BypassBlock->getTerminator());
1543   if (MemRuntimeCheck) {
1544     // Create a new block containing the memory check.
1545     BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1546                                                           "vector.memcheck");
1547     LoopBypassBlocks.push_back(CheckBlock);
1548
1549     // Replace the branch into the memory check block with a conditional branch
1550     // for the "few elements case".
1551     Instruction *OldTerm = BypassBlock->getTerminator();
1552     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1553     OldTerm->eraseFromParent();
1554
1555     Cmp = MemRuntimeCheck;
1556     LastBypassBlock = CheckBlock;
1557   }
1558
1559   LastBypassBlock->getTerminator()->eraseFromParent();
1560   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1561                      LastBypassBlock);
1562
1563   // We are going to resume the execution of the scalar loop.
1564   // Go over all of the induction variables that we found and fix the
1565   // PHIs that are left in the scalar version of the loop.
1566   // The starting values of PHI nodes depend on the counter of the last
1567   // iteration in the vectorized loop.
1568   // If we come from a bypass edge then we need to start from the original
1569   // start value.
1570
1571   // This variable saves the new starting index for the scalar loop.
1572   PHINode *ResumeIndex = 0;
1573   LoopVectorizationLegality::InductionList::iterator I, E;
1574   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1575   // Set builder to point to last bypass block.
1576   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1577   for (I = List->begin(), E = List->end(); I != E; ++I) {
1578     PHINode *OrigPhi = I->first;
1579     LoopVectorizationLegality::InductionInfo II = I->second;
1580
1581     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1582     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1583                                          MiddleBlock->getTerminator());
1584     // We might have extended the type of the induction variable but we need a
1585     // truncated version for the scalar loop.
1586     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1587       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1588                       MiddleBlock->getTerminator()) : 0;
1589
1590     Value *EndValue = 0;
1591     switch (II.IK) {
1592     case LoopVectorizationLegality::IK_NoInduction:
1593       llvm_unreachable("Unknown induction");
1594     case LoopVectorizationLegality::IK_IntInduction: {
1595       // Handle the integer induction counter.
1596       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1597
1598       // We have the canonical induction variable.
1599       if (OrigPhi == OldInduction) {
1600         // Create a truncated version of the resume value for the scalar loop,
1601         // we might have promoted the type to a larger width.
1602         EndValue =
1603           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1604         // The new PHI merges the original incoming value, in case of a bypass,
1605         // or the value at the end of the vectorized loop.
1606         for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1607           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1608         TruncResumeVal->addIncoming(EndValue, VecBody);
1609
1610         // We know what the end value is.
1611         EndValue = IdxEndRoundDown;
1612         // We also know which PHI node holds it.
1613         ResumeIndex = ResumeVal;
1614         break;
1615       }
1616
1617       // Not the canonical induction variable - add the vector loop count to the
1618       // start value.
1619       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1620                                                    II.StartValue->getType(),
1621                                                    "cast.crd");
1622       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1623       break;
1624     }
1625     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1626       // Convert the CountRoundDown variable to the PHI size.
1627       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1628                                                    II.StartValue->getType(),
1629                                                    "cast.crd");
1630       // Handle reverse integer induction counter.
1631       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1632       break;
1633     }
1634     case LoopVectorizationLegality::IK_PtrInduction: {
1635       // For pointer induction variables, calculate the offset using
1636       // the end index.
1637       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1638                                          "ptr.ind.end");
1639       break;
1640     }
1641     case LoopVectorizationLegality::IK_ReversePtrInduction: {
1642       // The value at the end of the loop for the reverse pointer is calculated
1643       // by creating a GEP with a negative index starting from the start value.
1644       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1645       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1646                                               "rev.ind.end");
1647       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1648                                          "rev.ptr.ind.end");
1649       break;
1650     }
1651     }// end of case
1652
1653     // The new PHI merges the original incoming value, in case of a bypass,
1654     // or the value at the end of the vectorized loop.
1655     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1656       if (OrigPhi == OldInduction)
1657         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1658       else
1659         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1660     }
1661     ResumeVal->addIncoming(EndValue, VecBody);
1662
1663     // Fix the scalar body counter (PHI node).
1664     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1665     // The old inductions phi node in the scalar body needs the truncated value.
1666     if (OrigPhi == OldInduction)
1667       OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1668     else
1669       OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1670   }
1671
1672   // If we are generating a new induction variable then we also need to
1673   // generate the code that calculates the exit value. This value is not
1674   // simply the end of the counter because we may skip the vectorized body
1675   // in case of a runtime check.
1676   if (!OldInduction){
1677     assert(!ResumeIndex && "Unexpected resume value found");
1678     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1679                                   MiddleBlock->getTerminator());
1680     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1681       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1682     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1683   }
1684
1685   // Make sure that we found the index where scalar loop needs to continue.
1686   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1687          "Invalid resume Index");
1688
1689   // Add a check in the middle block to see if we have completed
1690   // all of the iterations in the first vector loop.
1691   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1692   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1693                                 ResumeIndex, "cmp.n",
1694                                 MiddleBlock->getTerminator());
1695
1696   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1697   // Remove the old terminator.
1698   MiddleBlock->getTerminator()->eraseFromParent();
1699
1700   // Create i+1 and fill the PHINode.
1701   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1702   Induction->addIncoming(StartIdx, VectorPH);
1703   Induction->addIncoming(NextIdx, VecBody);
1704   // Create the compare.
1705   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1706   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1707
1708   // Now we have two terminators. Remove the old one from the block.
1709   VecBody->getTerminator()->eraseFromParent();
1710
1711   // Get ready to start creating new instructions into the vectorized body.
1712   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1713
1714   // Create and register the new vector loop.
1715   Loop* Lp = new Loop();
1716   Loop *ParentLoop = OrigLoop->getParentLoop();
1717
1718   // Insert the new loop into the loop nest and register the new basic blocks.
1719   if (ParentLoop) {
1720     ParentLoop->addChildLoop(Lp);
1721     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1722       ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1723     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1724     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1725     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1726   } else {
1727     LI->addTopLevelLoop(Lp);
1728   }
1729
1730   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1731
1732   // Save the state.
1733   LoopVectorPreHeader = VectorPH;
1734   LoopScalarPreHeader = ScalarPH;
1735   LoopMiddleBlock = MiddleBlock;
1736   LoopExitBlock = ExitBlock;
1737   LoopVectorBody = VecBody;
1738   LoopScalarBody = OldBasicBlock;
1739 }
1740
1741 /// This function returns the identity element (or neutral element) for
1742 /// the operation K.
1743 Constant*
1744 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1745   switch (K) {
1746   case RK_IntegerXor:
1747   case RK_IntegerAdd:
1748   case RK_IntegerOr:
1749     // Adding, Xoring, Oring zero to a number does not change it.
1750     return ConstantInt::get(Tp, 0);
1751   case RK_IntegerMult:
1752     // Multiplying a number by 1 does not change it.
1753     return ConstantInt::get(Tp, 1);
1754   case RK_IntegerAnd:
1755     // AND-ing a number with an all-1 value does not change it.
1756     return ConstantInt::get(Tp, -1, true);
1757   case  RK_FloatMult:
1758     // Multiplying a number by 1 does not change it.
1759     return ConstantFP::get(Tp, 1.0L);
1760   case  RK_FloatAdd:
1761     // Adding zero to a number does not change it.
1762     return ConstantFP::get(Tp, 0.0L);
1763   default:
1764     llvm_unreachable("Unknown reduction kind");
1765   }
1766 }
1767
1768 static Intrinsic::ID
1769 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1770   // If we have an intrinsic call, check if it is trivially vectorizable.
1771   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1772     switch (II->getIntrinsicID()) {
1773     case Intrinsic::sqrt:
1774     case Intrinsic::sin:
1775     case Intrinsic::cos:
1776     case Intrinsic::exp:
1777     case Intrinsic::exp2:
1778     case Intrinsic::log:
1779     case Intrinsic::log10:
1780     case Intrinsic::log2:
1781     case Intrinsic::fabs:
1782     case Intrinsic::floor:
1783     case Intrinsic::ceil:
1784     case Intrinsic::trunc:
1785     case Intrinsic::rint:
1786     case Intrinsic::nearbyint:
1787     case Intrinsic::pow:
1788     case Intrinsic::fma:
1789     case Intrinsic::fmuladd:
1790       return II->getIntrinsicID();
1791     default:
1792       return Intrinsic::not_intrinsic;
1793     }
1794   }
1795
1796   if (!TLI)
1797     return Intrinsic::not_intrinsic;
1798
1799   LibFunc::Func Func;
1800   Function *F = CI->getCalledFunction();
1801   // We're going to make assumptions on the semantics of the functions, check
1802   // that the target knows that it's available in this environment.
1803   if (!F || !TLI->getLibFunc(F->getName(), Func))
1804     return Intrinsic::not_intrinsic;
1805
1806   // Otherwise check if we have a call to a function that can be turned into a
1807   // vector intrinsic.
1808   switch (Func) {
1809   default:
1810     break;
1811   case LibFunc::sin:
1812   case LibFunc::sinf:
1813   case LibFunc::sinl:
1814     return Intrinsic::sin;
1815   case LibFunc::cos:
1816   case LibFunc::cosf:
1817   case LibFunc::cosl:
1818     return Intrinsic::cos;
1819   case LibFunc::exp:
1820   case LibFunc::expf:
1821   case LibFunc::expl:
1822     return Intrinsic::exp;
1823   case LibFunc::exp2:
1824   case LibFunc::exp2f:
1825   case LibFunc::exp2l:
1826     return Intrinsic::exp2;
1827   case LibFunc::log:
1828   case LibFunc::logf:
1829   case LibFunc::logl:
1830     return Intrinsic::log;
1831   case LibFunc::log10:
1832   case LibFunc::log10f:
1833   case LibFunc::log10l:
1834     return Intrinsic::log10;
1835   case LibFunc::log2:
1836   case LibFunc::log2f:
1837   case LibFunc::log2l:
1838     return Intrinsic::log2;
1839   case LibFunc::fabs:
1840   case LibFunc::fabsf:
1841   case LibFunc::fabsl:
1842     return Intrinsic::fabs;
1843   case LibFunc::floor:
1844   case LibFunc::floorf:
1845   case LibFunc::floorl:
1846     return Intrinsic::floor;
1847   case LibFunc::ceil:
1848   case LibFunc::ceilf:
1849   case LibFunc::ceill:
1850     return Intrinsic::ceil;
1851   case LibFunc::trunc:
1852   case LibFunc::truncf:
1853   case LibFunc::truncl:
1854     return Intrinsic::trunc;
1855   case LibFunc::rint:
1856   case LibFunc::rintf:
1857   case LibFunc::rintl:
1858     return Intrinsic::rint;
1859   case LibFunc::nearbyint:
1860   case LibFunc::nearbyintf:
1861   case LibFunc::nearbyintl:
1862     return Intrinsic::nearbyint;
1863   case LibFunc::pow:
1864   case LibFunc::powf:
1865   case LibFunc::powl:
1866     return Intrinsic::pow;
1867   }
1868
1869   return Intrinsic::not_intrinsic;
1870 }
1871
1872 /// This function translates the reduction kind to an LLVM binary operator.
1873 static unsigned
1874 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1875   switch (Kind) {
1876     case LoopVectorizationLegality::RK_IntegerAdd:
1877       return Instruction::Add;
1878     case LoopVectorizationLegality::RK_IntegerMult:
1879       return Instruction::Mul;
1880     case LoopVectorizationLegality::RK_IntegerOr:
1881       return Instruction::Or;
1882     case LoopVectorizationLegality::RK_IntegerAnd:
1883       return Instruction::And;
1884     case LoopVectorizationLegality::RK_IntegerXor:
1885       return Instruction::Xor;
1886     case LoopVectorizationLegality::RK_FloatMult:
1887       return Instruction::FMul;
1888     case LoopVectorizationLegality::RK_FloatAdd:
1889       return Instruction::FAdd;
1890     case LoopVectorizationLegality::RK_IntegerMinMax:
1891       return Instruction::ICmp;
1892     case LoopVectorizationLegality::RK_FloatMinMax:
1893       return Instruction::FCmp;
1894     default:
1895       llvm_unreachable("Unknown reduction operation");
1896   }
1897 }
1898
1899 Value *createMinMaxOp(IRBuilder<> &Builder,
1900                       LoopVectorizationLegality::MinMaxReductionKind RK,
1901                       Value *Left,
1902                       Value *Right) {
1903   CmpInst::Predicate P = CmpInst::ICMP_NE;
1904   switch (RK) {
1905   default:
1906     llvm_unreachable("Unknown min/max reduction kind");
1907   case LoopVectorizationLegality::MRK_UIntMin:
1908     P = CmpInst::ICMP_ULT;
1909     break;
1910   case LoopVectorizationLegality::MRK_UIntMax:
1911     P = CmpInst::ICMP_UGT;
1912     break;
1913   case LoopVectorizationLegality::MRK_SIntMin:
1914     P = CmpInst::ICMP_SLT;
1915     break;
1916   case LoopVectorizationLegality::MRK_SIntMax:
1917     P = CmpInst::ICMP_SGT;
1918     break;
1919   case LoopVectorizationLegality::MRK_FloatMin:
1920     P = CmpInst::FCMP_OLT;
1921     break;
1922   case LoopVectorizationLegality::MRK_FloatMax:
1923     P = CmpInst::FCMP_OGT;
1924     break;
1925   }
1926
1927   Value *Cmp;
1928   if (RK == LoopVectorizationLegality::MRK_FloatMin || RK == LoopVectorizationLegality::MRK_FloatMax)
1929     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1930   else
1931     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1932
1933   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1934   return Select;
1935 }
1936
1937 void
1938 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1939   //===------------------------------------------------===//
1940   //
1941   // Notice: any optimization or new instruction that go
1942   // into the code below should be also be implemented in
1943   // the cost-model.
1944   //
1945   //===------------------------------------------------===//
1946   Constant *Zero = Builder.getInt32(0);
1947
1948   // In order to support reduction variables we need to be able to vectorize
1949   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1950   // stages. First, we create a new vector PHI node with no incoming edges.
1951   // We use this value when we vectorize all of the instructions that use the
1952   // PHI. Next, after all of the instructions in the block are complete we
1953   // add the new incoming edges to the PHI. At this point all of the
1954   // instructions in the basic block are vectorized, so we can use them to
1955   // construct the PHI.
1956   PhiVector RdxPHIsToFix;
1957
1958   // Scan the loop in a topological order to ensure that defs are vectorized
1959   // before users.
1960   LoopBlocksDFS DFS(OrigLoop);
1961   DFS.perform(LI);
1962
1963   // Vectorize all of the blocks in the original loop.
1964   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1965        be = DFS.endRPO(); bb != be; ++bb)
1966     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1967
1968   // At this point every instruction in the original loop is widened to
1969   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1970   // that we vectorized. The PHI nodes are currently empty because we did
1971   // not want to introduce cycles. Notice that the remaining PHI nodes
1972   // that we need to fix are reduction variables.
1973
1974   // Create the 'reduced' values for each of the induction vars.
1975   // The reduced values are the vector values that we scalarize and combine
1976   // after the loop is finished.
1977   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1978        it != e; ++it) {
1979     PHINode *RdxPhi = *it;
1980     assert(RdxPhi && "Unable to recover vectorized PHI");
1981
1982     // Find the reduction variable descriptor.
1983     assert(Legal->getReductionVars()->count(RdxPhi) &&
1984            "Unable to find the reduction variable");
1985     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1986     (*Legal->getReductionVars())[RdxPhi];
1987
1988     // We need to generate a reduction vector from the incoming scalar.
1989     // To do so, we need to generate the 'identity' vector and overide
1990     // one of the elements with the incoming scalar reduction. We need
1991     // to do it in the vector-loop preheader.
1992     Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1993
1994     // This is the vector-clone of the value that leaves the loop.
1995     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1996     Type *VecTy = VectorExit[0]->getType();
1997
1998     // Find the reduction identity variable. Zero for addition, or, xor,
1999     // one for multiplication, -1 for And.
2000     Value *Identity;
2001     Value *VectorStart;
2002     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2003         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2004       // MinMax reduction have the start value as their identify.
2005       VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue,
2006                                                          "minmax.ident");
2007     } else {
2008       Constant *Iden =
2009         LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2010                                                         VecTy->getScalarType());
2011       Identity = ConstantVector::getSplat(VF, Iden);
2012
2013       // This vector is the Identity vector where the first element is the
2014       // incoming scalar reduction.
2015       VectorStart = Builder.CreateInsertElement(Identity,
2016                                                 RdxDesc.StartValue, Zero);
2017     }
2018
2019     // Fix the vector-loop phi.
2020     // We created the induction variable so we know that the
2021     // preheader is the first entry.
2022     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2023
2024     // Reductions do not have to start at zero. They can start with
2025     // any loop invariant values.
2026     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2027     BasicBlock *Latch = OrigLoop->getLoopLatch();
2028     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2029     VectorParts &Val = getVectorValue(LoopVal);
2030     for (unsigned part = 0; part < UF; ++part) {
2031       // Make sure to add the reduction stat value only to the
2032       // first unroll part.
2033       Value *StartVal = (part == 0) ? VectorStart : Identity;
2034       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2035       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2036     }
2037
2038     // Before each round, move the insertion point right between
2039     // the PHIs and the values we are going to write.
2040     // This allows us to write both PHINodes and the extractelement
2041     // instructions.
2042     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2043
2044     VectorParts RdxParts;
2045     for (unsigned part = 0; part < UF; ++part) {
2046       // This PHINode contains the vectorized reduction variable, or
2047       // the initial value vector, if we bypass the vector loop.
2048       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2049       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2050       Value *StartVal = (part == 0) ? VectorStart : Identity;
2051       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2052         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2053       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2054       RdxParts.push_back(NewPhi);
2055     }
2056
2057     // Reduce all of the unrolled parts into a single vector.
2058     Value *ReducedPartRdx = RdxParts[0];
2059     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2060     for (unsigned part = 1; part < UF; ++part) {
2061       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2062         ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2063                                              RdxParts[part], ReducedPartRdx,
2064                                              "bin.rdx");
2065       else
2066         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2067                                         ReducedPartRdx, RdxParts[part]);
2068     }
2069
2070     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2071     // and vector ops, reducing the set of values being computed by half each
2072     // round.
2073     assert(isPowerOf2_32(VF) &&
2074            "Reduction emission only supported for pow2 vectors!");
2075     Value *TmpVec = ReducedPartRdx;
2076     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2077     for (unsigned i = VF; i != 1; i >>= 1) {
2078       // Move the upper half of the vector to the lower half.
2079       for (unsigned j = 0; j != i/2; ++j)
2080         ShuffleMask[j] = Builder.getInt32(i/2 + j);
2081
2082       // Fill the rest of the mask with undef.
2083       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2084                 UndefValue::get(Builder.getInt32Ty()));
2085
2086       Value *Shuf =
2087         Builder.CreateShuffleVector(TmpVec,
2088                                     UndefValue::get(TmpVec->getType()),
2089                                     ConstantVector::get(ShuffleMask),
2090                                     "rdx.shuf");
2091
2092       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2093         TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2094                                      "bin.rdx");
2095       else
2096         TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2097     }
2098
2099     // The result is in the first element of the vector.
2100     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2101
2102     // Now, we need to fix the users of the reduction variable
2103     // inside and outside of the scalar remainder loop.
2104     // We know that the loop is in LCSSA form. We need to update the
2105     // PHI nodes in the exit blocks.
2106     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2107          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2108       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2109       if (!LCSSAPhi) continue;
2110
2111       // All PHINodes need to have a single entry edge, or two if
2112       // we already fixed them.
2113       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2114
2115       // We found our reduction value exit-PHI. Update it with the
2116       // incoming bypass edge.
2117       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2118         // Add an edge coming from the bypass.
2119         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
2120         break;
2121       }
2122     }// end of the LCSSA phi scan.
2123
2124     // Fix the scalar loop reduction variable with the incoming reduction sum
2125     // from the vector body and from the backedge value.
2126     int IncomingEdgeBlockIdx =
2127     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2128     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2129     // Pick the other block.
2130     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2131     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
2132     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2133   }// end of for each redux variable.
2134
2135   // The Loop exit block may have single value PHI nodes where the incoming
2136   // value is 'undef'. While vectorizing we only handled real values that
2137   // were defined inside the loop. Here we handle the 'undef case'.
2138   // See PR14725.
2139   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2140        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2141     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2142     if (!LCSSAPhi) continue;
2143     if (LCSSAPhi->getNumIncomingValues() == 1)
2144       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2145                             LoopMiddleBlock);
2146   }
2147 }
2148
2149 InnerLoopVectorizer::VectorParts
2150 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2151   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2152          "Invalid edge");
2153
2154   VectorParts SrcMask = createBlockInMask(Src);
2155
2156   // The terminator has to be a branch inst!
2157   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2158   assert(BI && "Unexpected terminator found");
2159
2160   if (BI->isConditional()) {
2161     VectorParts EdgeMask = getVectorValue(BI->getCondition());
2162
2163     if (BI->getSuccessor(0) != Dst)
2164       for (unsigned part = 0; part < UF; ++part)
2165         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2166
2167     for (unsigned part = 0; part < UF; ++part)
2168       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2169     return EdgeMask;
2170   }
2171
2172   return SrcMask;
2173 }
2174
2175 InnerLoopVectorizer::VectorParts
2176 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2177   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2178
2179   // Loop incoming mask is all-one.
2180   if (OrigLoop->getHeader() == BB) {
2181     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2182     return getVectorValue(C);
2183   }
2184
2185   // This is the block mask. We OR all incoming edges, and with zero.
2186   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2187   VectorParts BlockMask = getVectorValue(Zero);
2188
2189   // For each pred:
2190   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2191     VectorParts EM = createEdgeMask(*it, BB);
2192     for (unsigned part = 0; part < UF; ++part)
2193       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2194   }
2195
2196   return BlockMask;
2197 }
2198
2199 void
2200 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
2201                                           BasicBlock *BB, PhiVector *PV) {
2202   // For each instruction in the old loop.
2203   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2204     VectorParts &Entry = WidenMap.get(it);
2205     switch (it->getOpcode()) {
2206     case Instruction::Br:
2207       // Nothing to do for PHIs and BR, since we already took care of the
2208       // loop control flow instructions.
2209       continue;
2210     case Instruction::PHI:{
2211       PHINode* P = cast<PHINode>(it);
2212       // Handle reduction variables:
2213       if (Legal->getReductionVars()->count(P)) {
2214         for (unsigned part = 0; part < UF; ++part) {
2215           // This is phase one of vectorizing PHIs.
2216           Type *VecTy = VectorType::get(it->getType(), VF);
2217           Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2218                                         LoopVectorBody-> getFirstInsertionPt());
2219         }
2220         PV->push_back(P);
2221         continue;
2222       }
2223
2224       // Check for PHI nodes that are lowered to vector selects.
2225       if (P->getParent() != OrigLoop->getHeader()) {
2226         // We know that all PHIs in non header blocks are converted into
2227         // selects, so we don't have to worry about the insertion order and we
2228         // can just use the builder.
2229         // At this point we generate the predication tree. There may be
2230         // duplications since this is a simple recursive scan, but future
2231         // optimizations will clean it up.
2232
2233         unsigned NumIncoming = P->getNumIncomingValues();
2234
2235         // Generate a sequence of selects of the form:
2236         // SELECT(Mask3, In3,
2237         //      SELECT(Mask2, In2,
2238         //                   ( ...)))
2239         for (unsigned In = 0; In < NumIncoming; In++) {
2240           VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2241                                             P->getParent());
2242           VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2243
2244           for (unsigned part = 0; part < UF; ++part) {
2245             // We might have single edge PHIs (blocks) - use an identity
2246             // 'select' for the first PHI operand.
2247             if (In == 0)
2248               Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2249                                                  In0[part]);
2250             else
2251               // Select between the current value and the previous incoming edge
2252               // based on the incoming mask.
2253               Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2254                                                  Entry[part], "predphi");
2255           }
2256         }
2257         continue;
2258       }
2259
2260       // This PHINode must be an induction variable.
2261       // Make sure that we know about it.
2262       assert(Legal->getInductionVars()->count(P) &&
2263              "Not an induction variable");
2264
2265       LoopVectorizationLegality::InductionInfo II =
2266         Legal->getInductionVars()->lookup(P);
2267
2268       switch (II.IK) {
2269       case LoopVectorizationLegality::IK_NoInduction:
2270         llvm_unreachable("Unknown induction");
2271       case LoopVectorizationLegality::IK_IntInduction: {
2272         assert(P->getType() == II.StartValue->getType() && "Types must match");
2273         Type *PhiTy = P->getType();
2274         Value *Broadcasted;
2275         if (P == OldInduction) {
2276           // Handle the canonical induction variable. We might have had to
2277           // extend the type.
2278           Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2279         } else {
2280           // Handle other induction variables that are now based on the
2281           // canonical one.
2282           Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2283                                                    "normalized.idx");
2284           NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2285           Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2286                                           "offset.idx");
2287         }
2288         Broadcasted = getBroadcastInstrs(Broadcasted);
2289         // After broadcasting the induction variable we need to make the vector
2290         // consecutive by adding 0, 1, 2, etc.
2291         for (unsigned part = 0; part < UF; ++part)
2292           Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2293         continue;
2294       }
2295       case LoopVectorizationLegality::IK_ReverseIntInduction:
2296       case LoopVectorizationLegality::IK_PtrInduction:
2297       case LoopVectorizationLegality::IK_ReversePtrInduction:
2298         // Handle reverse integer and pointer inductions.
2299         Value *StartIdx = ExtendedIdx;
2300         // This is the normalized GEP that starts counting at zero.
2301         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2302                                                  "normalized.idx");
2303
2304         // Handle the reverse integer induction variable case.
2305         if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2306           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2307           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2308                                                  "resize.norm.idx");
2309           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2310                                                  "reverse.idx");
2311
2312           // This is a new value so do not hoist it out.
2313           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2314           // After broadcasting the induction variable we need to make the
2315           // vector consecutive by adding  ... -3, -2, -1, 0.
2316           for (unsigned part = 0; part < UF; ++part)
2317             Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2318                                                true);
2319           continue;
2320         }
2321
2322         // Handle the pointer induction variable case.
2323         assert(P->getType()->isPointerTy() && "Unexpected type.");
2324
2325         // Is this a reverse induction ptr or a consecutive induction ptr.
2326         bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2327                         II.IK);
2328
2329         // This is the vector of results. Notice that we don't generate
2330         // vector geps because scalar geps result in better code.
2331         for (unsigned part = 0; part < UF; ++part) {
2332           Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2333           for (unsigned int i = 0; i < VF; ++i) {
2334             int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2335             Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2336             Value *GlobalIdx;
2337             if (!Reverse)
2338               GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2339             else
2340               GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2341
2342             Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2343                                                "next.gep");
2344             VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2345                                                  Builder.getInt32(i),
2346                                                  "insert.gep");
2347           }
2348           Entry[part] = VecVal;
2349         }
2350         continue;
2351       }
2352
2353     }// End of PHI.
2354
2355     case Instruction::Add:
2356     case Instruction::FAdd:
2357     case Instruction::Sub:
2358     case Instruction::FSub:
2359     case Instruction::Mul:
2360     case Instruction::FMul:
2361     case Instruction::UDiv:
2362     case Instruction::SDiv:
2363     case Instruction::FDiv:
2364     case Instruction::URem:
2365     case Instruction::SRem:
2366     case Instruction::FRem:
2367     case Instruction::Shl:
2368     case Instruction::LShr:
2369     case Instruction::AShr:
2370     case Instruction::And:
2371     case Instruction::Or:
2372     case Instruction::Xor: {
2373       // Just widen binops.
2374       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2375       VectorParts &A = getVectorValue(it->getOperand(0));
2376       VectorParts &B = getVectorValue(it->getOperand(1));
2377
2378       // Use this vector value for all users of the original instruction.
2379       for (unsigned Part = 0; Part < UF; ++Part) {
2380         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2381
2382         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2383         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2384         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2385           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2386           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2387         }
2388         if (VecOp && isa<PossiblyExactOperator>(VecOp))
2389           VecOp->setIsExact(BinOp->isExact());
2390
2391         Entry[Part] = V;
2392       }
2393       break;
2394     }
2395     case Instruction::Select: {
2396       // Widen selects.
2397       // If the selector is loop invariant we can create a select
2398       // instruction with a scalar condition. Otherwise, use vector-select.
2399       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2400                                                OrigLoop);
2401
2402       // The condition can be loop invariant  but still defined inside the
2403       // loop. This means that we can't just use the original 'cond' value.
2404       // We have to take the 'vectorized' value and pick the first lane.
2405       // Instcombine will make this a no-op.
2406       VectorParts &Cond = getVectorValue(it->getOperand(0));
2407       VectorParts &Op0  = getVectorValue(it->getOperand(1));
2408       VectorParts &Op1  = getVectorValue(it->getOperand(2));
2409       Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2410                                                        Builder.getInt32(0));
2411       for (unsigned Part = 0; Part < UF; ++Part) {
2412         Entry[Part] = Builder.CreateSelect(
2413           InvariantCond ? ScalarCond : Cond[Part],
2414           Op0[Part],
2415           Op1[Part]);
2416       }
2417       break;
2418     }
2419
2420     case Instruction::ICmp:
2421     case Instruction::FCmp: {
2422       // Widen compares. Generate vector compares.
2423       bool FCmp = (it->getOpcode() == Instruction::FCmp);
2424       CmpInst *Cmp = dyn_cast<CmpInst>(it);
2425       VectorParts &A = getVectorValue(it->getOperand(0));
2426       VectorParts &B = getVectorValue(it->getOperand(1));
2427       for (unsigned Part = 0; Part < UF; ++Part) {
2428         Value *C = 0;
2429         if (FCmp)
2430           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2431         else
2432           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2433         Entry[Part] = C;
2434       }
2435       break;
2436     }
2437
2438     case Instruction::Store:
2439     case Instruction::Load:
2440         vectorizeMemoryInstruction(it, Legal);
2441         break;
2442     case Instruction::ZExt:
2443     case Instruction::SExt:
2444     case Instruction::FPToUI:
2445     case Instruction::FPToSI:
2446     case Instruction::FPExt:
2447     case Instruction::PtrToInt:
2448     case Instruction::IntToPtr:
2449     case Instruction::SIToFP:
2450     case Instruction::UIToFP:
2451     case Instruction::Trunc:
2452     case Instruction::FPTrunc:
2453     case Instruction::BitCast: {
2454       CastInst *CI = dyn_cast<CastInst>(it);
2455       /// Optimize the special case where the source is the induction
2456       /// variable. Notice that we can only optimize the 'trunc' case
2457       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2458       /// c. other casts depend on pointer size.
2459       if (CI->getOperand(0) == OldInduction &&
2460           it->getOpcode() == Instruction::Trunc) {
2461         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2462                                                CI->getType());
2463         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2464         for (unsigned Part = 0; Part < UF; ++Part)
2465           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2466         break;
2467       }
2468       /// Vectorize casts.
2469       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2470
2471       VectorParts &A = getVectorValue(it->getOperand(0));
2472       for (unsigned Part = 0; Part < UF; ++Part)
2473         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2474       break;
2475     }
2476
2477     case Instruction::Call: {
2478       // Ignore dbg intrinsics.
2479       if (isa<DbgInfoIntrinsic>(it))
2480         break;
2481
2482       Module *M = BB->getParent()->getParent();
2483       CallInst *CI = cast<CallInst>(it);
2484       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2485       assert(ID && "Not an intrinsic call!");
2486       for (unsigned Part = 0; Part < UF; ++Part) {
2487         SmallVector<Value*, 4> Args;
2488         for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2489           VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2490           Args.push_back(Arg[Part]);
2491         }
2492         Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2493         Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2494         Entry[Part] = Builder.CreateCall(F, Args);
2495       }
2496       break;
2497     }
2498
2499     default:
2500       // All other instructions are unsupported. Scalarize them.
2501       scalarizeInstruction(it);
2502       break;
2503     }// end of switch.
2504   }// end of for_each instr.
2505 }
2506
2507 void InnerLoopVectorizer::updateAnalysis() {
2508   // Forget the original basic block.
2509   SE->forgetLoop(OrigLoop);
2510
2511   // Update the dominator tree information.
2512   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2513          "Entry does not dominate exit.");
2514
2515   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2516     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2517   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2518   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2519   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2520   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2521   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2522   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2523
2524   DEBUG(DT->verifyAnalysis());
2525 }
2526
2527 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2528   if (!EnableIfConversion)
2529     return false;
2530
2531   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2532   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2533
2534   // Collect the blocks that need predication.
2535   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2536     BasicBlock *BB = LoopBlocks[i];
2537
2538     // We don't support switch statements inside loops.
2539     if (!isa<BranchInst>(BB->getTerminator()))
2540       return false;
2541
2542     // We must be able to predicate all blocks that need to be predicated.
2543     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2544       return false;
2545   }
2546
2547   // Check that we can actually speculate the hoistable loads.
2548   if (!LoadSpeculation.canHoistAllLoads())
2549     return false;
2550
2551   // We can if-convert this loop.
2552   return true;
2553 }
2554
2555 bool LoopVectorizationLegality::canVectorize() {
2556   // We must have a loop in canonical form. Loops with indirectbr in them cannot
2557   // be canonicalized.
2558   if (!TheLoop->getLoopPreheader())
2559     return false;
2560
2561   // We can only vectorize innermost loops.
2562   if (TheLoop->getSubLoopsVector().size())
2563     return false;
2564
2565   // We must have a single backedge.
2566   if (TheLoop->getNumBackEdges() != 1)
2567     return false;
2568
2569   // We must have a single exiting block.
2570   if (!TheLoop->getExitingBlock())
2571     return false;
2572
2573   unsigned NumBlocks = TheLoop->getNumBlocks();
2574
2575   // Check if we can if-convert non single-bb loops.
2576   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2577     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2578     return false;
2579   }
2580
2581   // We need to have a loop header.
2582   BasicBlock *Latch = TheLoop->getLoopLatch();
2583   DEBUG(dbgs() << "LV: Found a loop: " <<
2584         TheLoop->getHeader()->getName() << "\n");
2585
2586   // ScalarEvolution needs to be able to find the exit count.
2587   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2588   if (ExitCount == SE->getCouldNotCompute()) {
2589     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2590     return false;
2591   }
2592
2593   // Do not loop-vectorize loops with a tiny trip count.
2594   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2595   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2596     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2597           "This loop is not worth vectorizing.\n");
2598     return false;
2599   }
2600
2601   // Check if we can vectorize the instructions and CFG in this loop.
2602   if (!canVectorizeInstrs()) {
2603     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2604     return false;
2605   }
2606
2607   // Go over each instruction and look at memory deps.
2608   if (!canVectorizeMemory()) {
2609     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2610     return false;
2611   }
2612
2613   // Collect all of the variables that remain uniform after vectorization.
2614   collectLoopUniforms();
2615
2616   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2617         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2618         <<"!\n");
2619
2620   // Okay! We can vectorize. At this point we don't have any other mem analysis
2621   // which may limit our maximum vectorization factor, so just return true with
2622   // no restrictions.
2623   return true;
2624 }
2625
2626 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2627   if (Ty->isPointerTy())
2628     return DL.getIntPtrType(Ty->getContext());
2629   return Ty;
2630 }
2631
2632 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2633   Ty0 = convertPointerToIntegerType(DL, Ty0);
2634   Ty1 = convertPointerToIntegerType(DL, Ty1);
2635   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2636     return Ty0;
2637   return Ty1;
2638 }
2639
2640 bool LoopVectorizationLegality::canVectorizeInstrs() {
2641   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2642   BasicBlock *Header = TheLoop->getHeader();
2643
2644   // Look for the attribute signaling the absence of NaNs.
2645   Function &F = *Header->getParent();
2646   if (F.hasFnAttribute("no-nans-fp-math"))
2647     HasFunNoNaNAttr = F.getAttributes().getAttribute(
2648       AttributeSet::FunctionIndex,
2649       "no-nans-fp-math").getValueAsString() == "true";
2650
2651   // For each block in the loop.
2652   for (Loop::block_iterator bb = TheLoop->block_begin(),
2653        be = TheLoop->block_end(); bb != be; ++bb) {
2654
2655     // Scan the instructions in the block and look for hazards.
2656     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2657          ++it) {
2658
2659       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2660         Type *PhiTy = Phi->getType();
2661         // Check that this PHI type is allowed.
2662         if (!PhiTy->isIntegerTy() &&
2663             !PhiTy->isFloatingPointTy() &&
2664             !PhiTy->isPointerTy()) {
2665           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2666           return false;
2667         }
2668
2669         // If this PHINode is not in the header block, then we know that we
2670         // can convert it to select during if-conversion. No need to check if
2671         // the PHIs in this block are induction or reduction variables.
2672         if (*bb != Header)
2673           continue;
2674
2675         // We only allow if-converted PHIs with more than two incoming values.
2676         if (Phi->getNumIncomingValues() != 2) {
2677           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2678           return false;
2679         }
2680
2681         // This is the value coming from the preheader.
2682         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2683         // Check if this is an induction variable.
2684         InductionKind IK = isInductionVariable(Phi);
2685
2686         if (IK_NoInduction != IK) {
2687           // Get the widest type.
2688           if (!WidestIndTy)
2689             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2690           else
2691             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2692
2693           // Int inductions are special because we only allow one IV.
2694           if (IK == IK_IntInduction) {
2695             // Use the phi node with the widest type as induction. Use the last
2696             // one if there are multiple (no good reason for doing this other
2697             // than it is expedient).
2698             if (!Induction || PhiTy == WidestIndTy)
2699               Induction = Phi;
2700           }
2701
2702           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2703           Inductions[Phi] = InductionInfo(StartValue, IK);
2704           continue;
2705         }
2706
2707         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2708           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2709           continue;
2710         }
2711         if (AddReductionVar(Phi, RK_IntegerMult)) {
2712           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2713           continue;
2714         }
2715         if (AddReductionVar(Phi, RK_IntegerOr)) {
2716           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2717           continue;
2718         }
2719         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2720           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2721           continue;
2722         }
2723         if (AddReductionVar(Phi, RK_IntegerXor)) {
2724           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2725           continue;
2726         }
2727         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2728           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2729           continue;
2730         }
2731         if (AddReductionVar(Phi, RK_FloatMult)) {
2732           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2733           continue;
2734         }
2735         if (AddReductionVar(Phi, RK_FloatAdd)) {
2736           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2737           continue;
2738         }
2739         if (AddReductionVar(Phi, RK_FloatMinMax)) {
2740           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<"\n");
2741           continue;
2742         }
2743
2744         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2745         return false;
2746       }// end of PHI handling
2747
2748       // We still don't handle functions. However, we can ignore dbg intrinsic
2749       // calls and we do handle certain intrinsic and libm functions.
2750       CallInst *CI = dyn_cast<CallInst>(it);
2751       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2752         DEBUG(dbgs() << "LV: Found a call site.\n");
2753         return false;
2754       }
2755
2756       // Check that the instruction return type is vectorizable.
2757       if (!VectorType::isValidElementType(it->getType()) &&
2758           !it->getType()->isVoidTy()) {
2759         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2760         return false;
2761       }
2762
2763       // Check that the stored type is vectorizable.
2764       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2765         Type *T = ST->getValueOperand()->getType();
2766         if (!VectorType::isValidElementType(T))
2767           return false;
2768       }
2769
2770       // Reduction instructions are allowed to have exit users.
2771       // All other instructions must not have external users.
2772       if (!AllowedExit.count(it))
2773         //Check that all of the users of the loop are inside the BB.
2774         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2775              I != E; ++I) {
2776           Instruction *U = cast<Instruction>(*I);
2777           // This user may be a reduction exit value.
2778           if (!TheLoop->contains(U)) {
2779             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2780             return false;
2781           }
2782         }
2783     } // next instr.
2784
2785   }
2786
2787   if (!Induction) {
2788     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2789     if (Inductions.empty())
2790       return false;
2791   }
2792
2793   return true;
2794 }
2795
2796 void LoopVectorizationLegality::collectLoopUniforms() {
2797   // We now know that the loop is vectorizable!
2798   // Collect variables that will remain uniform after vectorization.
2799   std::vector<Value*> Worklist;
2800   BasicBlock *Latch = TheLoop->getLoopLatch();
2801
2802   // Start with the conditional branch and walk up the block.
2803   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2804
2805   while (Worklist.size()) {
2806     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2807     Worklist.pop_back();
2808
2809     // Look at instructions inside this loop.
2810     // Stop when reaching PHI nodes.
2811     // TODO: we need to follow values all over the loop, not only in this block.
2812     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2813       continue;
2814
2815     // This is a known uniform.
2816     Uniforms.insert(I);
2817
2818     // Insert all operands.
2819     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
2820   }
2821 }
2822
2823 AliasAnalysis::Location
2824 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2825   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2826     return AA->getLocation(Store);
2827   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2828     return AA->getLocation(Load);
2829
2830   llvm_unreachable("Should be either load or store instruction");
2831 }
2832
2833 bool
2834 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2835                                                 Value *Object,
2836                                                 Instruction *Inst,
2837                                                 AliasMultiMap& WriteObjects,
2838                                                 unsigned MaxByteWidth) {
2839
2840   AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2841
2842   std::vector<Instruction*>::iterator
2843               it = WriteObjects[Object].begin(),
2844               end = WriteObjects[Object].end();
2845
2846   for (; it != end; ++it) {
2847     Instruction* I = *it;
2848     if (I == Inst)
2849       continue;
2850
2851     AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2852     if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2853                   ThatLoc.getWithNewSize(MaxByteWidth)))
2854       return true;
2855   }
2856   return false;
2857 }
2858
2859 bool LoopVectorizationLegality::canVectorizeMemory() {
2860
2861   typedef SmallVector<Value*, 16> ValueVector;
2862   typedef SmallPtrSet<Value*, 16> ValueSet;
2863   // Holds the Load and Store *instructions*.
2864   ValueVector Loads;
2865   ValueVector Stores;
2866   PtrRtCheck.Pointers.clear();
2867   PtrRtCheck.Need = false;
2868
2869   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2870
2871   // For each block.
2872   for (Loop::block_iterator bb = TheLoop->block_begin(),
2873        be = TheLoop->block_end(); bb != be; ++bb) {
2874
2875     // Scan the BB and collect legal loads and stores.
2876     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2877          ++it) {
2878
2879       // If this is a load, save it. If this instruction can read from memory
2880       // but is not a load, then we quit. Notice that we don't handle function
2881       // calls that read or write.
2882       if (it->mayReadFromMemory()) {
2883         LoadInst *Ld = dyn_cast<LoadInst>(it);
2884         if (!Ld) return false;
2885         if (!Ld->isSimple() && !IsAnnotatedParallel) {
2886           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2887           return false;
2888         }
2889         Loads.push_back(Ld);
2890         continue;
2891       }
2892
2893       // Save 'store' instructions. Abort if other instructions write to memory.
2894       if (it->mayWriteToMemory()) {
2895         StoreInst *St = dyn_cast<StoreInst>(it);
2896         if (!St) return false;
2897         if (!St->isSimple() && !IsAnnotatedParallel) {
2898           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2899           return false;
2900         }
2901         Stores.push_back(St);
2902       }
2903     } // next instr.
2904   } // next block.
2905
2906   // Now we have two lists that hold the loads and the stores.
2907   // Next, we find the pointers that they use.
2908
2909   // Check if we see any stores. If there are no stores, then we don't
2910   // care if the pointers are *restrict*.
2911   if (!Stores.size()) {
2912     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2913     return true;
2914   }
2915
2916   // Holds the read and read-write *pointers* that we find. These maps hold
2917   // unique values for pointers (so no need for multi-map).
2918   AliasMap Reads;
2919   AliasMap ReadWrites;
2920
2921   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2922   // multiple times on the same object. If the ptr is accessed twice, once
2923   // for read and once for write, it will only appear once (on the write
2924   // list). This is okay, since we are going to check for conflicts between
2925   // writes and between reads and writes, but not between reads and reads.
2926   ValueSet Seen;
2927
2928   ValueVector::iterator I, IE;
2929   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2930     StoreInst *ST = cast<StoreInst>(*I);
2931     Value* Ptr = ST->getPointerOperand();
2932
2933     if (isUniform(Ptr)) {
2934       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2935       return false;
2936     }
2937
2938     // If we did *not* see this pointer before, insert it to
2939     // the read-write list. At this phase it is only a 'write' list.
2940     if (Seen.insert(Ptr))
2941       ReadWrites.insert(std::make_pair(Ptr, ST));
2942   }
2943
2944   if (IsAnnotatedParallel) {
2945     DEBUG(dbgs()
2946           << "LV: A loop annotated parallel, ignore memory dependency "
2947           << "checks.\n");
2948     return true;
2949   }
2950
2951   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2952     LoadInst *LD = cast<LoadInst>(*I);
2953     Value* Ptr = LD->getPointerOperand();
2954     // If we did *not* see this pointer before, insert it to the
2955     // read list. If we *did* see it before, then it is already in
2956     // the read-write list. This allows us to vectorize expressions
2957     // such as A[i] += x;  Because the address of A[i] is a read-write
2958     // pointer. This only works if the index of A[i] is consecutive.
2959     // If the address of i is unknown (for example A[B[i]]) then we may
2960     // read a few words, modify, and write a few words, and some of the
2961     // words may be written to the same address.
2962     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2963       Reads.insert(std::make_pair(Ptr, LD));
2964   }
2965
2966   // If we write (or read-write) to a single destination and there are no
2967   // other reads in this loop then is it safe to vectorize.
2968   if (ReadWrites.size() == 1 && Reads.size() == 0) {
2969     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2970     return true;
2971   }
2972
2973   unsigned NumReadPtrs = 0;
2974   unsigned NumWritePtrs = 0;
2975
2976   // Find pointers with computable bounds. We are going to use this information
2977   // to place a runtime bound check.
2978   bool CanDoRT = true;
2979   AliasMap::iterator MI, ME;
2980   for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2981     Value *V = (*MI).first;
2982     if (hasComputableBounds(V)) {
2983       PtrRtCheck.insert(SE, TheLoop, V, true);
2984       NumWritePtrs++;
2985       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2986     } else {
2987       CanDoRT = false;
2988       break;
2989     }
2990   }
2991   for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2992     Value *V = (*MI).first;
2993     if (hasComputableBounds(V)) {
2994       PtrRtCheck.insert(SE, TheLoop, V, false);
2995       NumReadPtrs++;
2996       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2997     } else {
2998       CanDoRT = false;
2999       break;
3000     }
3001   }
3002
3003   // Check that we did not collect too many pointers or found a
3004   // unsizeable pointer.
3005   unsigned NumComparisons = (NumWritePtrs * (NumReadPtrs + NumWritePtrs - 1));
3006   DEBUG(dbgs() << "LV: We need to compare " << NumComparisons << " ptrs.\n");
3007   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
3008     PtrRtCheck.reset();
3009     CanDoRT = false;
3010   }
3011
3012   if (CanDoRT) {
3013     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
3014   }
3015
3016   bool NeedRTCheck = false;
3017
3018   // Biggest vectorized access possible, vector width * unroll factor.
3019   // TODO: We're being very pessimistic here, find a way to know the
3020   // real access width before getting here.
3021   unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
3022                            TTI->getMaximumUnrollFactor();
3023   // Now that the pointers are in two lists (Reads and ReadWrites), we
3024   // can check that there are no conflicts between each of the writes and
3025   // between the writes to the reads.
3026   // Note that WriteObjects duplicates the stores (indexed now by underlying
3027   // objects) to avoid pointing to elements inside ReadWrites.
3028   // TODO: Maybe create a new type where they can interact without duplication.
3029   AliasMultiMap WriteObjects;
3030   ValueVector TempObjects;
3031
3032   // Check that the read-writes do not conflict with other read-write
3033   // pointers.
3034   bool AllWritesIdentified = true;
3035   for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
3036     Value *Val = (*MI).first;
3037     Instruction *Inst = (*MI).second;
3038
3039     GetUnderlyingObjects(Val, TempObjects, DL);
3040     for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
3041          UI != UE; ++UI) {
3042       if (!isIdentifiedObject(*UI)) {
3043         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
3044         NeedRTCheck = true;
3045         AllWritesIdentified = false;
3046       }
3047
3048       // Never seen it before, can't alias.
3049       if (WriteObjects[*UI].empty()) {
3050         DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
3051         WriteObjects[*UI].push_back(Inst);
3052         continue;
3053       }
3054       // Direct alias found.
3055       if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
3056         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
3057               << **UI <<"\n");
3058         return false;
3059       }
3060       DEBUG(dbgs() << "LV: Found a conflicting global value:"
3061             << **UI <<"\n");
3062       DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
3063       DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
3064
3065       // If global alias, make sure they do alias.
3066       if (hasPossibleGlobalWriteReorder(*UI,
3067                                         Inst,
3068                                         WriteObjects,
3069                                         MaxByteWidth)) {
3070         DEBUG(dbgs() << "LV: Found a possible write-write reorder:" << **UI
3071                      << "\n");
3072         return false;
3073       }
3074
3075       // Didn't alias, insert into map for further reference.
3076       WriteObjects[*UI].push_back(Inst);
3077     }
3078     TempObjects.clear();
3079   }
3080
3081   /// Check that the reads don't conflict with the read-writes.
3082   for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
3083     Value *Val = (*MI).first;
3084     GetUnderlyingObjects(Val, TempObjects, DL);
3085     for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
3086          UI != UE; ++UI) {
3087       // If all of the writes are identified then we don't care if the read
3088       // pointer is identified or not.
3089       if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
3090         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
3091         NeedRTCheck = true;
3092       }
3093
3094       // Never seen it before, can't alias.
3095       if (WriteObjects[*UI].empty())
3096         continue;
3097       // Direct alias found.
3098       if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
3099         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
3100               << **UI <<"\n");
3101         return false;
3102       }
3103       DEBUG(dbgs() << "LV: Found a global value:  "
3104             << **UI <<"\n");
3105       Instruction *Inst = (*MI).second;
3106       DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
3107       DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
3108
3109       // If global alias, make sure they do alias.
3110       if (hasPossibleGlobalWriteReorder(*UI,
3111                                         Inst,
3112                                         WriteObjects,
3113                                         MaxByteWidth)) {
3114         DEBUG(dbgs() << "LV: Found a possible read-write reorder:" << **UI
3115                      << "\n");
3116         return false;
3117       }
3118     }
3119     TempObjects.clear();
3120   }
3121
3122   PtrRtCheck.Need = NeedRTCheck;
3123   if (NeedRTCheck && !CanDoRT) {
3124     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
3125           "the array bounds.\n");
3126     PtrRtCheck.reset();
3127     return false;
3128   }
3129
3130   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
3131         " need a runtime memory check.\n");
3132   return true;
3133 }
3134
3135 static bool hasMultipleUsesOf(Instruction *I,
3136                               SmallPtrSet<Instruction *, 8> &Insts) {
3137   unsigned NumUses = 0;
3138   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3139     if (Insts.count(dyn_cast<Instruction>(*Use)))
3140       ++NumUses;
3141     if (NumUses > 1)
3142       return true;
3143   }
3144
3145   return false;
3146 }
3147
3148 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
3149   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3150     if (!Set.count(dyn_cast<Instruction>(*Use)))
3151       return false;
3152   return true;
3153 }
3154
3155 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3156                                                 ReductionKind Kind) {
3157   if (Phi->getNumIncomingValues() != 2)
3158     return false;
3159
3160   // Reduction variables are only found in the loop header block.
3161   if (Phi->getParent() != TheLoop->getHeader())
3162     return false;
3163
3164   // Obtain the reduction start value from the value that comes from the loop
3165   // preheader.
3166   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3167
3168   // ExitInstruction is the single value which is used outside the loop.
3169   // We only allow for a single reduction value to be used outside the loop.
3170   // This includes users of the reduction, variables (which form a cycle
3171   // which ends in the phi node).
3172   Instruction *ExitInstruction = 0;
3173   // Indicates that we found a reduction operation in our scan.
3174   bool FoundReduxOp = false;
3175
3176   // We start with the PHI node and scan for all of the users of this
3177   // instruction. All users must be instructions that can be used as reduction
3178   // variables (such as ADD). We must have a single out-of-block user. The cycle
3179   // must include the original PHI.
3180   bool FoundStartPHI = false;
3181
3182   // To recognize min/max patterns formed by a icmp select sequence, we store
3183   // the number of instruction we saw from the recognized min/max pattern,
3184   //  to make sure we only see exactly the two instructions.
3185   unsigned NumCmpSelectPatternInst = 0;
3186   ReductionInstDesc ReduxDesc(false, 0);
3187
3188   SmallPtrSet<Instruction *, 8> VisitedInsts;
3189   SmallVector<Instruction *, 8> Worklist;
3190   Worklist.push_back(Phi);
3191   VisitedInsts.insert(Phi);
3192
3193   // A value in the reduction can be used:
3194   //  - By the reduction:
3195   //      - Reduction operation:
3196   //        - One use of reduction value (safe).
3197   //        - Multiple use of reduction value (not safe).
3198   //      - PHI:
3199   //        - All uses of the PHI must be the reduction (safe).
3200   //        - Otherwise, not safe.
3201   //  - By one instruction outside of the loop (safe).
3202   //  - By further instructions outside of the loop (not safe).
3203   //  - By an instruction that is not part of the reduction (not safe).
3204   //    This is either:
3205   //      * An instruction type other than PHI or the reduction operation.
3206   //      * A PHI in the header other than the initial PHI.
3207   while (!Worklist.empty()) {
3208     Instruction *Cur = Worklist.back();
3209     Worklist.pop_back();
3210
3211     // No Users.
3212     // If the instruction has no users then this is a broken chain and can't be
3213     // a reduction variable.
3214     if (Cur->use_empty())
3215       return false;
3216
3217     bool IsAPhi = isa<PHINode>(Cur);
3218
3219     // A header PHI use other than the original PHI.
3220     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3221       return false;
3222
3223     // Reductions of instructions such as Div, and Sub is only possible if the
3224     // LHS is the reduction variable.
3225     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3226         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3227         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3228       return false;
3229
3230     // Any reduction instruction must be of one of the allowed kinds.
3231     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3232     if (!ReduxDesc.IsReduction)
3233       return false;
3234
3235     // A reduction operation must only have one use of the reduction value.
3236     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3237         hasMultipleUsesOf(Cur, VisitedInsts))
3238       return false;
3239
3240     // All inputs to a PHI node must be a reduction value.
3241     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3242       return false;
3243
3244     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3245                                      isa<SelectInst>(Cur)))
3246       ++NumCmpSelectPatternInst;
3247     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3248                                    isa<SelectInst>(Cur)))
3249       ++NumCmpSelectPatternInst;
3250
3251     // Check  whether we found a reduction operator.
3252     FoundReduxOp |= !IsAPhi;
3253
3254     // Process users of current instruction. Push non PHI nodes after PHI nodes
3255     // onto the stack. This way we are going to have seen all inputs to PHI
3256     // nodes once we get to them.
3257     SmallVector<Instruction *, 8> NonPHIs;
3258     SmallVector<Instruction *, 8> PHIs;
3259     for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3260          ++UI) {
3261       Instruction *Usr = cast<Instruction>(*UI);
3262
3263       // Check if we found the exit user.
3264       BasicBlock *Parent = Usr->getParent();
3265       if (!TheLoop->contains(Parent)) {
3266         // Exit if you find multiple outside users.
3267         if (ExitInstruction != 0)
3268           return false;
3269         ExitInstruction = Cur;
3270         continue;
3271       }
3272
3273       // Process instructions only once (termination).
3274       if (VisitedInsts.insert(Usr)) {
3275         if (isa<PHINode>(Usr))
3276           PHIs.push_back(Usr);
3277         else
3278           NonPHIs.push_back(Usr);
3279       }
3280       // Remember that we completed the cycle.
3281       if (Usr == Phi)
3282         FoundStartPHI = true;
3283     }
3284     Worklist.append(PHIs.begin(), PHIs.end());
3285     Worklist.append(NonPHIs.begin(), NonPHIs.end());
3286   }
3287
3288   // This means we have seen one but not the other instruction of the
3289   // pattern or more than just a select and cmp.
3290   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3291       NumCmpSelectPatternInst != 2)
3292     return false;
3293
3294   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3295     return false;
3296
3297   // We found a reduction var if we have reached the original phi node and we
3298   // only have a single instruction with out-of-loop users.
3299
3300   // This instruction is allowed to have out-of-loop users.
3301   AllowedExit.insert(ExitInstruction);
3302
3303   // Save the description of this reduction variable.
3304   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3305                          ReduxDesc.MinMaxKind);
3306   Reductions[Phi] = RD;
3307   // We've ended the cycle. This is a reduction variable if we have an
3308   // outside user and it has a binary op.
3309
3310   return true;
3311 }
3312
3313 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3314 /// pattern corresponding to a min(X, Y) or max(X, Y).
3315 LoopVectorizationLegality::ReductionInstDesc
3316 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3317                                                     ReductionInstDesc &Prev) {
3318
3319   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3320          "Expect a select instruction");
3321   Instruction *Cmp = 0;
3322   SelectInst *Select = 0;
3323
3324   // We must handle the select(cmp()) as a single instruction. Advance to the
3325   // select.
3326   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
3327     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
3328       return ReductionInstDesc(false, I);
3329     return ReductionInstDesc(Select, Prev.MinMaxKind);
3330   }
3331
3332   // Only handle single use cases for now.
3333   if (!(Select = dyn_cast<SelectInst>(I)))
3334     return ReductionInstDesc(false, I);
3335   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
3336       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
3337     return ReductionInstDesc(false, I);
3338   if (!Cmp->hasOneUse())
3339     return ReductionInstDesc(false, I);
3340
3341   Value *CmpLeft;
3342   Value *CmpRight;
3343
3344   // Look for a min/max pattern.
3345   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3346     return ReductionInstDesc(Select, MRK_UIntMin);
3347   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3348     return ReductionInstDesc(Select, MRK_UIntMax);
3349   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3350     return ReductionInstDesc(Select, MRK_SIntMax);
3351   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3352     return ReductionInstDesc(Select, MRK_SIntMin);
3353   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3354     return ReductionInstDesc(Select, MRK_FloatMin);
3355   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3356     return ReductionInstDesc(Select, MRK_FloatMax);
3357   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3358     return ReductionInstDesc(Select, MRK_FloatMin);
3359   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3360     return ReductionInstDesc(Select, MRK_FloatMax);
3361
3362   return ReductionInstDesc(false, I);
3363 }
3364
3365 LoopVectorizationLegality::ReductionInstDesc
3366 LoopVectorizationLegality::isReductionInstr(Instruction *I,
3367                                             ReductionKind Kind,
3368                                             ReductionInstDesc &Prev) {
3369   bool FP = I->getType()->isFloatingPointTy();
3370   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
3371   switch (I->getOpcode()) {
3372   default:
3373     return ReductionInstDesc(false, I);
3374   case Instruction::PHI:
3375       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
3376                  Kind != RK_FloatMinMax))
3377         return ReductionInstDesc(false, I);
3378     return ReductionInstDesc(I, Prev.MinMaxKind);
3379   case Instruction::Sub:
3380   case Instruction::Add:
3381     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
3382   case Instruction::Mul:
3383     return ReductionInstDesc(Kind == RK_IntegerMult, I);
3384   case Instruction::And:
3385     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
3386   case Instruction::Or:
3387     return ReductionInstDesc(Kind == RK_IntegerOr, I);
3388   case Instruction::Xor:
3389     return ReductionInstDesc(Kind == RK_IntegerXor, I);
3390   case Instruction::FMul:
3391     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
3392   case Instruction::FAdd:
3393     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
3394   case Instruction::FCmp:
3395   case Instruction::ICmp:
3396   case Instruction::Select:
3397     if (Kind != RK_IntegerMinMax &&
3398         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
3399       return ReductionInstDesc(false, I);
3400     return isMinMaxSelectCmpPattern(I, Prev);
3401   }
3402 }
3403
3404 LoopVectorizationLegality::InductionKind
3405 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
3406   Type *PhiTy = Phi->getType();
3407   // We only handle integer and pointer inductions variables.
3408   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3409     return IK_NoInduction;
3410
3411   // Check that the PHI is consecutive.
3412   const SCEV *PhiScev = SE->getSCEV(Phi);
3413   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3414   if (!AR) {
3415     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3416     return IK_NoInduction;
3417   }
3418   const SCEV *Step = AR->getStepRecurrence(*SE);
3419
3420   // Integer inductions need to have a stride of one.
3421   if (PhiTy->isIntegerTy()) {
3422     if (Step->isOne())
3423       return IK_IntInduction;
3424     if (Step->isAllOnesValue())
3425       return IK_ReverseIntInduction;
3426     return IK_NoInduction;
3427   }
3428
3429   // Calculate the pointer stride and check if it is consecutive.
3430   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3431   if (!C)
3432     return IK_NoInduction;
3433
3434   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
3435   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
3436   if (C->getValue()->equalsInt(Size))
3437     return IK_PtrInduction;
3438   else if (C->getValue()->equalsInt(0 - Size))
3439     return IK_ReversePtrInduction;
3440
3441   return IK_NoInduction;
3442 }
3443
3444 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
3445   Value *In0 = const_cast<Value*>(V);
3446   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
3447   if (!PN)
3448     return false;
3449
3450   return Inductions.count(PN);
3451 }
3452
3453 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
3454   assert(TheLoop->contains(BB) && "Unknown block used");
3455
3456   // Blocks that do not dominate the latch need predication.
3457   BasicBlock* Latch = TheLoop->getLoopLatch();
3458   return !DT->dominates(BB, Latch);
3459 }
3460
3461 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
3462   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3463     // We might be able to hoist the load.
3464     if (it->mayReadFromMemory() && !LoadSpeculation.isHoistableLoad(it))
3465       return false;
3466
3467     // We don't predicate stores at the moment.
3468     if (it->mayWriteToMemory() || it->mayThrow())
3469       return false;
3470
3471     // The instructions below can trap.
3472     switch (it->getOpcode()) {
3473     default: continue;
3474     case Instruction::UDiv:
3475     case Instruction::SDiv:
3476     case Instruction::URem:
3477     case Instruction::SRem:
3478              return false;
3479     }
3480   }
3481
3482   return true;
3483 }
3484
3485 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
3486   const SCEV *PhiScev = SE->getSCEV(Ptr);
3487   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3488   if (!AR)
3489     return false;
3490
3491   return AR->isAffine();
3492 }
3493
3494 LoopVectorizationCostModel::VectorizationFactor
3495 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
3496                                                       unsigned UserVF) {
3497   // Width 1 means no vectorize
3498   VectorizationFactor Factor = { 1U, 0U };
3499   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
3500     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
3501     return Factor;
3502   }
3503
3504   // Find the trip count.
3505   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
3506   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
3507
3508   unsigned WidestType = getWidestType();
3509   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
3510   unsigned MaxVectorSize = WidestRegister / WidestType;
3511   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
3512   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
3513
3514   if (MaxVectorSize == 0) {
3515     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
3516     MaxVectorSize = 1;
3517   }
3518
3519   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
3520          " into one vector!");
3521
3522   unsigned VF = MaxVectorSize;
3523
3524   // If we optimize the program for size, avoid creating the tail loop.
3525   if (OptForSize) {
3526     // If we are unable to calculate the trip count then don't try to vectorize.
3527     if (TC < 2) {
3528       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3529       return Factor;
3530     }
3531
3532     // Find the maximum SIMD width that can fit within the trip count.
3533     VF = TC % MaxVectorSize;
3534
3535     if (VF == 0)
3536       VF = MaxVectorSize;
3537
3538     // If the trip count that we found modulo the vectorization factor is not
3539     // zero then we require a tail.
3540     if (VF < 2) {
3541       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3542       return Factor;
3543     }
3544   }
3545
3546   if (UserVF != 0) {
3547     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
3548     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
3549
3550     Factor.Width = UserVF;
3551     return Factor;
3552   }
3553
3554   float Cost = expectedCost(1);
3555   unsigned Width = 1;
3556   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
3557   for (unsigned i=2; i <= VF; i*=2) {
3558     // Notice that the vector loop needs to be executed less times, so
3559     // we need to divide the cost of the vector loops by the width of
3560     // the vector elements.
3561     float VectorCost = expectedCost(i) / (float)i;
3562     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3563           (int)VectorCost << ".\n");
3564     if (VectorCost < Cost) {
3565       Cost = VectorCost;
3566       Width = i;
3567     }
3568   }
3569
3570   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3571   Factor.Width = Width;
3572   Factor.Cost = Width * Cost;
3573   return Factor;
3574 }
3575
3576 unsigned LoopVectorizationCostModel::getWidestType() {
3577   unsigned MaxWidth = 8;
3578
3579   // For each block.
3580   for (Loop::block_iterator bb = TheLoop->block_begin(),
3581        be = TheLoop->block_end(); bb != be; ++bb) {
3582     BasicBlock *BB = *bb;
3583
3584     // For each instruction in the loop.
3585     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3586       Type *T = it->getType();
3587
3588       // Only examine Loads, Stores and PHINodes.
3589       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3590         continue;
3591
3592       // Examine PHI nodes that are reduction variables.
3593       if (PHINode *PN = dyn_cast<PHINode>(it))
3594         if (!Legal->getReductionVars()->count(PN))
3595           continue;
3596
3597       // Examine the stored values.
3598       if (StoreInst *ST = dyn_cast<StoreInst>(it))
3599         T = ST->getValueOperand()->getType();
3600
3601       // Ignore loaded pointer types and stored pointer types that are not
3602       // consecutive. However, we do want to take consecutive stores/loads of
3603       // pointer vectors into account.
3604       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3605         continue;
3606
3607       MaxWidth = std::max(MaxWidth,
3608                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3609     }
3610   }
3611
3612   return MaxWidth;
3613 }
3614
3615 unsigned
3616 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3617                                                unsigned UserUF,
3618                                                unsigned VF,
3619                                                unsigned LoopCost) {
3620
3621   // -- The unroll heuristics --
3622   // We unroll the loop in order to expose ILP and reduce the loop overhead.
3623   // There are many micro-architectural considerations that we can't predict
3624   // at this level. For example frontend pressure (on decode or fetch) due to
3625   // code size, or the number and capabilities of the execution ports.
3626   //
3627   // We use the following heuristics to select the unroll factor:
3628   // 1. If the code has reductions the we unroll in order to break the cross
3629   // iteration dependency.
3630   // 2. If the loop is really small then we unroll in order to reduce the loop
3631   // overhead.
3632   // 3. We don't unroll if we think that we will spill registers to memory due
3633   // to the increased register pressure.
3634
3635   // Use the user preference, unless 'auto' is selected.
3636   if (UserUF != 0)
3637     return UserUF;
3638
3639   // When we optimize for size we don't unroll.
3640   if (OptForSize)
3641     return 1;
3642
3643   // Do not unroll loops with a relatively small trip count.
3644   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3645                                               TheLoop->getLoopLatch());
3646   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3647     return 1;
3648
3649   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3650   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3651         " vector registers\n");
3652
3653   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3654   // We divide by these constants so assume that we have at least one
3655   // instruction that uses at least one register.
3656   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3657   R.NumInstructions = std::max(R.NumInstructions, 1U);
3658
3659   // We calculate the unroll factor using the following formula.
3660   // Subtract the number of loop invariants from the number of available
3661   // registers. These registers are used by all of the unrolled instances.
3662   // Next, divide the remaining registers by the number of registers that is
3663   // required by the loop, in order to estimate how many parallel instances
3664   // fit without causing spills.
3665   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3666
3667   // Clamp the unroll factor ranges to reasonable factors.
3668   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3669
3670   // If we did not calculate the cost for VF (because the user selected the VF)
3671   // then we calculate the cost of VF here.
3672   if (LoopCost == 0)
3673     LoopCost = expectedCost(VF);
3674
3675   // Clamp the calculated UF to be between the 1 and the max unroll factor
3676   // that the target allows.
3677   if (UF > MaxUnrollSize)
3678     UF = MaxUnrollSize;
3679   else if (UF < 1)
3680     UF = 1;
3681
3682   if (Legal->getReductionVars()->size()) {
3683     DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3684     return UF;
3685   }
3686
3687   // We want to unroll tiny loops in order to reduce the loop overhead.
3688   // We assume that the cost overhead is 1 and we use the cost model
3689   // to estimate the cost of the loop and unroll until the cost of the
3690   // loop overhead is about 5% of the cost of the loop.
3691   DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3692   if (LoopCost < 20) {
3693     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3694     unsigned NewUF = 20/LoopCost + 1;
3695     return std::min(NewUF, UF);
3696   }
3697
3698   DEBUG(dbgs() << "LV: Not Unrolling. \n");
3699   return 1;
3700 }
3701
3702 LoopVectorizationCostModel::RegisterUsage
3703 LoopVectorizationCostModel::calculateRegisterUsage() {
3704   // This function calculates the register usage by measuring the highest number
3705   // of values that are alive at a single location. Obviously, this is a very
3706   // rough estimation. We scan the loop in a topological order in order and
3707   // assign a number to each instruction. We use RPO to ensure that defs are
3708   // met before their users. We assume that each instruction that has in-loop
3709   // users starts an interval. We record every time that an in-loop value is
3710   // used, so we have a list of the first and last occurrences of each
3711   // instruction. Next, we transpose this data structure into a multi map that
3712   // holds the list of intervals that *end* at a specific location. This multi
3713   // map allows us to perform a linear search. We scan the instructions linearly
3714   // and record each time that a new interval starts, by placing it in a set.
3715   // If we find this value in the multi-map then we remove it from the set.
3716   // The max register usage is the maximum size of the set.
3717   // We also search for instructions that are defined outside the loop, but are
3718   // used inside the loop. We need this number separately from the max-interval
3719   // usage number because when we unroll, loop-invariant values do not take
3720   // more register.
3721   LoopBlocksDFS DFS(TheLoop);
3722   DFS.perform(LI);
3723
3724   RegisterUsage R;
3725   R.NumInstructions = 0;
3726
3727   // Each 'key' in the map opens a new interval. The values
3728   // of the map are the index of the 'last seen' usage of the
3729   // instruction that is the key.
3730   typedef DenseMap<Instruction*, unsigned> IntervalMap;
3731   // Maps instruction to its index.
3732   DenseMap<unsigned, Instruction*> IdxToInstr;
3733   // Marks the end of each interval.
3734   IntervalMap EndPoint;
3735   // Saves the list of instruction indices that are used in the loop.
3736   SmallSet<Instruction*, 8> Ends;
3737   // Saves the list of values that are used in the loop but are
3738   // defined outside the loop, such as arguments and constants.
3739   SmallPtrSet<Value*, 8> LoopInvariants;
3740
3741   unsigned Index = 0;
3742   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3743        be = DFS.endRPO(); bb != be; ++bb) {
3744     R.NumInstructions += (*bb)->size();
3745     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3746          ++it) {
3747       Instruction *I = it;
3748       IdxToInstr[Index++] = I;
3749
3750       // Save the end location of each USE.
3751       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3752         Value *U = I->getOperand(i);
3753         Instruction *Instr = dyn_cast<Instruction>(U);
3754
3755         // Ignore non-instruction values such as arguments, constants, etc.
3756         if (!Instr) continue;
3757
3758         // If this instruction is outside the loop then record it and continue.
3759         if (!TheLoop->contains(Instr)) {
3760           LoopInvariants.insert(Instr);
3761           continue;
3762         }
3763
3764         // Overwrite previous end points.
3765         EndPoint[Instr] = Index;
3766         Ends.insert(Instr);
3767       }
3768     }
3769   }
3770
3771   // Saves the list of intervals that end with the index in 'key'.
3772   typedef SmallVector<Instruction*, 2> InstrList;
3773   DenseMap<unsigned, InstrList> TransposeEnds;
3774
3775   // Transpose the EndPoints to a list of values that end at each index.
3776   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3777        it != e; ++it)
3778     TransposeEnds[it->second].push_back(it->first);
3779
3780   SmallSet<Instruction*, 8> OpenIntervals;
3781   unsigned MaxUsage = 0;
3782
3783
3784   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3785   for (unsigned int i = 0; i < Index; ++i) {
3786     Instruction *I = IdxToInstr[i];
3787     // Ignore instructions that are never used within the loop.
3788     if (!Ends.count(I)) continue;
3789
3790     // Remove all of the instructions that end at this location.
3791     InstrList &List = TransposeEnds[i];
3792     for (unsigned int j=0, e = List.size(); j < e; ++j)
3793       OpenIntervals.erase(List[j]);
3794
3795     // Count the number of live interals.
3796     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3797
3798     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3799           OpenIntervals.size() <<"\n");
3800
3801     // Add the current instruction to the list of open intervals.
3802     OpenIntervals.insert(I);
3803   }
3804
3805   unsigned Invariant = LoopInvariants.size();
3806   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3807   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3808   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3809
3810   R.LoopInvariantRegs = Invariant;
3811   R.MaxLocalUsers = MaxUsage;
3812   return R;
3813 }
3814
3815 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3816   unsigned Cost = 0;
3817
3818   // For each block.
3819   for (Loop::block_iterator bb = TheLoop->block_begin(),
3820        be = TheLoop->block_end(); bb != be; ++bb) {
3821     unsigned BlockCost = 0;
3822     BasicBlock *BB = *bb;
3823
3824     // For each instruction in the old loop.
3825     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3826       // Skip dbg intrinsics.
3827       if (isa<DbgInfoIntrinsic>(it))
3828         continue;
3829
3830       unsigned C = getInstructionCost(it, VF);
3831       Cost += C;
3832       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3833             VF << " For instruction: "<< *it << "\n");
3834     }
3835
3836     // We assume that if-converted blocks have a 50% chance of being executed.
3837     // When the code is scalar then some of the blocks are avoided due to CF.
3838     // When the code is vectorized we execute all code paths.
3839     if (Legal->blockNeedsPredication(*bb) && VF == 1)
3840       BlockCost /= 2;
3841
3842     Cost += BlockCost;
3843   }
3844
3845   return Cost;
3846 }
3847
3848 unsigned
3849 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3850   // If we know that this instruction will remain uniform, check the cost of
3851   // the scalar version.
3852   if (Legal->isUniformAfterVectorization(I))
3853     VF = 1;
3854
3855   Type *RetTy = I->getType();
3856   Type *VectorTy = ToVectorTy(RetTy, VF);
3857
3858   // TODO: We need to estimate the cost of intrinsic calls.
3859   switch (I->getOpcode()) {
3860   case Instruction::GetElementPtr:
3861     // We mark this instruction as zero-cost because the cost of GEPs in
3862     // vectorized code depends on whether the corresponding memory instruction
3863     // is scalarized or not. Therefore, we handle GEPs with the memory
3864     // instruction cost.
3865     return 0;
3866   case Instruction::Br: {
3867     return TTI.getCFInstrCost(I->getOpcode());
3868   }
3869   case Instruction::PHI:
3870     //TODO: IF-converted IFs become selects.
3871     return 0;
3872   case Instruction::Add:
3873   case Instruction::FAdd:
3874   case Instruction::Sub:
3875   case Instruction::FSub:
3876   case Instruction::Mul:
3877   case Instruction::FMul:
3878   case Instruction::UDiv:
3879   case Instruction::SDiv:
3880   case Instruction::FDiv:
3881   case Instruction::URem:
3882   case Instruction::SRem:
3883   case Instruction::FRem:
3884   case Instruction::Shl:
3885   case Instruction::LShr:
3886   case Instruction::AShr:
3887   case Instruction::And:
3888   case Instruction::Or:
3889   case Instruction::Xor: {
3890     // Certain instructions can be cheaper to vectorize if they have a constant
3891     // second vector operand. One example of this are shifts on x86.
3892     TargetTransformInfo::OperandValueKind Op1VK =
3893       TargetTransformInfo::OK_AnyValue;
3894     TargetTransformInfo::OperandValueKind Op2VK =
3895       TargetTransformInfo::OK_AnyValue;
3896
3897     if (isa<ConstantInt>(I->getOperand(1)))
3898       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
3899
3900     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
3901   }
3902   case Instruction::Select: {
3903     SelectInst *SI = cast<SelectInst>(I);
3904     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3905     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3906     Type *CondTy = SI->getCondition()->getType();
3907     if (!ScalarCond)
3908       CondTy = VectorType::get(CondTy, VF);
3909
3910     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3911   }
3912   case Instruction::ICmp:
3913   case Instruction::FCmp: {
3914     Type *ValTy = I->getOperand(0)->getType();
3915     VectorTy = ToVectorTy(ValTy, VF);
3916     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3917   }
3918   case Instruction::Store:
3919   case Instruction::Load: {
3920     StoreInst *SI = dyn_cast<StoreInst>(I);
3921     LoadInst *LI = dyn_cast<LoadInst>(I);
3922     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3923                    LI->getType());
3924     VectorTy = ToVectorTy(ValTy, VF);
3925
3926     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3927     unsigned AS = SI ? SI->getPointerAddressSpace() :
3928       LI->getPointerAddressSpace();
3929     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3930     // We add the cost of address computation here instead of with the gep
3931     // instruction because only here we know whether the operation is
3932     // scalarized.
3933     if (VF == 1)
3934       return TTI.getAddressComputationCost(VectorTy) +
3935         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3936
3937     // Scalarized loads/stores.
3938     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
3939     bool Reverse = ConsecutiveStride < 0;
3940     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
3941     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
3942     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
3943       unsigned Cost = 0;
3944       // The cost of extracting from the value vector and pointer vector.
3945       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3946       for (unsigned i = 0; i < VF; ++i) {
3947         //  The cost of extracting the pointer operand.
3948         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3949         // In case of STORE, the cost of ExtractElement from the vector.
3950         // In case of LOAD, the cost of InsertElement into the returned
3951         // vector.
3952         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3953                                             Instruction::InsertElement,
3954                                             VectorTy, i);
3955       }
3956
3957       // The cost of the scalar loads/stores.
3958       Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3959       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3960                                        Alignment, AS);
3961       return Cost;
3962     }
3963
3964     // Wide load/stores.
3965     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3966     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3967
3968     if (Reverse)
3969       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3970                                   VectorTy, 0);
3971     return Cost;
3972   }
3973   case Instruction::ZExt:
3974   case Instruction::SExt:
3975   case Instruction::FPToUI:
3976   case Instruction::FPToSI:
3977   case Instruction::FPExt:
3978   case Instruction::PtrToInt:
3979   case Instruction::IntToPtr:
3980   case Instruction::SIToFP:
3981   case Instruction::UIToFP:
3982   case Instruction::Trunc:
3983   case Instruction::FPTrunc:
3984   case Instruction::BitCast: {
3985     // We optimize the truncation of induction variable.
3986     // The cost of these is the same as the scalar operation.
3987     if (I->getOpcode() == Instruction::Trunc &&
3988         Legal->isInductionVariable(I->getOperand(0)))
3989       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3990                                   I->getOperand(0)->getType());
3991
3992     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3993     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3994   }
3995   case Instruction::Call: {
3996     CallInst *CI = cast<CallInst>(I);
3997     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3998     assert(ID && "Not an intrinsic call!");
3999     Type *RetTy = ToVectorTy(CI->getType(), VF);
4000     SmallVector<Type*, 4> Tys;
4001     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4002       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4003     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4004   }
4005   default: {
4006     // We are scalarizing the instruction. Return the cost of the scalar
4007     // instruction, plus the cost of insert and extract into vector
4008     // elements, times the vector width.
4009     unsigned Cost = 0;
4010
4011     if (!RetTy->isVoidTy() && VF != 1) {
4012       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4013                                                 VectorTy);
4014       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4015                                                 VectorTy);
4016
4017       // The cost of inserting the results plus extracting each one of the
4018       // operands.
4019       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4020     }
4021
4022     // The cost of executing VF copies of the scalar instruction. This opcode
4023     // is unknown. Assume that it is the same as 'mul'.
4024     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4025     return Cost;
4026   }
4027   }// end of switch.
4028 }
4029
4030 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4031   if (Scalar->isVoidTy() || VF == 1)
4032     return Scalar;
4033   return VectorType::get(Scalar, VF);
4034 }
4035
4036 char LoopVectorize::ID = 0;
4037 static const char lv_name[] = "Loop Vectorization";
4038 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4039 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4040 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
4041 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4042 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4043 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4044
4045 namespace llvm {
4046   Pass *createLoopVectorizePass() {
4047     return new LoopVectorize();
4048   }
4049 }
4050
4051 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
4052   // Check for a store.
4053   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
4054     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
4055
4056   // Check for a load.
4057   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
4058     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
4059
4060   return false;
4061 }