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