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