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