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