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