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