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