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