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