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