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