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