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