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