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