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